Use filename instead of path
[platform/core/multimedia/libmedia-service.git] / src / common / media-svc-util.c
1 /*
2  * libmedia-service
3  *
4  * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  */
19
20 #include <unistd.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <fcntl.h>
24 #include <sys/stat.h>
25 #include <sys/vfs.h>
26 #include <ctype.h>
27 #include <aul/aul.h>
28 #include <mm_file.h>
29 #include <libexif/exif-data.h>
30 #include <media-util.h>
31 #include <uuid/uuid.h>
32 #include <mm_util_magick.h>
33 #include <media-thumbnail.h>
34 #include "media-svc-util.h"
35 #include "media-svc-db-utils.h"
36 #include "media-svc-debug.h"
37 #include "media-svc-env.h"
38 #include "media-svc-album.h"
39 /*For ebook metadata */
40 #include <zip.h>
41 #include <libxml/xmlmemory.h>
42 #include <libxml/parser.h>
43 #include <libxml/HTMLparser.h>
44 #include <dlfcn.h>
45
46 #define MEDIA_SVC_FILE_EXT_LEN_MAX                              6                       /**< Maximum file ext lenth*/
47
48 #define MUSIC_MIME_NUM 29
49 #define SOUND_MIME_NUM 2
50 #define MIME_LENGTH 50
51 #define MEDIA_SVC_DEFAULT_FORMAT_LEN 19
52 #define IMAGE_PREFIX "image/"
53 #define IMAGE_PREFIX_LEN 6
54 #define AUDIO_PREFIX "audio/"
55 #define AUDIO_PREFIX_LEN 6
56 #define VIDEO_PREFIX "video/"
57 #define VIDEO_PREFIX_LEN 6
58
59 #define MEDIA_SVC_PDF_TAG_TAIL_LEN 12
60 #define MEDIA_SVC_PDF_BUF_SIZE 256
61
62 #define MEDIA_SVC_THUMB_WIDTH 320
63 #define MEDIA_SVC_THUMB_HEIGHT 240
64
65 #define PATH_PLUGIN_LIB                         PATH_LIBDIR"/libmedia-ebook-plugin.so"
66
67 enum Exif_Orientation {
68         NOT_AVAILABLE = 0,
69         NORMAL = 1,
70         HFLIP = 2,
71         ROT_180 = 3,
72         VFLIP = 4,
73         TRANSPOSE = 5,
74         ROT_90 = 6,
75         TRANSVERSE = 7,
76         ROT_270 = 8
77 };
78
79 static const char music_mime_table[MUSIC_MIME_NUM][MIME_LENGTH] = {
80         /*known mime types of normal files*/
81         "mpeg",
82         "ogg",
83         "x-ms-wma",
84         "x-flac",
85         "mp4",
86         "mp3",
87         "x-mp3", /*alias of audio/mpeg*/
88         "x-mpeg", /*alias of audio/mpeg*/
89         "3gpp",
90         "x-ogg", /*alias of audio/ogg*/
91         "vnd.ms-playready.media.pya:*.pya", /*playready*/
92         "wma",
93         "aac",
94         "x-m4a", /*alias of audio/mp4*/
95         /* below mimes are rare*/
96         "x-vorbis+ogg",
97         "x-flac+ogg",
98         "x-matroska",
99         "ac3",
100         "mp2",
101         "x-ape",
102         "x-ms-asx",
103         "vnd.rn-realaudio",
104
105         "x-vorbis", /*alias of audio/x-vorbis+ogg*/
106         "vorbis", /*alias of audio/x-vorbis+ogg*/
107         "x-oggflac",
108         "x-mp2", /*alias of audio/mp2*/
109         "x-pn-realaudio", /*alias of audio/vnd.rn-realaudio*/
110         "vnd.m-realaudio", /*alias of audio/vnd.rn-realaudio*/
111         "x-wav",
112 };
113
114 static const char sound_mime_table[SOUND_MIME_NUM][MIME_LENGTH] = {
115         "application/x-smaf",
116         "text/x-iMelody"
117 };
118
119 static char *__media_info_generate_uuid(void)
120 {
121         uuid_t uuid_value;
122         char uuid_unparsed[37];
123
124 RETRY_GEN:
125         uuid_generate(uuid_value);
126         uuid_unparse(uuid_value, uuid_unparsed);
127
128         if (strlen(uuid_unparsed) < 36) {
129                 media_svc_debug("INVALID UUID : %s. RETRY GENERATE.", uuid_unparsed);
130                 goto RETRY_GEN;
131         }
132
133         return g_strdup(uuid_unparsed);
134 }
135
136 static int __media_svc_get_exif_info(ExifData *ed, char *buf, int *i_value, ExifTag tagtype)
137 {
138         ExifEntry *entry;
139         ExifByteOrder mByteOrder;
140
141         media_svc_retv_if(!ed, MS_MEDIA_ERR_INVALID_PARAMETER);
142
143         entry = exif_data_get_entry(ed, tagtype);
144         media_svc_retv_if(!entry, MS_MEDIA_ERR_NONE);
145
146         switch (tagtype) {
147         case EXIF_TAG_ORIENTATION:
148         case EXIF_TAG_PIXEL_X_DIMENSION:
149         case EXIF_TAG_PIXEL_Y_DIMENSION:
150                 media_svc_retvm_if(!i_value, MS_MEDIA_ERR_INVALID_PARAMETER, "i_value is NULL");
151
152                 mByteOrder = exif_data_get_byte_order(ed);
153                 short exif_value = exif_get_short(entry->data, mByteOrder);
154                 *i_value = (int)exif_value;
155                 break;
156         default:
157                 media_svc_retvm_if(!buf, MS_MEDIA_ERR_INVALID_PARAMETER, "buf is NULL");
158
159                 exif_entry_get_value(entry, buf, MEDIA_SVC_METADATA_LEN_MAX);
160                 buf[strlen(buf)] = '\0';
161         }
162
163         return MS_MEDIA_ERR_NONE;
164 }
165
166 static int __media_svc_get_media_type(const char *path, const char *mime_type, media_svc_media_type_e *media_type)
167 {
168         int idx = 0;
169         int audio = 0;
170         int video = 0;
171
172         media_svc_retvm_if(!path, MS_MEDIA_ERR_INVALID_PARAMETER, "path is null");
173         media_svc_retvm_if(!mime_type, MS_MEDIA_ERR_INVALID_PARAMETER, "mime_type is null");
174         media_svc_retvm_if(!media_type, MS_MEDIA_ERR_INVALID_PARAMETER, "media_type is null");
175
176         /* Image */
177         if (strncmp(mime_type, IMAGE_PREFIX, IMAGE_PREFIX_LEN) == 0) {
178                 *media_type = MEDIA_SVC_MEDIA_TYPE_IMAGE;
179                 return MS_MEDIA_ERR_NONE;
180         }
181
182         /* Audio */
183         if (strncmp(mime_type, AUDIO_PREFIX, AUDIO_PREFIX_LEN) == 0) {
184                 *media_type = MEDIA_SVC_MEDIA_TYPE_SOUND;
185
186                 for (idx = 0; idx < MUSIC_MIME_NUM; idx++) {
187                         if (strcmp(mime_type + AUDIO_PREFIX_LEN, music_mime_table[idx]) == 0) {
188                                 *media_type = MEDIA_SVC_MEDIA_TYPE_MUSIC;
189                                 break;
190                         }
191                 }
192
193                 /* audio/x-mpegurl : .m3u file (playlist file) */
194                 if (strcmp(mime_type + AUDIO_PREFIX_LEN, "x-mpegurl") == 0)
195                         *media_type = MEDIA_SVC_MEDIA_TYPE_OTHER;
196
197                 return MS_MEDIA_ERR_NONE;
198         }
199
200         /* Video */
201         if (strncmp(mime_type, VIDEO_PREFIX, VIDEO_PREFIX_LEN) == 0) {
202                 *media_type = MEDIA_SVC_MEDIA_TYPE_VIDEO;
203
204                 /*some video files don't have video stream. in this case it is categorize as music. */
205                 if (strcmp(mime_type + VIDEO_PREFIX_LEN, "3gpp") == 0 ||
206                         strcmp(mime_type + VIDEO_PREFIX_LEN, "mp4") == 0) {
207                         if (mm_file_get_stream_info(path, &audio, &video) == FILEINFO_ERROR_NONE) {
208                                 if (audio > 0 && video == 0)
209                                         *media_type = MEDIA_SVC_MEDIA_TYPE_MUSIC;
210                         }
211                 }
212
213                 return MS_MEDIA_ERR_NONE;
214         }
215
216         /* ETC */
217         *media_type = MEDIA_SVC_MEDIA_TYPE_OTHER;
218
219         for (idx = 0; idx < SOUND_MIME_NUM; idx++) {
220                 if (strcmp(mime_type, sound_mime_table[idx]) == 0) {
221                         *media_type = MEDIA_SVC_MEDIA_TYPE_SOUND;
222                         return MS_MEDIA_ERR_NONE;
223                 }
224         }
225
226         /*"asf" must check video stream and then categorize in directly. */
227         if (strcmp(mime_type, "application/vnd.ms-asf") == 0) {
228                 if (mm_file_get_stream_info(path, &audio, &video) == FILEINFO_ERROR_NONE) {
229                         if (audio > 0 && video == 0)
230                                 *media_type = MEDIA_SVC_MEDIA_TYPE_MUSIC;
231                         else
232                                 *media_type = MEDIA_SVC_MEDIA_TYPE_VIDEO;
233                 }
234
235                 return MS_MEDIA_ERR_NONE;
236         }
237
238         if (strcmp(mime_type, "application/epub+zip") == 0 || strcmp(mime_type, "application/pdf") == 0)
239                 *media_type = MEDIA_SVC_MEDIA_TYPE_BOOK;
240
241         return MS_MEDIA_ERR_NONE;
242 }
243
244 static int __media_svc_get_mime_type(const char *path, char *mimetype)
245 {
246         media_svc_retvm_if(path == NULL, MS_MEDIA_ERR_INVALID_PARAMETER, "path is NULL");
247
248         if (aul_get_mime_from_file(path, mimetype, 255) < 0) {
249                 media_svc_error("aul_get_mime_from_file fail");
250                 return MS_MEDIA_ERR_INTERNAL;
251         }
252
253         return MS_MEDIA_ERR_NONE;
254 }
255
256 static bool __media_svc_get_file_ext(const char *file_path, char *file_ext)
257 {
258         int i = 0;
259
260         for (i = strlen(file_path); i >= 0; i--) {
261                 if (file_path[i] == '.') {
262                         SAFE_STRLCPY(file_ext, &file_path[i + 1], MEDIA_SVC_FILE_EXT_LEN_MAX);
263                         return true;
264                 }
265
266                 if (file_path[i] == '/')
267                         return false;
268         }
269         return false;
270 }
271
272 static int __media_svc_safe_atoi(char *buffer, int *si)
273 {
274         char *end = NULL;
275         errno = 0;
276         media_svc_retvm_if(buffer == NULL || si == NULL, MS_MEDIA_ERR_INTERNAL, "invalid parameter");
277
278         const long sl = strtol(buffer, &end, 10);
279
280         media_svc_retvm_if(end == buffer, MS_MEDIA_ERR_INTERNAL, "not a decimal number");
281         media_svc_retvm_if('\0' != *end, MS_MEDIA_ERR_INTERNAL, "extra characters at end of input: %s", end);
282         media_svc_retvm_if((LONG_MIN == sl || LONG_MAX == sl) && (ERANGE == errno), MS_MEDIA_ERR_INTERNAL, "out of range of type long");
283         media_svc_retvm_if(sl > INT_MAX, MS_MEDIA_ERR_INTERNAL, "greater than INT_MAX");
284         media_svc_retvm_if(sl < INT_MIN, MS_MEDIA_ERR_INTERNAL, "less than INT_MIN");
285
286         *si = (int)sl;
287
288         return MS_MEDIA_ERR_NONE;
289 }
290
291 static int __media_svc_save_image(unsigned char *image, unsigned int size, char *image_path, uid_t uid)
292 {
293         int ret = MS_MEDIA_ERR_NONE;
294         struct statfs fs;
295         char *thumb_path = NULL;
296         long bsize_kbytes = 0;
297         GError *error = NULL;
298
299         media_svc_retvm_if(!image || size == 0, MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid image");
300         media_svc_sec_debug("start save image, path [%s] image size [%d]", image_path, size);
301
302         ret = ms_user_get_root_thumb_store_path(uid, &thumb_path);
303         media_svc_retvm_if(ret != MS_MEDIA_ERR_NONE, ret, "ms_user_get_root_thumb_store_path error");
304
305         ret = statfs(thumb_path, &fs);
306         g_free(thumb_path);
307         media_svc_retvm_if(ret == -1, MS_MEDIA_ERR_INTERNAL, "statfs failed");
308
309         bsize_kbytes = fs.f_bsize >> 10;
310         media_svc_retvm_if((bsize_kbytes * fs.f_bavail) < 1024, MS_MEDIA_ERR_NOT_ENOUGH_SPACE, "Not enough space");
311
312         if (!g_file_set_contents(image_path, (const gchar *)image, (gssize)size, &error)) {
313                 media_svc_error("g_file_set_contents faild:%s", error->message);
314                 g_error_free(error);
315                 return MS_MEDIA_ERR_INTERNAL;
316         }
317
318         return MS_MEDIA_ERR_NONE;
319 }
320
321 static char *__media_svc_get_title_from_filename(const char *filename)
322 {
323         char *title = NULL;
324         char *last_dot = NULL;
325
326         media_svc_retvm_if(!STRING_VALID(filename), g_strdup(MEDIA_SVC_TAG_UNKNOWN), "Invalid path");
327
328         last_dot = strrchr(filename, '.');
329         if (last_dot) {
330                 title = g_strndup(filename, last_dot - filename);
331         } else {
332                 title = g_strdup(filename);
333         }
334
335         media_svc_debug("extract title is [%s]", title);
336
337         return title;
338 }
339
340 void _media_svc_remove_file(const char *path)
341 {
342         if (!STRING_VALID(path))
343                 return;
344
345         if (remove(path) != 0)
346                 media_svc_stderror("fail to remove file result");
347 }
348
349 static int __media_svc_get_thumbnail_path(char *thumb_path, const char *pathname, const char *img_format, uid_t uid)
350 {
351         int ret = MS_MEDIA_ERR_NONE;
352         char file_ext[MEDIA_SVC_FILE_EXT_LEN_MAX + 1] = {0, };
353         g_autofree gchar *hash = NULL;
354         g_autofree gchar *thumb_dir = NULL;
355
356         ret = ms_user_get_root_thumb_store_path(uid, &thumb_dir);
357         media_svc_retvm_if(!STRING_VALID(thumb_dir), ret, "ms_user_get_root_thumb_store_path failed");
358         media_svc_retvm_if(!g_file_test(thumb_dir, G_FILE_TEST_IS_DIR), MS_MEDIA_ERR_INTERNAL, "Not a directory");
359
360         memset(file_ext, 0, sizeof(file_ext));
361         if (!__media_svc_get_file_ext(pathname, file_ext))
362                 media_svc_error("get file ext fail");
363
364         hash = g_compute_checksum_for_string(G_CHECKSUM_MD5, pathname, -1);
365         media_svc_retvm_if(!hash, MS_MEDIA_ERR_INTERNAL, "Failed to create hashname");
366
367         if (img_format) {
368                 /* 'img_format' is mime-type */
369                 if (!g_str_has_prefix(img_format, IMAGE_PREFIX) || strlen(img_format) == IMAGE_PREFIX_LEN) {
370                         media_svc_error("Not proper img format");
371                         return MS_MEDIA_ERR_INTERNAL;
372                 }
373
374                 snprintf(thumb_path, MEDIA_SVC_PATHNAME_SIZE, "%s/.%s-%s.%s", thumb_dir, file_ext, hash, img_format + IMAGE_PREFIX_LEN);
375         } else {
376                 if (strcasecmp(file_ext, "PNG") == 0)
377                         snprintf(thumb_path, MEDIA_SVC_PATHNAME_SIZE, "%s/.%s-%s.png", thumb_dir, file_ext, hash);
378                 else
379                         snprintf(thumb_path, MEDIA_SVC_PATHNAME_SIZE, "%s/.%s-%s.jpg", thumb_dir, file_ext, hash);
380         }
381
382         return MS_MEDIA_ERR_NONE;
383 }
384
385 int _media_svc_get_file_time(const char *full_path)
386 {
387         struct stat statbuf = { 0, };
388
389         if (stat(full_path, &statbuf) == -1) {
390                 media_svc_stderror("stat fails.");
391                 return 0;
392         }
393
394         return statbuf.st_mtime;
395 }
396
397 int _media_svc_set_media_info(media_svc_content_info_s *content_info, const char *storage_id, const char *path, bool refresh)
398 {
399         int ret = MS_MEDIA_ERR_NONE;
400         char mime_type[256] = {0, };
401         media_svc_media_type_e media_type;
402
403         media_svc_retvm_if(!STRING_VALID(path), MS_MEDIA_ERR_INVALID_PARAMETER, "path is NULL");
404
405         content_info->path = g_strdup(path);
406         media_svc_retv_del_if(content_info->path == NULL, MS_MEDIA_ERR_INTERNAL, content_info);
407
408         struct stat st;
409         memset(&st, 0, sizeof(struct stat));
410         if (stat(path, &st) == 0) {
411                 content_info->modified_time = st.st_mtime;
412                 content_info->timeline = content_info->modified_time;
413                 content_info->size = st.st_size;
414         } else {
415                 media_svc_stderror("stat failed");
416         }
417
418         /* refresh is TRUE when file modified. so only modified_time and size are changed*/
419         if (refresh) {
420                 media_svc_debug("refresh");
421                 return MS_MEDIA_ERR_NONE;
422         }
423
424         content_info->storage_uuid = g_strdup(storage_id);
425         media_svc_retv_del_if(content_info->storage_uuid == NULL, MS_MEDIA_ERR_INTERNAL, content_info);
426
427         time(&content_info->added_time);
428
429         content_info->media_uuid = __media_info_generate_uuid();
430         media_svc_retv_del_if(content_info->media_uuid == NULL, MS_MEDIA_ERR_INTERNAL, content_info);
431
432         content_info->file_name = g_path_get_basename(path);
433         media_svc_retv_del_if(content_info->file_name == NULL, MS_MEDIA_ERR_INTERNAL, content_info);
434
435         ret = __media_svc_get_mime_type(path, mime_type);
436         media_svc_retv_del_if(ret != MS_MEDIA_ERR_NONE, ret, content_info);
437
438         media_svc_debug("mime [%s]", mime_type);
439
440         ret = __media_svc_get_media_type(path, mime_type, &media_type);
441         media_svc_retv_del_if(ret != MS_MEDIA_ERR_NONE, ret, content_info);
442
443         content_info->mime_type = g_strdup(mime_type);
444         media_svc_retv_del_if(content_info->mime_type == NULL, MS_MEDIA_ERR_INTERNAL, content_info);
445
446         media_svc_sec_debug("path[%s], media_type[%d]", path, media_type);
447
448         content_info->media_type = media_type;
449
450         return MS_MEDIA_ERR_NONE;
451 }
452
453 static char * __media_svc_get_title(MMHandleType tag, const char *filename)
454 {
455         int ret = FILEINFO_ERROR_NONE;
456         char *p = NULL;
457         int size = 0;
458
459         if (tag) {
460                 ret = mm_file_get_attrs(tag, MM_FILE_TAG_TITLE, &p, &size, NULL);
461                 if (ret == FILEINFO_ERROR_NONE && size > 0) {
462                         while(p && isspace(*p))
463                                 p++;
464
465                         return g_strdup(p);
466                 }
467         }
468
469         return __media_svc_get_title_from_filename(filename);
470 }
471
472 char * _media_svc_get_title_from_filename(const char *filename)
473 {
474         /* No MMHandleType in media-svc.c */
475         return __media_svc_get_title_from_filename(filename);
476 }
477
478 int _media_svc_extract_image_metadata(media_svc_content_info_s *content_info)
479 {
480         int orient_value = 0;
481         int exif_width = 0;
482         int exif_height = 0;
483         ExifData *ed = NULL;
484         bool has_datetaken = false;
485         char *path = NULL;
486
487         char buf[MEDIA_SVC_METADATA_LEN_MAX + 1] = { '\0' };
488
489         media_svc_retvm_if(!content_info, MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid content_info");
490         media_svc_retvm_if(content_info->media_type != MEDIA_SVC_MEDIA_TYPE_IMAGE, MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid media_type [%d]", content_info->media_type);
491         media_svc_retvm_if(!STRING_VALID(content_info->path), MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid path");
492
493         path = content_info->path;
494         content_info->media_meta.title = __media_svc_get_title_from_filename(content_info->file_name);
495
496         /* Not used. But to preserved the behavior, set MEDIA_SVC_TAG_UNKNOWN. */
497         content_info->media_meta.album = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
498         content_info->media_meta.artist = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
499         content_info->media_meta.album_artist = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
500         content_info->media_meta.genre = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
501         content_info->media_meta.year = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
502         content_info->media_meta.track_num = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
503
504         /* Load an ExifData object from an EXIF file */
505         ed = exif_data_new_from_file(path);
506         if (!ed) {
507                 media_svc_sec_debug("There is no exif data in [ %s ]", path);
508                 goto GET_WIDTH_HEIGHT;
509         }
510
511         memset(buf, 0x00, sizeof(buf));
512         if (!has_datetaken && __media_svc_get_exif_info(ed, buf, NULL, EXIF_TAG_DATE_TIME_ORIGINAL) == MS_MEDIA_ERR_NONE) {
513                 if (strlen(buf) > 0) {
514                         has_datetaken = true;
515                         content_info->media_meta.datetaken = g_strdup(buf);
516
517                         /* This is same as recorded_date */
518                         content_info->media_meta.recorded_date = g_strdup(buf);
519                 }
520         }
521
522         memset(buf, 0x00, sizeof(buf));
523         if (!has_datetaken && __media_svc_get_exif_info(ed, buf, NULL, EXIF_TAG_DATE_TIME) == MS_MEDIA_ERR_NONE) {
524                 if (strlen(buf) > 0) {
525                         has_datetaken = true;
526                         content_info->media_meta.datetaken = g_strdup(buf);
527
528                         /* This is same as recorded_date */
529                         content_info->media_meta.recorded_date = g_strdup(buf);
530                 }
531         }
532
533         if (content_info->media_meta.recorded_date == NULL)
534                 content_info->media_meta.recorded_date = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
535
536         /* Get orientation value from exif. */
537         if (__media_svc_get_exif_info(ed, NULL, &orient_value, EXIF_TAG_ORIENTATION) == MS_MEDIA_ERR_NONE) {
538                 if (orient_value >= NOT_AVAILABLE && orient_value <= ROT_270)
539                         content_info->media_meta.orientation = orient_value;
540         }
541
542         /* Get width value from exif. */
543         if (__media_svc_get_exif_info(ed, NULL, &exif_width, EXIF_TAG_PIXEL_X_DIMENSION) == MS_MEDIA_ERR_NONE) {
544                 if (exif_width > 0)
545                         content_info->media_meta.width = exif_width;
546         }
547
548         /* Get height value from exif. */
549         if (__media_svc_get_exif_info(ed, NULL, &exif_height, EXIF_TAG_PIXEL_Y_DIMENSION) == MS_MEDIA_ERR_NONE) {
550                 if (exif_height > 0)
551                         content_info->media_meta.height = exif_height;
552         }
553
554         if (ed)
555                 exif_data_unref(ed);
556
557 GET_WIDTH_HEIGHT:
558
559         if (content_info->media_meta.width == 0 || content_info->media_meta.height == 0) {
560                 /*Get image width, height*/
561                 unsigned int img_width = 0;
562                 unsigned int img_height = 0;
563                 mm_util_img_codec_type img_type = IMG_CODEC_UNKNOWN_TYPE;
564
565                 mm_util_extract_image_info(path, &img_type, &img_width, &img_height);
566                 if (content_info->media_meta.width == 0)
567                         content_info->media_meta.width = img_width;
568
569                 if (content_info->media_meta.height == 0)
570                         content_info->media_meta.height = img_height;
571         }
572
573         return MS_MEDIA_ERR_NONE;
574 }
575
576 static char * __media_svc_get_tag_str_value(MMHandleType tag, const char *tag_name)
577 {
578         int ret = FILEINFO_ERROR_NONE;
579         char *p = NULL;
580         int size = 0;
581
582         ret = mm_file_get_attrs(tag, tag_name, &p, &size, NULL);
583         if (ret == FILEINFO_ERROR_NONE && size > 0)
584                 return g_strdup(p);
585
586         return g_strdup(MEDIA_SVC_TAG_UNKNOWN);
587 }
588
589 int _media_svc_extract_audio_metadata(sqlite3 *handle, bool is_direct, media_svc_content_info_s *content_info, uid_t uid)
590 {
591         MMHandleType tag = 0;
592         char *p = NULL;
593         unsigned char *image = NULL;
594         unsigned int size = 0;
595         int mmf_error = FILEINFO_ERROR_NONE;
596         int album_id = 0;
597         int ret = MS_MEDIA_ERR_NONE;
598         int convert_value = 0;
599         bool support_albumart = ms_user_thumb_support(uid, content_info->path);
600
601         /*Get Content Tag attribute ===========*/
602         if (support_albumart)
603                 mmf_error = mm_file_create_tag_attrs(&tag, content_info->path);
604         else
605                 mmf_error = mm_file_create_tag_attrs_no_albumart(&tag, content_info->path);
606
607         if (mmf_error == FILEINFO_ERROR_NONE) {
608                 content_info->media_meta.title = __media_svc_get_title(tag, content_info->file_name);
609                 content_info->media_meta.album = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_ALBUM);
610                 content_info->media_meta.artist = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_ARTIST);
611                 content_info->media_meta.album_artist = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_ALBUM_ARTIST);
612                 content_info->media_meta.genre = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_GENRE);
613                 content_info->media_meta.track_num = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_TRACK_NUM);
614                 content_info->media_meta.copyright = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_COPYRIGHT);
615
616                 mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_RECDATE, &p, &size, NULL);
617                 if ((mmf_error == FILEINFO_ERROR_NONE) && (size > 0)) {
618                         if (g_str_has_suffix(content_info->mime_type, "mp4") || g_str_has_suffix(content_info->mime_type, "3gpp")) {
619                                 /*Creation time format is 20130101 00:00:00 +0000. change it to 2013:01:01 00:00:00  +0000 like exif time format*/
620                                 char *p_value = g_strdelimit(g_strdup(p), "-", ':');
621                                 content_info->media_meta.recorded_date = g_strdup_printf("%s +0000", p_value);
622                                 g_free(p_value);
623                         } else {
624                                 content_info->media_meta.recorded_date = g_strdup(p);
625                         }
626                 }
627
628                 if (content_info->media_meta.recorded_date == NULL)
629                         content_info->media_meta.recorded_date = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
630
631                 mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_DATE, &p, &size, NULL);
632                 if (mmf_error == FILEINFO_ERROR_NONE && size == 4) {
633                         if (__media_svc_safe_atoi(p, &convert_value) == MS_MEDIA_ERR_NONE)
634                                 content_info->media_meta.year = g_strdup(p);
635                 }
636
637                 if (!content_info->media_meta.year)
638                                 content_info->media_meta.year = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
639
640                 /*Do not extract artwork for the USB Storage content*/
641                 if (support_albumart) {
642                         mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_ARTWORK, &image, &size, NULL);
643                         if (mmf_error != FILEINFO_ERROR_NONE)
644                                 media_svc_error("fail to get tag artwork - err(%x)", mmf_error);
645
646                         mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_ARTWORK_SIZE, &size, NULL);
647                         if (mmf_error != FILEINFO_ERROR_NONE)
648                                 media_svc_error("fail to get artwork size - err(%x)", mmf_error);
649
650                         if (image != NULL && size > 0) {
651                                 char thumb_path[MEDIA_SVC_PATHNAME_SIZE] = "\0";
652                                 int artwork_mime_size = -1;
653
654                                 mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_ARTWORK_MIME, &p, &artwork_mime_size, NULL);
655                                 if ((mmf_error == FILEINFO_ERROR_NONE) && (artwork_mime_size > 0)) {
656                                         ret = __media_svc_get_thumbnail_path(thumb_path, content_info->path, p, uid);
657                                         if (ret != MS_MEDIA_ERR_NONE) {
658                                                 media_svc_error("Fail to Get Thumbnail Path");
659                                         } else {
660                                                 ret = __media_svc_save_image(image, size, thumb_path, uid);
661                                                 if (ret != MS_MEDIA_ERR_NONE) {
662                                                         media_svc_error("Fail to Save Image");
663                                                 } else {
664                                                         content_info->thumbnail_path = g_strdup(thumb_path);
665                                                 }
666                                         }
667                                 }
668                         }
669                 }
670
671                 /*Initialize album_id to 0. below code will set the album_id*/
672                 content_info->album_id = album_id;
673                 ret = _media_svc_get_album_id(handle, content_info->media_meta.album, content_info->media_meta.artist, &album_id);
674                 if (ret != MS_MEDIA_ERR_NONE) {
675                         if (ret == MS_MEDIA_ERR_DB_NO_RECORD) {
676                                 media_svc_debug("album does not exist. So start to make album art");
677                                 if ((g_strcmp0(content_info->media_meta.album, MEDIA_SVC_TAG_UNKNOWN)) &&
678                                         (g_strcmp0(content_info->media_meta.artist, MEDIA_SVC_TAG_UNKNOWN)))
679                                         ret = _media_svc_append_album(handle, is_direct, content_info->media_meta.album, content_info->media_meta.artist, content_info->thumbnail_path, &album_id, uid);
680                                 else
681                                         ret = _media_svc_append_album(handle, is_direct, content_info->media_meta.album, content_info->media_meta.artist, NULL, &album_id, uid);
682
683                                 content_info->album_id = album_id;
684                         }
685                 } else {
686                         content_info->album_id = album_id;
687                 }
688
689                 mmf_error = mm_file_destroy_tag_attrs(tag);
690                 if (mmf_error != FILEINFO_ERROR_NONE)
691                         media_svc_error("fail to free tag attr - err(%x)", mmf_error);
692         }       else {
693                 content_info->media_meta.title = __media_svc_get_title_from_filename(content_info->file_name);
694                 content_info->album_id = album_id;
695         }
696
697         return MS_MEDIA_ERR_NONE;
698 }
699
700 int _media_svc_extract_video_metadata(media_svc_content_info_s *content_info)
701 {
702         int mmf_error = FILEINFO_ERROR_NONE;
703         MMHandleType tag = 0;
704         MMHandleType content = 0;
705         char *p = NULL;
706         unsigned int size = 0;
707
708         mmf_error = mm_file_create_tag_attrs_no_albumart(&tag, content_info->path);
709
710         if (mmf_error == FILEINFO_ERROR_NONE) {
711                 mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_RECDATE, &p, &size, NULL);
712                 if ((mmf_error == FILEINFO_ERROR_NONE) && (size > 0)) {
713                         if (g_str_has_suffix(content_info->mime_type, "mp4") || g_str_has_suffix(content_info->mime_type, "3gpp")) {
714                                 /*Creation time format is 20130101 00:00:00 +0000. change it to 2013:01:01 00:00:00  +0000 like exif time format*/
715                                 content_info->media_meta.recorded_date = g_strdelimit(g_strdup(p), "-", ':');
716                         } else {
717                                 content_info->media_meta.recorded_date = g_strdup(p);
718                         }
719                 }
720
721                 if (content_info->media_meta.recorded_date == NULL)
722                         content_info->media_meta.recorded_date = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
723                 content_info->media_meta.datetaken = g_strdup(content_info->media_meta.recorded_date);
724
725                 mmf_error = mm_file_destroy_tag_attrs(tag);
726                 if (mmf_error != FILEINFO_ERROR_NONE)
727                         media_svc_error("fail to free tag attr - err(%x)", mmf_error);
728         }
729         /*Get Content attribute ===========*/
730         mmf_error = mm_file_create_content_attrs_simple(&content, content_info->path);
731         media_svc_retvm_if(mmf_error != FILEINFO_ERROR_NONE, MS_MEDIA_ERR_NONE, "mm_file_create_content_attrs failed");
732
733         mm_file_get_attrs(content, MM_FILE_CONTENT_VIDEO_WIDTH, &content_info->media_meta.width,
734                 MM_FILE_CONTENT_VIDEO_HEIGHT, &content_info->media_meta.height,
735                 NULL);
736
737         mm_file_destroy_content_attrs(content);
738
739         content_info->media_meta.title = __media_svc_get_title_from_filename(content_info->file_name);
740         content_info->media_meta.album = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
741         content_info->media_meta.artist = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
742         content_info->media_meta.album_artist = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
743         content_info->media_meta.genre = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
744         content_info->media_meta.track_num = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
745         content_info->media_meta.year = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
746         content_info->media_meta.copyright = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
747         content_info->album_id = 0;
748
749         return MS_MEDIA_ERR_NONE;
750 }
751
752 static gchar * __media_svc_get_zipfile_string(zip_t *z, const char *fname)
753 {
754         int err = 0;
755         zip_int64_t index_num = 0;
756         zip_file_t *file = NULL;
757         zip_stat_t sb = {0, };
758         gchar *buf = NULL;
759
760         media_svc_retvm_if(!z, NULL, "z is NULL");
761         media_svc_retvm_if(!fname, NULL, "fname is NULL");
762
763         index_num = zip_name_locate(z, fname, ZIP_FL_NOCASE);
764         media_svc_retvm_if(index_num == -1, NULL, "fname is not exists [%s]", fname);
765
766         err = zip_stat_index(z, index_num, ZIP_STAT_SIZE, &sb);
767         media_svc_retvm_if(err == -1, NULL, "zip_stat_index failed");
768
769         file = zip_fopen_index(z, index_num, ZIP_FL_UNCHANGED);
770         media_svc_retvm_if(!file, NULL, "zip_fopen_index failed");
771
772         buf = g_malloc0(sb.size + 1);
773
774         err = zip_fread(file, buf, sb.size);
775         zip_fclose(file);
776
777         if (err == -1) {
778                 g_free(buf);
779                 buf = NULL;
780         }
781
782         return buf;
783 }
784
785 static xmlNodePtr __media_svc_find_node(xmlNodePtr node, const char *key)
786 {
787         xmlNodePtr tmp = NULL;
788
789         media_svc_retvm_if(!node, NULL, "node is NULL");
790         media_svc_retvm_if(!key, NULL, "key is NULL");
791
792         for (tmp = node->children; tmp; tmp = tmp->next) {
793                 if (xmlIsBlankNode(tmp))
794                         continue;
795
796                 if (g_str_has_suffix((gchar *)tmp->name, key))
797                         return tmp;
798         }
799
800         return NULL;
801 }
802
803 static char * __media_svc_remove_escape_c(const char *value)
804 {
805         int start = -1;
806         int end = 0;
807         int len, i;
808
809         media_svc_retv_if(!value, NULL);
810
811         len = strlen(value);
812
813         for (i = 0; i < len; i++) {
814                 if (value[i] != 10 && value[i] != 32) { // 10='\n' 32=' '
815                         if (start == -1)
816                                 start = i;
817
818                         end = i;
819                 }
820         }
821
822         end = end - start + 1;
823
824         return g_strndup(value + start, end);
825 }
826
827 static char * __media_svc_find_and_get_value(xmlNodePtr node, const char *key)
828 {
829         xmlNodePtr tmp = NULL;
830         char *tmp_res = NULL;
831         char *res = NULL;
832
833         media_svc_retvm_if(!node, NULL, "node is NULL");
834         media_svc_retvm_if(!key, NULL, "key is NULL");
835
836         for (tmp = node->children; tmp; tmp = tmp->next) {
837                 if (xmlIsBlankNode(tmp))
838                         continue;
839
840                 if (tmp->children) {
841                         tmp_res = __media_svc_find_and_get_value(tmp, key);
842                         if (tmp_res) {
843                                 res = __media_svc_remove_escape_c(tmp_res);
844                                 xmlFree(tmp_res);
845                                 return res;
846                         }
847                 }
848
849                 if (g_str_has_suffix((gchar *)tmp->name, key))
850                         return (char *)xmlNodeGetContent(tmp);
851         }
852
853         return NULL;
854 }
855
856 static gboolean __media_svc_get_epub_root_file(zip_t *z, char **opf_file)
857 {
858         gchar *buf = NULL;
859         gchar *tmp_buf = NULL;
860         xmlDocPtr doc = NULL;
861         xmlNodePtr node = NULL;
862
863         media_svc_retvm_if(!z, FALSE, "z is NULL");
864         media_svc_retvm_if(!opf_file, FALSE, "opf_file is NULL");
865
866         buf = __media_svc_get_zipfile_string(z, "META-INF/container.xml");
867         media_svc_retvm_if(!buf, FALSE, "buf is NULL");
868
869         tmp_buf = g_strrstr(buf, ">");
870         if (tmp_buf)
871                 *(tmp_buf + 1) = '\0';
872
873         doc = xmlParseDoc((const xmlChar *)buf);
874         g_free(buf);
875         media_svc_retvm_if(!doc, FALSE, "doc is NULL");
876
877         node = xmlDocGetRootElement(doc);
878         node = __media_svc_find_node(node, "rootfiles");
879         node = __media_svc_find_node(node, "rootfile");
880
881         *opf_file = (char *)xmlGetProp(node, (const xmlChar *)"full-path");
882         media_svc_sec_debug("OPF [%s]", *opf_file);
883         xmlFreeDoc(doc);
884
885         return TRUE;
886 }
887
888 static gboolean __media_svc_get_xml_metadata(const xmlChar *buffer, gboolean is_pdf, media_svc_content_info_s *content_info)
889 {
890         xmlDocPtr doc = NULL;
891         xmlNodePtr root = NULL;
892
893         media_svc_retvm_if(!buffer, FALSE, "buffer is NULL");
894         media_svc_retvm_if(!content_info, FALSE, "content_info is NULL");
895
896         doc = xmlParseDoc(buffer);
897         media_svc_retv_if(!doc, FALSE);
898
899         root = xmlDocGetRootElement(doc);
900         if (!root) {
901                 xmlFreeDoc(doc);
902                 return FALSE;
903         }
904
905         content_info->media_meta.title = __media_svc_find_and_get_value(root, "title");
906         if (is_pdf && !content_info->media_meta.title) {
907                 xmlFreeDoc(doc);
908                 return FALSE;
909         }
910
911         content_info->media_meta.artist = __media_svc_find_and_get_value(root, "creator");
912         if (!content_info->media_meta.artist)
913                 content_info->media_meta.artist = __media_svc_find_and_get_value(root, "author");
914         content_info->media_meta.genre = __media_svc_find_and_get_value(root, "subject");
915         content_info->media_meta.copyright = __media_svc_find_and_get_value(root, "publisher");
916         content_info->media_meta.recorded_date = __media_svc_find_and_get_value(root, "date");
917
918         xmlFreeDoc(doc);
919
920         return TRUE;
921 }
922
923 static int __media_svc_get_epub_metadata(media_svc_content_info_s *content_info)
924 {
925         int err = 0;
926         zip_t *z = NULL;
927         gchar *buf = NULL;
928         char *opf_path = NULL;
929
930         media_svc_retvm_if(!content_info, MS_MEDIA_ERR_INVALID_PARAMETER, "content_info is NULL");
931
932         //1. open epub
933         z = zip_open(content_info->path, ZIP_RDONLY, &err);
934         media_svc_retvm_if(err == -1, MS_MEDIA_ERR_INTERNAL, "zip_open failed");
935
936         //2. find and read opf file
937         if (!__media_svc_get_epub_root_file(z, &opf_path)) {
938                 media_svc_error("__media_svc_get_epub_root_file failed");
939                 zip_close(z);
940                 return MS_MEDIA_ERR_INTERNAL;
941         }
942
943         //3. get metadata
944         buf = __media_svc_get_zipfile_string(z, opf_path);
945         xmlFree(opf_path);
946         zip_close(z);
947         media_svc_retvm_if(!buf, MS_MEDIA_ERR_INTERNAL, "__media_svc_get_zipfile_string failed");
948
949         if (!__media_svc_get_xml_metadata((const xmlChar *)buf, FALSE, content_info))
950                 media_svc_error("__media_svc_get_xml_metadata failed");
951
952         g_free(buf);
953
954         return MS_MEDIA_ERR_NONE;
955 }
956
957 static int __media_svc_get_pdf_metadata(media_svc_content_info_s *content_info)
958 {
959     int fd = 0;
960     int start_pos = 0;
961     int end_pos = 0;
962     int cur_pos = 0;
963     int search_limit = 0;
964     char tmp[MEDIA_SVC_PDF_BUF_SIZE + 1] = {0, };
965     gchar *meta_buf = NULL;
966     char *found = NULL;
967
968         media_svc_retvm_if(!content_info, MS_MEDIA_ERR_INVALID_PARAMETER, "content_info is NULL");
969         media_svc_retvm_if(content_info->size < 256, MS_MEDIA_ERR_INTERNAL, "open failed");
970
971         fd = open(content_info->path, O_RDONLY);
972         media_svc_retvm_if(fd < 0, MS_MEDIA_ERR_INTERNAL, "open failed");
973
974         search_limit = content_info->size - MEDIA_SVC_PDF_TAG_TAIL_LEN;
975
976         while (cur_pos <= search_limit) {
977                 if (lseek(fd, cur_pos, SEEK_SET) == -1)
978                         break;
979
980                 memset(&tmp, 0x00, MEDIA_SVC_PDF_BUF_SIZE + 1);
981
982                 if (read(fd, &tmp, MEDIA_SVC_PDF_BUF_SIZE) != MEDIA_SVC_PDF_BUF_SIZE) {
983                         media_svc_error("read failed");
984                         break;
985                 }
986
987                 //1.Find <x:xmpmeta .. </x:xmpmeta> block
988                 if (start_pos == 0 && (found = strstr(tmp, "<x:xmpmeta"))) {
989                         start_pos = cur_pos + (found - tmp);
990 //                      media_svc_error("FIND START_POS[%d]", start_pos);
991                         found = NULL;
992                 }
993
994
995                 if (start_pos != 0 && (found = strstr(tmp, "</x:xmpmeta>"))) {
996                         end_pos = cur_pos + (found - tmp) + MEDIA_SVC_PDF_TAG_TAIL_LEN;
997 //                      media_svc_error("FIND END_POS[%d]", end_pos);
998                         found = NULL;
999                 }
1000
1001                 //2.get metadata using xml parser
1002                 if (start_pos && end_pos) {
1003                         if (lseek(fd, start_pos, SEEK_SET) == -1)
1004                                 break;
1005
1006                         meta_buf = g_malloc0(end_pos - start_pos + 1);
1007
1008                         if (read(fd, meta_buf, end_pos - start_pos) == end_pos - start_pos) {
1009                                 if (__media_svc_get_xml_metadata((const xmlChar *)meta_buf, TRUE, content_info)) {
1010                                         g_free(meta_buf);
1011                                         break;
1012                                 }
1013                         }
1014
1015                         g_free(meta_buf);
1016
1017                         start_pos = 0;
1018                         end_pos = 0;
1019                 }
1020
1021                 cur_pos += 240;
1022
1023         }
1024
1025         close(fd);
1026
1027         return MS_MEDIA_ERR_NONE;
1028 }
1029
1030 int _media_svc_extract_book_metadata(media_svc_content_info_s *content_info)
1031 {
1032         media_svc_retvm_if(!content_info, MS_MEDIA_ERR_INVALID_PARAMETER, "content info is NULL");
1033
1034         if (g_str_has_suffix(content_info->mime_type, "epub+zip"))
1035                 return __media_svc_get_epub_metadata(content_info);
1036         else
1037                 return __media_svc_get_pdf_metadata(content_info);
1038 }
1039
1040 void _media_svc_destroy_content_info(media_svc_content_info_s *content_info)
1041 {
1042         media_svc_retm_if(!content_info, "content info is NULL");
1043
1044         /* Delete media_svc_content_info_s */
1045         g_free(content_info->media_uuid);
1046         g_free(content_info->path);
1047         g_free(content_info->file_name);
1048         g_free(content_info->mime_type);
1049         g_free(content_info->thumbnail_path);
1050         g_free(content_info->storage_uuid);
1051
1052         /* Delete media_svc_content_meta_s */
1053         g_free(content_info->media_meta.title);
1054         g_free(content_info->media_meta.album);
1055         g_free(content_info->media_meta.artist);
1056         g_free(content_info->media_meta.album_artist);
1057         g_free(content_info->media_meta.genre);
1058         g_free(content_info->media_meta.year);
1059         g_free(content_info->media_meta.recorded_date);
1060         g_free(content_info->media_meta.copyright);
1061         g_free(content_info->media_meta.track_num);
1062         g_free(content_info->media_meta.datetaken);
1063 }
1064
1065 int _media_svc_create_thumbnail(const char *path, char *thumb_path, media_svc_media_type_e media_type, uid_t uid)
1066 {
1067         int ret = MS_MEDIA_ERR_NONE;
1068
1069         media_svc_retvm_if(!path, MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid path");
1070         media_svc_retvm_if(!thumb_path, MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid thumb_path");
1071         media_svc_retvm_if(!g_file_test(path, G_FILE_TEST_IS_REGULAR), MS_MEDIA_ERR_INVALID_PARAMETER, "File doesn't exist[%s]", path);
1072
1073         if (!ms_user_thumb_support(uid, path)) {
1074                 media_svc_sec_error("origin path(%s) is invalid", path);
1075                 return MS_MEDIA_ERR_INVALID_PARAMETER;
1076         }
1077
1078         media_svc_sec_debug("Path[%s] Type[%d]", path, media_type);
1079
1080         //1. make thumb path
1081         ret = __media_svc_get_thumbnail_path(thumb_path, path, NULL, uid);
1082         if (ret != MS_MEDIA_ERR_NONE) {
1083                 media_svc_error("Failed to create thumbnail path[%d]", ret);
1084                 SAFE_STRLCPY(thumb_path, "", MAX_FILEPATH_LEN);
1085                 return ret;
1086         }
1087
1088         //2. save thumbnail
1089         if (media_type == MEDIA_SVC_MEDIA_TYPE_IMAGE)
1090                 ret = create_image_thumbnail_to_file(path, MEDIA_SVC_THUMB_WIDTH, MEDIA_SVC_THUMB_HEIGHT, thumb_path, true);
1091         else
1092                 ret = create_video_thumbnail_to_file(path, MEDIA_SVC_THUMB_WIDTH, MEDIA_SVC_THUMB_HEIGHT, thumb_path, true);
1093
1094         return (ret == THUMB_OK) ? MS_MEDIA_ERR_NONE : MS_MEDIA_ERR_INTERNAL;
1095 }
1096
1097 int _media_svc_get_media_type(const char *path, int *mediatype)
1098 {
1099         int ret = MS_MEDIA_ERR_NONE;
1100         char mime_type[256] = {0};
1101         media_svc_media_type_e media_type = MEDIA_SVC_MEDIA_TYPE_OTHER;
1102
1103         media_svc_retvm_if(mediatype == NULL, MS_MEDIA_ERR_INVALID_PARAMETER, "mediatype is NULL");
1104
1105         ret = __media_svc_get_mime_type(path, mime_type);
1106         if (ret == MS_MEDIA_ERR_NONE)
1107                 __media_svc_get_media_type(path, mime_type, &media_type);
1108         else
1109                 media_svc_error("__media_svc_get_mime_type failed");
1110
1111         *mediatype = media_type;
1112
1113         return ret;
1114 }
1115
1116 bool _media_svc_is_keyword_included(const char *path, const char *keyword)
1117 {
1118         bool ret = false;
1119         void *handle = NULL;
1120         bool (*svc_search) (const char *, const char *);
1121
1122         media_svc_retvm_if(!path, false, "Invalid path");
1123         media_svc_retvm_if(!keyword, false, "Invalid keyword");
1124
1125         handle = dlopen(PATH_PLUGIN_LIB, RTLD_LAZY);
1126         media_svc_retvm_if(!handle, false, "dlopen failed");
1127
1128         if (g_str_has_suffix(path, "epub") || g_str_has_suffix(path, "EPUB"))
1129                 svc_search = dlsym(handle, "media_svc_epub_is_keyword_included");
1130         else
1131                 svc_search = dlsym(handle, "media_svc_pdf_is_keyword_included");
1132
1133         if (!svc_search) {
1134                 media_svc_error("dlsym failed - %s", dlerror());
1135                 dlclose(handle);
1136                 return false;
1137         }
1138
1139         ret = svc_search(path, keyword);
1140         dlclose(handle);
1141
1142         return ret;
1143 }
1144
1145 static int __media_svc_create_wordbook_db(const char *path, sqlite3 **handle)
1146 {
1147         int ret = SQLITE_OK;
1148         sqlite3 *db_handle = NULL;
1149         char *err = NULL;
1150
1151         ret = sqlite3_open_v2(path, &db_handle, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL);
1152         media_svc_retvm_if(ret != SQLITE_OK, ret, "sqlite3_open_v2 failed : %d", ret);
1153
1154         ret = sqlite3_exec(db_handle, "PRAGMA journal_mode = OFF;", NULL, NULL, &err);
1155         if (ret != SQLITE_OK)
1156                 goto ERROR;
1157
1158         ret = sqlite3_exec(db_handle, "CREATE TABLE IF NOT EXISTS files(id integer primary key autoincrement, path text unique, validity integer default 1);", NULL, NULL, &err);
1159         if (ret != SQLITE_OK)
1160                 goto ERROR;
1161
1162         ret = sqlite3_exec(db_handle, "CREATE TABLE IF NOT EXISTS words(file_id integer, word text, frequency integer default 1, unique(file_id, word));", NULL, NULL, &err);
1163         if (ret != SQLITE_OK)
1164                 goto ERROR;
1165
1166         ret = sqlite3_exec(db_handle, "CREATE TRIGGER IF NOT EXISTS TR_files_words DELETE ON files BEGIN DELETE FROM words WHERE file_id = old.id;END;", NULL, NULL, &err);
1167         if (ret != SQLITE_OK)
1168                 goto ERROR;
1169
1170         *handle = db_handle;
1171
1172         return SQLITE_OK;
1173
1174 ERROR:
1175         media_svc_error("sqlite3_exec failed : %s", err);
1176         SQLITE3_SAFE_FREE(err);
1177         sqlite3_close_v2(db_handle);
1178
1179         return ret;
1180 }
1181
1182 static bool __media_svc_get_wordbook_handle(uid_t uid, sqlite3 **handle)
1183 {
1184         int ret = SQLITE_OK;
1185         char *db_path = NULL;
1186
1187         ms_user_get_wordbook_db_path(uid, &db_path);
1188         if (!db_path)
1189                 return false;
1190
1191         ret = sqlite3_open_v2(db_path, handle, SQLITE_OPEN_READWRITE, NULL);
1192         if (ret != SQLITE_OK) {
1193                 ret = __media_svc_create_wordbook_db(db_path, handle);
1194                 free(db_path);
1195                 media_svc_retvm_if(ret != SQLITE_OK, false, "__media_svc_create_wordbook_db failed : %d", ret);
1196         } else {
1197                 ret = sqlite3_exec(*handle, "PRAGMA journal_mode = OFF;", NULL, NULL, NULL);
1198                 if (ret != SQLITE_OK)
1199                         media_svc_error("Failed to change journal mode [%d]", ret);
1200         }
1201
1202         return true;
1203 }
1204
1205 static bool __media_svc_is_exist_in_wordbook(sqlite3 *db_handle, const char *path)
1206 {
1207         int ret = SQLITE_OK;
1208         char *err = NULL;
1209         char *query = NULL;
1210
1211         query = sqlite3_mprintf("UPDATE files SET validity=1 WHERE path = %Q", path);
1212
1213         ret = sqlite3_exec(db_handle, query, NULL, NULL, &err);
1214         SQLITE3_SAFE_FREE(query);
1215         if (ret != SQLITE_OK) {
1216                 media_svc_error("Query failed. [%s]", err);
1217                 SQLITE3_SAFE_FREE(err);
1218                 return false;
1219         }
1220
1221         return sqlite3_changes(db_handle) > 0 ? true : false;
1222 }
1223
1224 static void __media_svc_insert_to_wordbook(sqlite3 *db_handle, const char *path)
1225 {
1226         void *handle = NULL;
1227         void (*svc_update) (sqlite3 *, const char *);
1228         char *query = NULL;
1229
1230         query = sqlite3_mprintf("INSERT INTO files(path) VALUES(%Q);", path);
1231         sqlite3_exec(db_handle, query, NULL, NULL, NULL);
1232         sqlite3_free(query);
1233
1234         handle = dlopen(PATH_PLUGIN_LIB, RTLD_LAZY);
1235         if (!handle) {
1236                 media_svc_error("dlopen failed");
1237                 return;
1238         }
1239
1240         if (g_str_has_suffix(path, "epub") || g_str_has_suffix(path, "EPUB"))
1241                 svc_update = dlsym(handle, "media_svc_epub_insert_to_db");
1242         else
1243                 svc_update = dlsym(handle, "media_svc_pdf_insert_to_db");
1244
1245         if (!svc_update) {
1246                 media_svc_error("dlsym failed - %s", dlerror());
1247                 dlclose(handle);
1248                 return;
1249         }
1250
1251         svc_update(db_handle, path);
1252         dlclose(handle);
1253 }
1254
1255 void _media_svc_update_wordbook(const char *path, uid_t uid)
1256 {
1257         sqlite3 *db_handle = NULL;
1258
1259         if (!path) {
1260                 media_svc_error("Invalid path");
1261                 return;
1262         }
1263
1264         // check db..
1265         if (!__media_svc_get_wordbook_handle(uid, &db_handle))
1266                 return;
1267
1268         if (__media_svc_is_exist_in_wordbook(db_handle, path)) {
1269                 sqlite3_close_v2(db_handle);
1270                 return;
1271         }
1272
1273         // if no item, insert to db..
1274         __media_svc_insert_to_wordbook(db_handle, path);
1275         sqlite3_close_v2(db_handle);
1276 }
1277
1278 void _media_svc_clean_wordbook(uid_t uid)
1279 {
1280         sqlite3 *db_handle = NULL;
1281
1282         if (!__media_svc_get_wordbook_handle(uid, &db_handle))
1283                 return;
1284
1285         sqlite3_exec(db_handle, "DELETE FROM files where validity = 0;", NULL, NULL, NULL);
1286         sqlite3_exec(db_handle, "UPDATE files SET validity = 0;", NULL, NULL, NULL);
1287         sqlite3_close_v2(db_handle);
1288 }
1289
1290 bool _media_svc_get_matched_list(const char *keyword, uid_t uid, GList **list)
1291 {
1292         int ret = SQLITE_OK;
1293         sqlite3 *handle = NULL;
1294         sqlite3_stmt *stmt = NULL;
1295         char *query = NULL;
1296
1297         media_svc_retvm_if(!list, false, "list is NULL");
1298         media_svc_retvm_if(!keyword, false, "keyword is NULL");
1299         media_svc_retvm_if(!__media_svc_get_wordbook_handle(uid, &handle), false, "Failed to get handle");
1300
1301         query = sqlite3_mprintf("SELECT files.path FROM files JOIN (SELECT file_id, sum(frequency) AS freq_sum FROM words WHERE word LIKE '%q%%' GROUP BY file_id ORDER BY freq_sum DESC) w ON files.id = w.file_id;", keyword);
1302         ret = sqlite3_prepare_v2(handle, query, -1, &stmt, NULL);
1303         SQLITE3_SAFE_FREE(query);
1304
1305         if (ret != SQLITE_OK) {
1306                 media_svc_error("Query failed[%d]", ret);
1307                 sqlite3_close_v2(handle);
1308                 return false;
1309         }
1310
1311         while (sqlite3_step(stmt) == SQLITE_ROW)
1312                 *list = g_list_append(*list, g_strdup((char *)sqlite3_column_text(stmt, 0)));
1313
1314         sqlite3_finalize(stmt);
1315         sqlite3_close_v2(handle);
1316
1317         return true;
1318 }