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