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