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