Modify _media_svc_extract_book_metadata()
[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_safe_atoi(char *buffer, int *si)
268 {
269         char *end = NULL;
270         errno = 0;
271         media_svc_retvm_if(buffer == NULL || si == NULL, MS_MEDIA_ERR_INTERNAL, "invalid parameter");
272
273         const long sl = strtol(buffer, &end, 10);
274
275         media_svc_retvm_if(end == buffer, MS_MEDIA_ERR_INTERNAL, "not a decimal number");
276         media_svc_retvm_if('\0' != *end, MS_MEDIA_ERR_INTERNAL, "extra characters at end of input: %s", end);
277         media_svc_retvm_if((LONG_MIN == sl || LONG_MAX == sl) && (ERANGE == errno), MS_MEDIA_ERR_INTERNAL, "out of range of type long");
278         media_svc_retvm_if(sl > INT_MAX, MS_MEDIA_ERR_INTERNAL, "greater than INT_MAX");
279         media_svc_retvm_if(sl < INT_MIN, MS_MEDIA_ERR_INTERNAL, "less than INT_MIN");
280
281         *si = (int)sl;
282
283         return MS_MEDIA_ERR_NONE;
284 }
285
286 static int __media_svc_save_image(unsigned char *image, unsigned int size, char *image_path, uid_t uid)
287 {
288         int ret = MS_MEDIA_ERR_NONE;
289         struct statfs fs;
290         char *thumb_path = NULL;
291         long bsize_kbytes = 0;
292         GError *error = NULL;
293
294         media_svc_retvm_if(!image || size == 0, MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid image");
295         media_svc_sec_debug("start save image, path [%s] image size [%d]", image_path, size);
296
297         ret = ms_user_get_root_thumb_store_path(uid, &thumb_path);
298         media_svc_retvm_if(ret != MS_MEDIA_ERR_NONE, ret, "ms_user_get_root_thumb_store_path error");
299
300         ret = statfs(thumb_path, &fs);
301         g_free(thumb_path);
302         media_svc_retvm_if(ret == -1, MS_MEDIA_ERR_INTERNAL, "statfs failed");
303
304         bsize_kbytes = fs.f_bsize >> 10;
305         media_svc_retvm_if((bsize_kbytes * fs.f_bavail) < 1024, MS_MEDIA_ERR_NOT_ENOUGH_SPACE, "Not enough space");
306
307         if (!g_file_set_contents(image_path, (const gchar *)image, (gssize)size, &error)) {
308                 media_svc_error("g_file_set_contents faild:%s", error->message);
309                 g_error_free(error);
310                 return MS_MEDIA_ERR_INTERNAL;
311         }
312
313         return MS_MEDIA_ERR_NONE;
314 }
315
316 static char *__media_svc_get_title_from_filename(const char *filename)
317 {
318         char *title = NULL;
319         char *last_dot = NULL;
320
321         media_svc_retvm_if(!STRING_VALID(filename), g_strdup(MEDIA_SVC_TAG_UNKNOWN), "Invalid path");
322
323         last_dot = strrchr(filename, '.');
324         if (last_dot) {
325                 title = g_strndup(filename, last_dot - filename);
326         } else {
327                 title = g_strdup(filename);
328         }
329
330         media_svc_debug("extract title is [%s]", title);
331
332         return title;
333 }
334
335 void _media_svc_remove_file(const char *path)
336 {
337         if (!STRING_VALID(path))
338                 return;
339
340         if (remove(path) != 0)
341                 media_svc_stderror("fail to remove file result");
342 }
343
344 static int __media_svc_get_thumbnail_path(char *thumb_path, const char *pathname, const char *img_format, uid_t uid)
345 {
346         int ret = MS_MEDIA_ERR_NONE;
347         char file_ext[MEDIA_SVC_FILE_EXT_LEN_MAX + 1] = {0, };
348         g_autofree gchar *hash = NULL;
349         g_autofree gchar *thumb_dir = NULL;
350
351         ret = ms_user_get_root_thumb_store_path(uid, &thumb_dir);
352         media_svc_retvm_if(!STRING_VALID(thumb_dir), ret, "ms_user_get_root_thumb_store_path failed");
353         media_svc_retvm_if(!g_file_test(thumb_dir, G_FILE_TEST_IS_DIR), MS_MEDIA_ERR_INTERNAL, "Not a directory");
354
355         memset(file_ext, 0, sizeof(file_ext));
356         if (!__media_svc_get_file_ext(pathname, file_ext))
357                 media_svc_error("get file ext fail");
358
359         hash = g_compute_checksum_for_string(G_CHECKSUM_MD5, pathname, -1);
360         media_svc_retvm_if(!hash, MS_MEDIA_ERR_INTERNAL, "Failed to create hashname");
361
362         if (img_format) {
363                 /* 'img_format' is mime-type */
364                 if (!g_str_has_prefix(img_format, IMAGE_PREFIX) || strlen(img_format) == PREFIX_LEN) {
365                         media_svc_error("Not proper img format");
366                         return MS_MEDIA_ERR_INTERNAL;
367                 }
368
369                 snprintf(thumb_path, MEDIA_SVC_PATHNAME_SIZE, "%s/.%s-%s.%s", thumb_dir, file_ext, hash, img_format + PREFIX_LEN);
370         } else {
371                 if (strcasecmp(file_ext, "PNG") == 0)
372                         snprintf(thumb_path, MEDIA_SVC_PATHNAME_SIZE, "%s/.%s-%s.png", thumb_dir, file_ext, hash);
373                 else
374                         snprintf(thumb_path, MEDIA_SVC_PATHNAME_SIZE, "%s/.%s-%s.jpg", thumb_dir, file_ext, hash);
375         }
376
377         return MS_MEDIA_ERR_NONE;
378 }
379
380 int _media_svc_get_file_time(const char *full_path)
381 {
382         struct stat statbuf = { 0, };
383
384         if (stat(full_path, &statbuf) == -1) {
385                 media_svc_stderror("stat fails.");
386                 return 0;
387         }
388
389         return statbuf.st_mtime;
390 }
391
392 int _media_svc_set_media_info(media_svc_content_info_s *content_info, const char *storage_id, const char *path, bool refresh)
393 {
394         int ret = MS_MEDIA_ERR_NONE;
395         char mime_type[256] = {0, };
396         media_svc_media_type_e media_type;
397
398         media_svc_retvm_if(!STRING_VALID(path), MS_MEDIA_ERR_INVALID_PARAMETER, "path is NULL");
399
400         content_info->path = g_strdup(path);
401         media_svc_retv_del_if(content_info->path == NULL, MS_MEDIA_ERR_INTERNAL, content_info);
402
403         struct stat st;
404         memset(&st, 0, sizeof(struct stat));
405         if (stat(path, &st) == 0) {
406                 content_info->modified_time = st.st_mtime;
407                 content_info->timeline = content_info->modified_time;
408                 content_info->size = st.st_size;
409         } else {
410                 media_svc_stderror("stat failed");
411         }
412
413         /* refresh is TRUE when file modified. so only modified_time and size are changed*/
414         if (refresh) {
415                 media_svc_debug("refresh");
416                 return MS_MEDIA_ERR_NONE;
417         }
418
419         content_info->storage_uuid = g_strdup(storage_id);
420         media_svc_retv_del_if(content_info->storage_uuid == NULL, MS_MEDIA_ERR_INTERNAL, content_info);
421
422         time(&content_info->added_time);
423
424         content_info->media_uuid = __media_info_generate_uuid();
425         media_svc_retv_del_if(content_info->media_uuid == NULL, MS_MEDIA_ERR_INTERNAL, content_info);
426
427         content_info->file_name = g_path_get_basename(path);
428         media_svc_retv_del_if(content_info->file_name == NULL, MS_MEDIA_ERR_INTERNAL, content_info);
429
430         ret = __media_svc_get_mime_type(path, mime_type);
431         media_svc_retv_del_if(ret != MS_MEDIA_ERR_NONE, ret, content_info);
432
433         media_svc_debug("mime [%s]", mime_type);
434
435         ret = __media_svc_get_media_type(path, mime_type, &media_type);
436         media_svc_retv_del_if(ret != MS_MEDIA_ERR_NONE, ret, content_info);
437
438         content_info->mime_type = g_strdup(mime_type);
439         media_svc_retv_del_if(content_info->mime_type == NULL, MS_MEDIA_ERR_INTERNAL, content_info);
440
441         media_svc_sec_debug("path[%s], media_type[%d]", path, media_type);
442
443         content_info->media_type = media_type;
444
445         return MS_MEDIA_ERR_NONE;
446 }
447
448 static char * __media_svc_get_title(MMHandleType tag, const char *filename)
449 {
450         int ret = FILEINFO_ERROR_NONE;
451         char *p = NULL;
452         int size = 0;
453
454         if (tag) {
455                 ret = mm_file_get_attrs(tag, MM_FILE_TAG_TITLE, &p, &size, NULL);
456                 if (ret == FILEINFO_ERROR_NONE && size > 0) {
457                         while(p && isspace(*p))
458                                 p++;
459
460                         return g_strdup(p);
461                 }
462         }
463
464         return __media_svc_get_title_from_filename(filename);
465 }
466
467 char * _media_svc_get_title_from_filename(const char *filename)
468 {
469         return __media_svc_get_title_from_filename(filename);
470 }
471
472 int _media_svc_extract_image_metadata(media_svc_content_info_s *content_info)
473 {
474         int orient_value = 0;
475         int exif_width = 0;
476         int exif_height = 0;
477         ExifData *ed = NULL;
478         bool has_datetaken = false;
479         char *path = NULL;
480
481         char buf[MEDIA_SVC_METADATA_LEN_MAX + 1] = { '\0' };
482
483         media_svc_retvm_if(!content_info, MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid content_info");
484         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);
485         media_svc_retvm_if(!STRING_VALID(content_info->path), MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid path");
486
487         path = content_info->path;
488         content_info->media_meta.title = __media_svc_get_title_from_filename(content_info->file_name);
489
490         /* Not used. But to preserved the behavior, set MEDIA_SVC_TAG_UNKNOWN. */
491         content_info->media_meta.album = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
492         content_info->media_meta.artist = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
493         content_info->media_meta.album_artist = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
494         content_info->media_meta.genre = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
495         content_info->media_meta.year = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
496         content_info->media_meta.track_num = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
497
498         /* Load an ExifData object from an EXIF file */
499         ed = exif_data_new_from_file(path);
500         if (!ed) {
501                 media_svc_sec_debug("There is no exif data in [ %s ]", path);
502                 goto GET_WIDTH_HEIGHT;
503         }
504
505         memset(buf, 0x00, sizeof(buf));
506         if (!has_datetaken && __media_svc_get_exif_info(ed, buf, NULL, EXIF_TAG_DATE_TIME_ORIGINAL) == MS_MEDIA_ERR_NONE) {
507                 if (strlen(buf) > 0) {
508                         has_datetaken = true;
509                         content_info->media_meta.datetaken = g_strdup(buf);
510
511                         /* This is same as recorded_date */
512                         content_info->media_meta.recorded_date = g_strdup(buf);
513                 }
514         }
515
516         memset(buf, 0x00, sizeof(buf));
517         if (!has_datetaken && __media_svc_get_exif_info(ed, buf, NULL, EXIF_TAG_DATE_TIME) == MS_MEDIA_ERR_NONE) {
518                 if (strlen(buf) > 0) {
519                         has_datetaken = true;
520                         content_info->media_meta.datetaken = g_strdup(buf);
521
522                         /* This is same as recorded_date */
523                         content_info->media_meta.recorded_date = g_strdup(buf);
524                 }
525         }
526
527         if (content_info->media_meta.recorded_date == NULL)
528                 content_info->media_meta.recorded_date = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
529
530         /* Get orientation value from exif. */
531         if (__media_svc_get_exif_info(ed, NULL, &orient_value, EXIF_TAG_ORIENTATION) == MS_MEDIA_ERR_NONE) {
532                 if (orient_value >= NOT_AVAILABLE && orient_value <= ROT_270)
533                         content_info->media_meta.orientation = orient_value;
534         }
535
536         /* Get width value from exif. */
537         if (__media_svc_get_exif_info(ed, NULL, &exif_width, EXIF_TAG_PIXEL_X_DIMENSION) == MS_MEDIA_ERR_NONE) {
538                 if (exif_width > 0)
539                         content_info->media_meta.width = exif_width;
540         }
541
542         /* Get height value from exif. */
543         if (__media_svc_get_exif_info(ed, NULL, &exif_height, EXIF_TAG_PIXEL_Y_DIMENSION) == MS_MEDIA_ERR_NONE) {
544                 if (exif_height > 0)
545                         content_info->media_meta.height = exif_height;
546         }
547
548         if (ed)
549                 exif_data_unref(ed);
550
551 GET_WIDTH_HEIGHT:
552         if (content_info->media_meta.width == 0 || content_info->media_meta.height == 0) {
553                 /*Get image width, height*/
554                 unsigned int img_width = 0;
555                 unsigned int img_height = 0;
556
557                 if (get_image_info(path, &img_width, &img_height) != THUMB_OK)
558                         return MS_MEDIA_ERR_NONE;
559
560                 if (content_info->media_meta.width == 0)
561                         content_info->media_meta.width = img_width;
562
563                 if (content_info->media_meta.height == 0)
564                         content_info->media_meta.height = img_height;
565         }
566
567         return MS_MEDIA_ERR_NONE;
568 }
569
570 static char * __media_svc_get_tag_str_value(MMHandleType tag, const char *tag_name)
571 {
572         int ret = FILEINFO_ERROR_NONE;
573         char *p = NULL;
574         int size = 0;
575
576         ret = mm_file_get_attrs(tag, tag_name, &p, &size, NULL);
577         if (ret == FILEINFO_ERROR_NONE && size > 0)
578                 return g_strdup(p);
579
580         return g_strdup(MEDIA_SVC_TAG_UNKNOWN);
581 }
582
583 int _media_svc_extract_audio_metadata(sqlite3 *handle, bool is_direct, media_svc_content_info_s *content_info, uid_t uid)
584 {
585         MMHandleType tag = 0;
586         char *p = NULL;
587         unsigned char *image = NULL;
588         unsigned int size = 0;
589         int mmf_error = FILEINFO_ERROR_NONE;
590         int album_id = 0;
591         int ret = MS_MEDIA_ERR_NONE;
592         int convert_value = 0;
593         bool support_albumart = ms_user_thumb_support(uid, content_info->path);
594
595         /*Get Content Tag attribute ===========*/
596         if (support_albumart)
597                 mmf_error = mm_file_create_tag_attrs(&tag, content_info->path);
598         else
599                 mmf_error = mm_file_create_tag_attrs_no_albumart(&tag, content_info->path);
600
601         if (mmf_error == FILEINFO_ERROR_NONE) {
602                 content_info->media_meta.title = __media_svc_get_title(tag, content_info->file_name);
603                 content_info->media_meta.album = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_ALBUM);
604                 content_info->media_meta.artist = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_ARTIST);
605                 content_info->media_meta.album_artist = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_ALBUM_ARTIST);
606                 content_info->media_meta.genre = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_GENRE);
607                 content_info->media_meta.track_num = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_TRACK_NUM);
608                 content_info->media_meta.copyright = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_COPYRIGHT);
609
610                 mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_RECDATE, &p, &size, NULL);
611                 if ((mmf_error == FILEINFO_ERROR_NONE) && (size > 0)) {
612                         if (g_str_has_suffix(content_info->mime_type, "mp4") || g_str_has_suffix(content_info->mime_type, "3gpp")) {
613                                 /*Creation time format is 20130101 00:00:00 +0000. change it to 2013:01:01 00:00:00  +0000 like exif time format*/
614                                 char *p_value = g_strdelimit(g_strdup(p), "-", ':');
615                                 content_info->media_meta.recorded_date = g_strdup_printf("%s +0000", p_value);
616                                 g_free(p_value);
617                         } else {
618                                 content_info->media_meta.recorded_date = g_strdup(p);
619                         }
620                 }
621
622                 if (content_info->media_meta.recorded_date == NULL)
623                         content_info->media_meta.recorded_date = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
624
625                 mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_DATE, &p, &size, NULL);
626                 if (mmf_error == FILEINFO_ERROR_NONE && size == 4) {
627                         if (__media_svc_safe_atoi(p, &convert_value) == MS_MEDIA_ERR_NONE)
628                                 content_info->media_meta.year = g_strdup(p);
629                 }
630
631                 if (!content_info->media_meta.year)
632                                 content_info->media_meta.year = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
633
634                 /*Do not extract artwork for the USB Storage content*/
635                 if (support_albumart) {
636                         mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_ARTWORK, &image, &size, NULL);
637                         if (mmf_error != FILEINFO_ERROR_NONE)
638                                 media_svc_error("fail to get tag artwork - err(%x)", mmf_error);
639
640                         mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_ARTWORK_SIZE, &size, NULL);
641                         if (mmf_error != FILEINFO_ERROR_NONE)
642                                 media_svc_error("fail to get artwork size - err(%x)", mmf_error);
643
644                         if (image != NULL && size > 0) {
645                                 char thumb_path[MEDIA_SVC_PATHNAME_SIZE] = "\0";
646                                 int artwork_mime_size = -1;
647
648                                 mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_ARTWORK_MIME, &p, &artwork_mime_size, NULL);
649                                 if ((mmf_error == FILEINFO_ERROR_NONE) && (artwork_mime_size > 0)) {
650                                         ret = __media_svc_get_thumbnail_path(thumb_path, content_info->path, p, uid);
651                                         if (ret != MS_MEDIA_ERR_NONE) {
652                                                 media_svc_error("Fail to Get Thumbnail Path");
653                                         } else {
654                                                 ret = __media_svc_save_image(image, size, thumb_path, uid);
655                                                 if (ret != MS_MEDIA_ERR_NONE) {
656                                                         media_svc_error("Fail to Save Image");
657                                                 } else {
658                                                         content_info->thumbnail_path = g_strdup(thumb_path);
659                                                 }
660                                         }
661                                 }
662                         }
663                 }
664
665                 /*Initialize album_id to 0. below code will set the album_id*/
666                 content_info->album_id = album_id;
667                 ret = _media_svc_get_album_id(handle, content_info->media_meta.album, content_info->media_meta.artist, &album_id);
668                 if (ret != MS_MEDIA_ERR_NONE) {
669                         if (ret == MS_MEDIA_ERR_DB_NO_RECORD) {
670                                 media_svc_debug("album does not exist. So start to make album art");
671                                 if ((g_strcmp0(content_info->media_meta.album, MEDIA_SVC_TAG_UNKNOWN)) &&
672                                         (g_strcmp0(content_info->media_meta.artist, MEDIA_SVC_TAG_UNKNOWN)))
673                                         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);
674                                 else
675                                         ret = _media_svc_append_album(handle, is_direct, content_info->media_meta.album, content_info->media_meta.artist, NULL, &album_id, uid);
676
677                                 content_info->album_id = album_id;
678                         }
679                 } else {
680                         content_info->album_id = album_id;
681                 }
682
683                 mmf_error = mm_file_destroy_tag_attrs(tag);
684                 if (mmf_error != FILEINFO_ERROR_NONE)
685                         media_svc_error("fail to free tag attr - err(%x)", mmf_error);
686         }       else {
687                 content_info->media_meta.title = __media_svc_get_title_from_filename(content_info->file_name);
688                 content_info->album_id = album_id;
689         }
690
691         return MS_MEDIA_ERR_NONE;
692 }
693
694 int _media_svc_extract_video_metadata(media_svc_content_info_s *content_info)
695 {
696         int mmf_error = FILEINFO_ERROR_NONE;
697         MMHandleType tag = 0;
698         MMHandleType content = 0;
699         char *p = NULL;
700         unsigned int size = 0;
701
702         mmf_error = mm_file_create_tag_attrs_no_albumart(&tag, content_info->path);
703
704         if (mmf_error == FILEINFO_ERROR_NONE) {
705                 mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_RECDATE, &p, &size, NULL);
706                 if ((mmf_error == FILEINFO_ERROR_NONE) && (size > 0)) {
707                         if (g_str_has_suffix(content_info->mime_type, "mp4") || g_str_has_suffix(content_info->mime_type, "3gpp")) {
708                                 /*Creation time format is 20130101 00:00:00 +0000. change it to 2013:01:01 00:00:00  +0000 like exif time format*/
709                                 content_info->media_meta.recorded_date = g_strdelimit(g_strdup(p), "-", ':');
710                         } else {
711                                 content_info->media_meta.recorded_date = g_strdup(p);
712                         }
713                 }
714
715                 if (content_info->media_meta.recorded_date == NULL)
716                         content_info->media_meta.recorded_date = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
717                 content_info->media_meta.datetaken = g_strdup(content_info->media_meta.recorded_date);
718
719                 mmf_error = mm_file_destroy_tag_attrs(tag);
720                 if (mmf_error != FILEINFO_ERROR_NONE)
721                         media_svc_error("fail to free tag attr - err(%x)", mmf_error);
722         }
723         /*Get Content attribute ===========*/
724         mmf_error = mm_file_create_content_attrs_simple(&content, content_info->path);
725         media_svc_retvm_if(mmf_error != FILEINFO_ERROR_NONE, MS_MEDIA_ERR_NONE, "mm_file_create_content_attrs failed");
726
727         mm_file_get_attrs(content, MM_FILE_CONTENT_VIDEO_WIDTH, &content_info->media_meta.width,
728                 MM_FILE_CONTENT_VIDEO_HEIGHT, &content_info->media_meta.height,
729                 NULL);
730
731         mm_file_destroy_content_attrs(content);
732
733         content_info->media_meta.title = __media_svc_get_title_from_filename(content_info->file_name);
734         content_info->media_meta.album = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
735         content_info->media_meta.artist = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
736         content_info->media_meta.album_artist = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
737         content_info->media_meta.genre = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
738         content_info->media_meta.track_num = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
739         content_info->media_meta.year = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
740         content_info->media_meta.copyright = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
741         content_info->album_id = 0;
742
743         return MS_MEDIA_ERR_NONE;
744 }
745
746 static gchar * __media_svc_get_zipfile_string(zip_t *z, const char *fname)
747 {
748         int err = 0;
749         zip_int64_t index_num = 0;
750         zip_file_t *file = NULL;
751         zip_stat_t sb = {0, };
752         gchar *buf = NULL;
753
754         media_svc_retvm_if(!z, NULL, "z is NULL");
755         media_svc_retvm_if(!fname, NULL, "fname is NULL");
756
757         index_num = zip_name_locate(z, fname, ZIP_FL_NOCASE);
758         media_svc_retvm_if(index_num == -1, NULL, "fname is not exists [%s]", fname);
759
760         err = zip_stat_index(z, index_num, ZIP_STAT_SIZE, &sb);
761         media_svc_retvm_if(err == -1, NULL, "zip_stat_index failed");
762
763         file = zip_fopen_index(z, index_num, ZIP_FL_UNCHANGED);
764         media_svc_retvm_if(!file, NULL, "zip_fopen_index failed");
765
766         buf = g_malloc0(sb.size + 1);
767
768         err = zip_fread(file, buf, sb.size);
769         zip_fclose(file);
770
771         if (err == -1) {
772                 g_free(buf);
773                 buf = NULL;
774         }
775
776         return buf;
777 }
778
779 static xmlNodePtr __media_svc_find_node(xmlNodePtr node, const char *key)
780 {
781         xmlNodePtr tmp = NULL;
782
783         media_svc_retvm_if(!node, NULL, "node is NULL");
784         media_svc_retvm_if(!key, NULL, "key is NULL");
785
786         for (tmp = node->children; tmp; tmp = tmp->next) {
787                 if (xmlIsBlankNode(tmp))
788                         continue;
789
790                 if (g_str_has_suffix((gchar *)tmp->name, key))
791                         return tmp;
792         }
793
794         return NULL;
795 }
796
797 static char * __media_svc_remove_escape_c(const char *value)
798 {
799         int start = -1;
800         int end = 0;
801         int len, i;
802
803         media_svc_retv_if(!value, NULL);
804
805         len = strlen(value);
806
807         for (i = 0; i < len; i++) {
808                 if (value[i] != 10 && value[i] != 32) { // 10='\n' 32=' '
809                         if (start == -1)
810                                 start = i;
811
812                         end = i;
813                 }
814         }
815
816         end = end - start + 1;
817
818         return g_strndup(value + start, end);
819 }
820
821 static char * __media_svc_find_and_get_value(xmlNodePtr node, const char *key)
822 {
823         xmlNodePtr tmp = NULL;
824         char *tmp_res = NULL;
825         char *res = NULL;
826
827         media_svc_retvm_if(!node, NULL, "node is NULL");
828         media_svc_retvm_if(!key, NULL, "key is NULL");
829
830         for (tmp = node->children; tmp; tmp = tmp->next) {
831                 if (xmlIsBlankNode(tmp))
832                         continue;
833
834                 if (tmp->children) {
835                         tmp_res = __media_svc_find_and_get_value(tmp, key);
836                         if (tmp_res) {
837                                 res = __media_svc_remove_escape_c(tmp_res);
838                                 xmlFree(tmp_res);
839                                 return res;
840                         }
841                 }
842
843                 if (g_str_has_suffix((gchar *)tmp->name, key))
844                         return (char *)xmlNodeGetContent(tmp);
845         }
846
847         return NULL;
848 }
849
850 static gboolean __media_svc_get_epub_root_file(zip_t *z, char **opf_file)
851 {
852         gchar *buf = NULL;
853         gchar *tmp_buf = NULL;
854         xmlDocPtr doc = NULL;
855         xmlNodePtr node = NULL;
856
857         media_svc_retvm_if(!z, FALSE, "z is NULL");
858         media_svc_retvm_if(!opf_file, FALSE, "opf_file is NULL");
859
860         buf = __media_svc_get_zipfile_string(z, "META-INF/container.xml");
861         media_svc_retvm_if(!buf, FALSE, "buf is NULL");
862
863         tmp_buf = g_strrstr(buf, ">");
864         if (tmp_buf)
865                 *(tmp_buf + 1) = '\0';
866
867         doc = xmlParseDoc((const xmlChar *)buf);
868         g_free(buf);
869         media_svc_retvm_if(!doc, FALSE, "doc is NULL");
870
871         node = xmlDocGetRootElement(doc);
872         node = __media_svc_find_node(node, "rootfiles");
873         node = __media_svc_find_node(node, "rootfile");
874
875         *opf_file = (char *)xmlGetProp(node, (const xmlChar *)"full-path");
876         media_svc_sec_debug("OPF [%s]", *opf_file);
877         xmlFreeDoc(doc);
878
879         return TRUE;
880 }
881
882 static gboolean __media_svc_get_xml_metadata(const xmlChar *buffer, gboolean is_pdf, media_svc_content_info_s *content_info)
883 {
884         xmlDocPtr doc = NULL;
885         xmlNodePtr root = NULL;
886
887         media_svc_retvm_if(!buffer, FALSE, "buffer is NULL");
888         media_svc_retvm_if(!content_info, FALSE, "content_info is NULL");
889
890         doc = xmlParseDoc(buffer);
891         media_svc_retv_if(!doc, FALSE);
892
893         root = xmlDocGetRootElement(doc);
894         if (!root) {
895                 xmlFreeDoc(doc);
896                 return FALSE;
897         }
898
899         content_info->media_meta.title = __media_svc_find_and_get_value(root, "title");
900         /* In the case of PDF, if there is no title, it may not be a metadata block. Search for the next xml block*/
901         if (is_pdf && !content_info->media_meta.title) {
902                 xmlFreeDoc(doc);
903                 return FALSE;
904         }
905
906         content_info->media_meta.artist = __media_svc_find_and_get_value(root, "creator");
907         if (!content_info->media_meta.artist)
908                 content_info->media_meta.artist = __media_svc_find_and_get_value(root, "author");
909         content_info->media_meta.genre = __media_svc_find_and_get_value(root, "subject");
910         content_info->media_meta.copyright = __media_svc_find_and_get_value(root, "publisher");
911         content_info->media_meta.recorded_date = __media_svc_find_and_get_value(root, "date");
912
913         xmlFreeDoc(doc);
914
915         return TRUE;
916 }
917
918 static int __media_svc_get_epub_metadata(media_svc_content_info_s *content_info)
919 {
920         int err = 0;
921         zip_t *z = NULL;
922         gchar *buf = NULL;
923         char *opf_path = NULL;
924
925         media_svc_retvm_if(!content_info, MS_MEDIA_ERR_INVALID_PARAMETER, "content_info is NULL");
926
927         //1. open epub
928         z = zip_open(content_info->path, ZIP_RDONLY, &err);
929         media_svc_retvm_if(err == -1, MS_MEDIA_ERR_INTERNAL, "zip_open failed");
930
931         //2. find and read opf file
932         if (!__media_svc_get_epub_root_file(z, &opf_path)) {
933                 media_svc_error("__media_svc_get_epub_root_file failed");
934                 zip_close(z);
935                 return MS_MEDIA_ERR_INTERNAL;
936         }
937
938         //3. get metadata
939         buf = __media_svc_get_zipfile_string(z, opf_path);
940         xmlFree(opf_path);
941         zip_close(z);
942         media_svc_retvm_if(!buf, MS_MEDIA_ERR_INTERNAL, "__media_svc_get_zipfile_string failed");
943
944         if (!__media_svc_get_xml_metadata((const xmlChar *)buf, FALSE, content_info))
945                 media_svc_error("__media_svc_get_xml_metadata failed");
946
947         g_free(buf);
948
949         return MS_MEDIA_ERR_NONE;
950 }
951
952 static int __media_svc_get_pdf_metadata(media_svc_content_info_s *content_info)
953 {
954     int fd = 0;
955     int start_pos = 0;
956     int end_pos = 0;
957     int cur_pos = 0;
958     int search_limit = 0;
959     char tmp[MEDIA_SVC_PDF_BUF_SIZE + 1] = {0, };
960     gchar *meta_buf = NULL;
961     char *found = NULL;
962
963         media_svc_retvm_if(!content_info, MS_MEDIA_ERR_INVALID_PARAMETER, "content_info is NULL");
964         media_svc_retvm_if(content_info->size < 256, MS_MEDIA_ERR_INTERNAL, "open failed");
965
966         fd = open(content_info->path, O_RDONLY);
967         media_svc_retvm_if(fd < 0, MS_MEDIA_ERR_INTERNAL, "open failed");
968
969         search_limit = content_info->size - MEDIA_SVC_PDF_TAG_TAIL_LEN;
970
971         while (cur_pos <= search_limit) {
972                 if (lseek(fd, cur_pos, SEEK_SET) == -1)
973                         break;
974
975                 memset(&tmp, 0x00, MEDIA_SVC_PDF_BUF_SIZE + 1);
976
977                 if (read(fd, &tmp, MEDIA_SVC_PDF_BUF_SIZE) != MEDIA_SVC_PDF_BUF_SIZE) {
978                         media_svc_error("read failed");
979                         break;
980                 }
981
982                 //1.Find <x:xmpmeta .. </x:xmpmeta> block
983                 if (start_pos == 0 && (found = strstr(tmp, "<x:xmpmeta"))) {
984                         start_pos = cur_pos + (found - tmp);
985 //                      media_svc_error("FIND START_POS[%d]", start_pos);
986                         found = NULL;
987                 }
988
989
990                 if (start_pos != 0 && (found = strstr(tmp, "</x:xmpmeta>"))) {
991                         end_pos = cur_pos + (found - tmp) + MEDIA_SVC_PDF_TAG_TAIL_LEN;
992 //                      media_svc_error("FIND END_POS[%d]", end_pos);
993                         found = NULL;
994                 }
995
996                 //2.get metadata using xml parser
997                 if (start_pos && end_pos) {
998                         if (lseek(fd, start_pos, SEEK_SET) == -1)
999                                 break;
1000
1001                         meta_buf = g_malloc0(end_pos - start_pos + 1);
1002
1003                         if (read(fd, meta_buf, end_pos - start_pos) == end_pos - start_pos) {
1004                                 if (__media_svc_get_xml_metadata((const xmlChar *)meta_buf, TRUE, content_info)) {
1005                                         g_free(meta_buf);
1006                                         break;
1007                                 }
1008                         }
1009
1010                         g_free(meta_buf);
1011
1012                         start_pos = 0;
1013                         end_pos = 0;
1014                 }
1015
1016                 cur_pos += 240;
1017
1018         }
1019
1020         close(fd);
1021
1022         return MS_MEDIA_ERR_NONE;
1023 }
1024
1025 int _media_svc_extract_book_metadata(media_svc_content_info_s *content_info)
1026 {
1027         int ret = MS_MEDIA_ERR_NONE;
1028
1029         media_svc_retvm_if(!content_info, MS_MEDIA_ERR_INVALID_PARAMETER, "content info is NULL");
1030
1031         if (g_str_has_suffix(content_info->mime_type, "epub+zip"))
1032                 ret = __media_svc_get_epub_metadata(content_info);
1033         else
1034                 ret = __media_svc_get_pdf_metadata(content_info);
1035
1036         media_svc_retvm_if(ret != MS_MEDIA_ERR_NONE, ret, "failed to extract metadata");
1037         if (!content_info->media_meta.title || strlen(content_info->media_meta.title) == 0) {
1038                 g_free(content_info->media_meta.title);
1039                 content_info->media_meta.title = __media_svc_get_title_from_filename(content_info->file_name);
1040         }
1041
1042         return MS_MEDIA_ERR_NONE;
1043 }
1044
1045 void _media_svc_destroy_content_info(media_svc_content_info_s *content_info)
1046 {
1047         media_svc_retm_if(!content_info, "content info is NULL");
1048
1049         /* Delete media_svc_content_info_s */
1050         g_free(content_info->media_uuid);
1051         g_free(content_info->path);
1052         g_free(content_info->file_name);
1053         g_free(content_info->mime_type);
1054         g_free(content_info->thumbnail_path);
1055         g_free(content_info->storage_uuid);
1056
1057         /* Delete media_svc_content_meta_s */
1058         g_free(content_info->media_meta.title);
1059         g_free(content_info->media_meta.album);
1060         g_free(content_info->media_meta.artist);
1061         g_free(content_info->media_meta.album_artist);
1062         g_free(content_info->media_meta.genre);
1063         g_free(content_info->media_meta.year);
1064         g_free(content_info->media_meta.recorded_date);
1065         g_free(content_info->media_meta.copyright);
1066         g_free(content_info->media_meta.track_num);
1067         g_free(content_info->media_meta.datetaken);
1068 }
1069
1070 int _media_svc_create_thumbnail(const char *path, char *thumb_path, media_svc_media_type_e media_type, uid_t uid)
1071 {
1072         int ret = MS_MEDIA_ERR_NONE;
1073
1074         media_svc_retvm_if(!path, MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid path");
1075         media_svc_retvm_if(!thumb_path, MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid thumb_path");
1076         media_svc_retvm_if(!g_file_test(path, G_FILE_TEST_IS_REGULAR), MS_MEDIA_ERR_INVALID_PARAMETER, "File doesn't exist[%s]", path);
1077
1078         if (!ms_user_thumb_support(uid, path)) {
1079                 media_svc_sec_error("origin path(%s) is invalid", path);
1080                 return MS_MEDIA_ERR_INVALID_PARAMETER;
1081         }
1082
1083         media_svc_sec_debug("Path[%s] Type[%d]", path, media_type);
1084
1085         //1. make thumb path
1086         ret = __media_svc_get_thumbnail_path(thumb_path, path, NULL, uid);
1087         media_svc_retvm_if(ret != MS_MEDIA_ERR_NONE, ret, "Failed to create thumbnail path[%d]", ret);
1088
1089         //2. save thumbnail
1090         if (media_type == MEDIA_SVC_MEDIA_TYPE_IMAGE)
1091                 ret = create_image_thumbnail_to_file(path, MEDIA_SVC_THUMB_WIDTH, MEDIA_SVC_THUMB_HEIGHT, thumb_path, true);
1092         else
1093                 ret = create_video_thumbnail_to_file(path, MEDIA_SVC_THUMB_WIDTH, MEDIA_SVC_THUMB_HEIGHT, thumb_path, true);
1094
1095         return (ret == THUMB_OK) ? MS_MEDIA_ERR_NONE : MS_MEDIA_ERR_INTERNAL;
1096 }
1097
1098 int _media_svc_get_media_type(const char *path, int *mediatype)
1099 {
1100         int ret = MS_MEDIA_ERR_NONE;
1101         char mime_type[256] = {0};
1102         media_svc_media_type_e media_type = MEDIA_SVC_MEDIA_TYPE_OTHER;
1103
1104         media_svc_retvm_if(mediatype == NULL, MS_MEDIA_ERR_INVALID_PARAMETER, "mediatype is NULL");
1105
1106         ret = __media_svc_get_mime_type(path, mime_type);
1107         if (ret == MS_MEDIA_ERR_NONE)
1108                 __media_svc_get_media_type(path, mime_type, &media_type);
1109         else
1110                 media_svc_error("__media_svc_get_mime_type failed");
1111
1112         *mediatype = media_type;
1113
1114         return ret;
1115 }
1116
1117 bool _media_svc_is_keyword_included(const char *path, const char *keyword)
1118 {
1119         bool ret = false;
1120         void *handle = NULL;
1121         bool (*svc_search) (const char *, const char *);
1122
1123         media_svc_retvm_if(!path, false, "Invalid path");
1124         media_svc_retvm_if(!keyword, false, "Invalid keyword");
1125
1126         handle = dlopen(PATH_PLUGIN_LIB, RTLD_LAZY);
1127         media_svc_retvm_if(!handle, false, "dlopen failed");
1128
1129         if (g_str_has_suffix(path, "epub") || g_str_has_suffix(path, "EPUB"))
1130                 svc_search = dlsym(handle, "media_svc_epub_is_keyword_included");
1131         else
1132                 svc_search = dlsym(handle, "media_svc_pdf_is_keyword_included");
1133
1134         if (!svc_search) {
1135                 media_svc_error("dlsym failed - %s", dlerror());
1136                 dlclose(handle);
1137                 return false;
1138         }
1139
1140         ret = svc_search(path, keyword);
1141         dlclose(handle);
1142
1143         return ret;
1144 }
1145
1146 static int __media_svc_create_wordbook_db(const char *path, sqlite3 **handle)
1147 {
1148         int ret = SQLITE_OK;
1149         sqlite3 *db_handle = NULL;
1150         char *err = NULL;
1151
1152         ret = sqlite3_open_v2(path, &db_handle, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL);
1153         media_svc_retvm_if(ret != SQLITE_OK, ret, "sqlite3_open_v2 failed : %d", ret);
1154
1155         ret = sqlite3_exec(db_handle, "PRAGMA journal_mode = OFF;", NULL, NULL, &err);
1156         if (ret != SQLITE_OK)
1157                 goto ERROR;
1158
1159         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);
1160         if (ret != SQLITE_OK)
1161                 goto ERROR;
1162
1163         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);
1164         if (ret != SQLITE_OK)
1165                 goto ERROR;
1166
1167         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);
1168         if (ret != SQLITE_OK)
1169                 goto ERROR;
1170
1171         *handle = db_handle;
1172
1173         return SQLITE_OK;
1174
1175 ERROR:
1176         media_svc_error("sqlite3_exec failed : %s", err);
1177         SQLITE3_SAFE_FREE(err);
1178         sqlite3_close_v2(db_handle);
1179
1180         return ret;
1181 }
1182
1183 static bool __media_svc_get_wordbook_handle(uid_t uid, sqlite3 **handle)
1184 {
1185         int ret = SQLITE_OK;
1186         char *db_path = NULL;
1187
1188         ms_user_get_wordbook_db_path(uid, &db_path);
1189         if (!db_path)
1190                 return false;
1191
1192         ret = sqlite3_open_v2(db_path, handle, SQLITE_OPEN_READWRITE, NULL);
1193         if (ret != SQLITE_OK) {
1194                 ret = __media_svc_create_wordbook_db(db_path, handle);
1195                 free(db_path);
1196                 media_svc_retvm_if(ret != SQLITE_OK, false, "__media_svc_create_wordbook_db failed : %d", ret);
1197         } else {
1198                 ret = sqlite3_exec(*handle, "PRAGMA journal_mode = OFF;", NULL, NULL, NULL);
1199                 if (ret != SQLITE_OK)
1200                         media_svc_error("Failed to change journal mode [%d]", ret);
1201         }
1202
1203         return true;
1204 }
1205
1206 static bool __media_svc_is_exist_in_wordbook(sqlite3 *db_handle, const char *path)
1207 {
1208         int ret = SQLITE_OK;
1209         char *err = NULL;
1210         char *query = NULL;
1211
1212         query = sqlite3_mprintf("UPDATE files SET validity=1 WHERE path = %Q", path);
1213
1214         ret = sqlite3_exec(db_handle, query, NULL, NULL, &err);
1215         SQLITE3_SAFE_FREE(query);
1216         if (ret != SQLITE_OK) {
1217                 media_svc_error("Query failed. [%s]", err);
1218                 SQLITE3_SAFE_FREE(err);
1219                 return false;
1220         }
1221
1222         return sqlite3_changes(db_handle) > 0 ? true : false;
1223 }
1224
1225 static void __media_svc_insert_to_wordbook(sqlite3 *db_handle, const char *path)
1226 {
1227         void *handle = NULL;
1228         void (*svc_update) (sqlite3 *, const char *);
1229         char *query = NULL;
1230
1231         query = sqlite3_mprintf("INSERT INTO files(path) VALUES(%Q);", path);
1232         sqlite3_exec(db_handle, query, NULL, NULL, NULL);
1233         sqlite3_free(query);
1234
1235         handle = dlopen(PATH_PLUGIN_LIB, RTLD_LAZY);
1236         if (!handle) {
1237                 media_svc_error("dlopen failed");
1238                 return;
1239         }
1240
1241         if (g_str_has_suffix(path, "epub") || g_str_has_suffix(path, "EPUB"))
1242                 svc_update = dlsym(handle, "media_svc_epub_insert_to_db");
1243         else
1244                 svc_update = dlsym(handle, "media_svc_pdf_insert_to_db");
1245
1246         if (!svc_update) {
1247                 media_svc_error("dlsym failed - %s", dlerror());
1248                 dlclose(handle);
1249                 return;
1250         }
1251
1252         svc_update(db_handle, path);
1253         dlclose(handle);
1254 }
1255
1256 void _media_svc_update_wordbook(const char *path, uid_t uid)
1257 {
1258         sqlite3 *db_handle = NULL;
1259
1260         if (!path) {
1261                 media_svc_error("Invalid path");
1262                 return;
1263         }
1264
1265         // check db..
1266         if (!__media_svc_get_wordbook_handle(uid, &db_handle))
1267                 return;
1268
1269         if (__media_svc_is_exist_in_wordbook(db_handle, path)) {
1270                 sqlite3_close_v2(db_handle);
1271                 return;
1272         }
1273
1274         // if no item, insert to db..
1275         __media_svc_insert_to_wordbook(db_handle, path);
1276         sqlite3_close_v2(db_handle);
1277 }
1278
1279 void _media_svc_clean_wordbook(uid_t uid)
1280 {
1281         sqlite3 *db_handle = NULL;
1282
1283         if (!__media_svc_get_wordbook_handle(uid, &db_handle))
1284                 return;
1285
1286         sqlite3_exec(db_handle, "DELETE FROM files where validity = 0;", NULL, NULL, NULL);
1287         sqlite3_exec(db_handle, "UPDATE files SET validity = 0;", NULL, NULL, NULL);
1288         sqlite3_close_v2(db_handle);
1289 }
1290
1291 bool _media_svc_get_matched_list(const char *keyword, uid_t uid, GList **list)
1292 {
1293         int ret = SQLITE_OK;
1294         sqlite3 *handle = NULL;
1295         sqlite3_stmt *stmt = NULL;
1296         char *query = NULL;
1297
1298         media_svc_retvm_if(!list, false, "list is NULL");
1299         media_svc_retvm_if(!keyword, false, "keyword is NULL");
1300         media_svc_retvm_if(!__media_svc_get_wordbook_handle(uid, &handle), false, "Failed to get handle");
1301
1302         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);
1303         ret = sqlite3_prepare_v2(handle, query, -1, &stmt, NULL);
1304         SQLITE3_SAFE_FREE(query);
1305
1306         if (ret != SQLITE_OK) {
1307                 media_svc_error("Query failed[%d]", ret);
1308                 sqlite3_close_v2(handle);
1309                 return false;
1310         }
1311
1312         while (sqlite3_step(stmt) == SQLITE_ROW)
1313                 *list = g_list_append(*list, g_strdup((char *)sqlite3_column_text(stmt, 0)));
1314
1315         sqlite3_finalize(stmt);
1316         sqlite3_close_v2(handle);
1317
1318         return true;
1319 }