Remove unused DB fields
[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  * Contact: Hyunjun Ko <zzoon.ko@samsung.com>, Haejeong Kim <backto.kim@samsung.com>
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  */
21
22 #include <unistd.h>
23 #include <stdlib.h>
24 #ifndef __USE_XOPEN
25 #define DEF_XOPEN
26 #define __USE_XOPEN /* needed for strptime */
27 #endif
28 #include <time.h>
29 #ifdef DEF_XOPEN
30 #undef __USE_XOPEN
31 #endif
32 #include <string.h>
33 #include <system_info.h>
34 #include <sys/vfs.h>
35 #include <glib/gstdio.h>
36 #include <sys/stat.h>
37 #include <dirent.h>
38 #include <ctype.h>
39 #include <aul/aul.h>
40 #include <mm_file.h>
41 #include <libexif/exif-data.h>
42 #include <media-util.h>
43 #include <uuid/uuid.h>
44 #include <mm_util_magick.h>
45 #include <media-thumbnail.h>
46 #include "media-util-err.h"
47 #include "media-svc-util.h"
48 #include "media-svc-db-utils.h"
49 #include "media-svc-debug.h"
50 #include "media-svc-env.h"
51 #include "media-svc-hash.h"
52 #include "media-svc-album.h"
53 #include "media-svc-localize_ch.h"
54 /*For ebook metadata */
55 #include <zip.h>
56 #include <libxml/xmlmemory.h>
57 #include <libxml/parser.h>
58 #include <libxml/HTMLparser.h>
59 #include <dlfcn.h>
60
61 #define MEDIA_SVC_FILE_EXT_LEN_MAX                              6                       /**< Maximum file ext lenth*/
62
63 #define MUSIC_MIME_NUM 29
64 #define SOUND_MIME_NUM 2
65 #define MIME_TYPE_LENGTH 255
66 #define THUMB_HASH_LEN 256
67 #define MIME_LENGTH 50
68 #define MEDIA_SVC_ARTWORK_SIZE 2000
69 #define MEDIA_SVC_DEFAULT_FORMAT_LEN 19
70 #define IMAGE_PREFIX "image/"
71 #define IMAGE_PREFIX_LEN 6
72 #define AUDIO_PREFIX "audio/"
73 #define AUDIO_PREFIX_LEN 6
74 #define VIDEO_PREFIX "video/"
75 #define VIDEO_PREFIX_LEN 6
76
77 #define MEDIA_SVC_DEFAULT_GPS_VALUE                     -200                    /**< Default GPS Value*/
78
79 #define MEDIA_SVC_PDF_TAG_TAIL_LEN 12
80 #define MEDIA_SVC_PDF_BUF_SIZE 256
81
82 #define MEDIA_SVC_THUMB_WIDTH 320
83 #define MEDIA_SVC_THUMB_HEIGHT 240
84
85 #define PATH_PLUGIN_LIB                         PATH_LIBDIR"/libmedia-ebook-plugin.so"
86
87 enum Exif_Orientation {
88         NOT_AVAILABLE = 0,
89         NORMAL = 1,
90         HFLIP = 2,
91         ROT_180 = 3,
92         VFLIP = 4,
93         TRANSPOSE = 5,
94         ROT_90 = 6,
95         TRANSVERSE = 7,
96         ROT_270 = 8
97 };
98
99 static const char music_mime_table[MUSIC_MIME_NUM][MIME_LENGTH] = {
100         /*known mime types of normal files*/
101         "mpeg",
102         "ogg",
103         "x-ms-wma",
104         "x-flac",
105         "mp4",
106         /* known mime types of drm files*/
107         "mp3",
108         "x-mp3", /*alias of audio/mpeg*/
109         "x-mpeg", /*alias of audio/mpeg*/
110         "3gpp",
111         "x-ogg", /*alias of audio/ogg*/
112         "vnd.ms-playready.media.pya:*.pya", /*playready*/
113         "wma",
114         "aac",
115         "x-m4a", /*alias of audio/mp4*/
116         /* below mimes are rare*/
117         "x-vorbis+ogg",
118         "x-flac+ogg",
119         "x-matroska",
120         "ac3",
121         "mp2",
122         "x-ape",
123         "x-ms-asx",
124         "vnd.rn-realaudio",
125
126         "x-vorbis", /*alias of audio/x-vorbis+ogg*/
127         "vorbis", /*alias of audio/x-vorbis+ogg*/
128         "x-oggflac",
129         "x-mp2", /*alias of audio/mp2*/
130         "x-pn-realaudio", /*alias of audio/vnd.rn-realaudio*/
131         "vnd.m-realaudio", /*alias of audio/vnd.rn-realaudio*/
132         "x-wav",
133 };
134
135 static const char sound_mime_table[SOUND_MIME_NUM][MIME_LENGTH] = {
136         "application/x-smaf",
137         "text/x-iMelody"
138 };
139
140 static char *__media_info_generate_uuid(void)
141 {
142         uuid_t uuid_value;
143         char uuid_unparsed[37];
144
145 RETRY_GEN:
146         uuid_generate(uuid_value);
147         uuid_unparse(uuid_value, uuid_unparsed);
148
149         if (strlen(uuid_unparsed) < 36) {
150                 media_svc_debug("INVALID UUID : %s. RETRY GENERATE.", uuid_unparsed);
151                 goto RETRY_GEN;
152         }
153
154         return g_strdup(uuid_unparsed);
155 }
156
157 /* GPS information is not ExifTag member */
158 static int __media_svc_get_exif_gps_double(ExifData *ed, double *value, long tagtype)
159 {
160         ExifEntry *entry;
161         char gps_buf[MEDIA_SVC_METADATA_LEN_MAX + 1] = {0, };
162         double tmp_arr[3] = { 0.0, 0.0, 0.0 };
163         int i = 0;
164         char **tmp_split = NULL;
165
166         media_svc_retv_if(!ed, MS_MEDIA_ERR_INVALID_PARAMETER);
167         media_svc_retv_if(!value, MS_MEDIA_ERR_INVALID_PARAMETER);
168
169         entry = exif_data_get_entry(ed, tagtype);
170         media_svc_retv_if(!entry, MS_MEDIA_ERR_INTERNAL);
171
172         exif_entry_get_value(entry, gps_buf, sizeof(gps_buf));
173         gps_buf[strlen(gps_buf)] = '\0';
174
175         tmp_split = g_strsplit(gps_buf, ",", -1);
176         if (g_strv_length(tmp_split) != 3) {
177                 g_strfreev(tmp_split);
178                 media_svc_error("Wrong GPS format");
179                 return MS_MEDIA_ERR_INTERNAL;
180         }
181
182         for (i = 0; i < 3; i++)
183                 tmp_arr[i] = g_strtod(tmp_split[i], NULL);
184
185         g_strfreev(tmp_split);
186
187         *value = tmp_arr[0] + tmp_arr[1] / 60 + tmp_arr[2] / 3600;
188
189         return MS_MEDIA_ERR_NONE;
190 }
191
192 static int __media_svc_get_exif_gps_str(ExifData *ed, char *value, long tagtype)
193 {
194         ExifEntry *entry;
195
196         media_svc_retv_if(!ed, MS_MEDIA_ERR_INVALID_PARAMETER);
197         media_svc_retv_if(!value, MS_MEDIA_ERR_INVALID_PARAMETER);
198
199         entry = exif_data_get_entry(ed, tagtype);
200         if (entry) {
201                 exif_entry_get_value(entry, value, MEDIA_SVC_METADATA_LEN_MAX);
202                 value[strlen(value)] = '\0';
203         }
204
205         return MS_MEDIA_ERR_NONE;
206 }
207
208 static int __media_svc_get_exif_info(ExifData *ed, char *buf, int *i_value, double *d_value, ExifTag tagtype)
209 {
210         ExifEntry *entry;
211         ExifByteOrder mByteOrder;
212         ExifRational mRational;
213         long numerator, denominator;
214
215         media_svc_retv_if(!ed, MS_MEDIA_ERR_INVALID_PARAMETER);
216
217         entry = exif_data_get_entry(ed, tagtype);
218         media_svc_retv_if(!entry, MS_MEDIA_ERR_NONE);
219
220         switch (tagtype) {
221         case EXIF_TAG_ORIENTATION:
222         case EXIF_TAG_PIXEL_X_DIMENSION:
223         case EXIF_TAG_PIXEL_Y_DIMENSION:
224         case EXIF_TAG_ISO_SPEED_RATINGS:
225                 media_svc_retvm_if(!i_value, MS_MEDIA_ERR_INVALID_PARAMETER, "i_value is NULL");
226
227                 mByteOrder = exif_data_get_byte_order(ed);
228                 short exif_value = exif_get_short(entry->data, mByteOrder);
229                 *i_value = (int)exif_value;
230                 break;
231         case EXIF_TAG_EXPOSURE_TIME:
232                 media_svc_retvm_if(!buf, MS_MEDIA_ERR_INVALID_PARAMETER, "buf is NULL");
233
234                 mByteOrder = exif_data_get_byte_order(ed);
235                 mRational = exif_get_rational(entry->data, mByteOrder);
236                 numerator = mRational.numerator;
237                 denominator = mRational.denominator;
238                 snprintf(buf, MEDIA_SVC_METADATA_LEN_MAX, "%ld/%ld", numerator, denominator);
239                 break;
240         case EXIF_TAG_FNUMBER:
241                 media_svc_retvm_if(!d_value, MS_MEDIA_ERR_INVALID_PARAMETER, "d_value is NULL");
242
243                 mByteOrder = exif_data_get_byte_order(ed);
244                 mRational = exif_get_rational(entry->data, mByteOrder);
245                 numerator = mRational.numerator;
246                 denominator = mRational.denominator;
247
248                 *d_value = ((numerator*1.0)/(denominator*1.0));
249                 break;
250         default:
251                 media_svc_retvm_if(!buf, MS_MEDIA_ERR_INVALID_PARAMETER, "buf is NULL");
252
253                 exif_entry_get_value(entry, buf, MEDIA_SVC_METADATA_LEN_MAX);
254                 buf[strlen(buf)] = '\0';
255         }
256
257         return MS_MEDIA_ERR_NONE;
258 }
259
260 static time_t __media_svc_get_timeline_from_str(const char *timstr)
261 {
262         struct tm t;
263         time_t modified_t = 0;
264         time_t rawtime;
265         struct tm timeinfo;
266
267         if (!STRING_VALID(timstr)) {
268                 media_svc_error("Invalid Parameter");
269                 return 0;
270         }
271
272         /*Exif Format : %Y:%m:%d %H:%M:%S
273         Videoc Content Creation_time format of FFMpeg : %Y-%m-%d %H:%M:%S*/
274         memset(&t, 0x00, sizeof(struct tm));
275
276         tzset();
277         time(&rawtime);
278         localtime_r(&rawtime, &timeinfo);
279
280         if (strptime(timstr, "%Y:%m:%d %H:%M:%S", &t) || strptime(timstr, "%Y-%m-%d %H:%M:%S", &t)) {
281                 t.tm_isdst = timeinfo.tm_isdst;
282                 if (t.tm_isdst != 0)
283                         media_svc_debug("DST %d", t.tm_isdst);
284
285                 /* If time string has timezone */
286                 if (strptime(timstr, "%Y:%m:%d %H:%M:%S %z", &t) || strptime(timstr, "%Y-%m-%d %H:%M:%S %z", &t)) {
287                         char tim_tmp_str[255] = { 0, };
288
289                         /* ISO8601 Time string format */
290                         strftime(tim_tmp_str, 255, "%Y-%m-%dT%H:%M:%S%z", &t);
291                         GDateTime *pdatetime = g_date_time_new_from_iso8601(tim_tmp_str, NULL);
292                         if (pdatetime)
293                                 modified_t = g_date_time_to_unix(pdatetime);
294                         g_date_time_unref(pdatetime);
295                         media_svc_debug("Calibrated timeval : [%ld][%s]", modified_t, tim_tmp_str);
296                 } else {
297                         /* Just localtime */
298                         modified_t = mktime(&t);
299                 }
300
301                 if (modified_t > 0)
302                         return modified_t;
303                 else
304                         media_svc_debug("Failed to get timeline : [%s] [%d:%d:%d: %d:%d:%d]", timstr, t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);
305         } else {
306                 media_svc_error("Failed to get timeline : [%s]", timstr);
307         }
308
309         return 0;
310 }
311
312 static int __media_svc_get_media_type(const char *path, const char *mime_type, media_svc_media_type_e *media_type)
313 {
314         int idx = 0;
315         int audio = 0;
316         int video = 0;
317
318         media_svc_retvm_if(!path, MS_MEDIA_ERR_INVALID_PARAMETER, "path is null");
319         media_svc_retvm_if(!mime_type, MS_MEDIA_ERR_INVALID_PARAMETER, "mime_type is null");
320         media_svc_retvm_if(!media_type, MS_MEDIA_ERR_INVALID_PARAMETER, "media_type is null");
321
322         /* Image */
323         if (strncmp(mime_type, IMAGE_PREFIX, IMAGE_PREFIX_LEN) == 0) {
324                 *media_type = MEDIA_SVC_MEDIA_TYPE_IMAGE;
325                 return MS_MEDIA_ERR_NONE;
326         }
327
328         /* Audio */
329         if (strncmp(mime_type, AUDIO_PREFIX, AUDIO_PREFIX_LEN) == 0) {
330                 *media_type = MEDIA_SVC_MEDIA_TYPE_SOUND;
331
332                 for (idx = 0; idx < MUSIC_MIME_NUM; idx++) {
333                         if (strcmp(mime_type + AUDIO_PREFIX_LEN, music_mime_table[idx]) == 0) {
334                                 *media_type = MEDIA_SVC_MEDIA_TYPE_MUSIC;
335                                 break;
336                         }
337                 }
338
339                 /* audio/x-mpegurl : .m3u file (playlist file) */
340                 if (strcmp(mime_type + AUDIO_PREFIX_LEN, "x-mpegurl") == 0)
341                         *media_type = MEDIA_SVC_MEDIA_TYPE_OTHER;
342
343                 return MS_MEDIA_ERR_NONE;
344         }
345
346         /* Video */
347         if (strncmp(mime_type, VIDEO_PREFIX, VIDEO_PREFIX_LEN) == 0) {
348                 *media_type = MEDIA_SVC_MEDIA_TYPE_VIDEO;
349
350                 /*some video files don't have video stream. in this case it is categorize as music. */
351                 if (strcmp(mime_type + VIDEO_PREFIX_LEN, "3gpp") == 0 ||
352                         strcmp(mime_type + VIDEO_PREFIX_LEN, "mp4") == 0) {
353                         if (mm_file_get_stream_info(path, &audio, &video) == FILEINFO_ERROR_NONE) {
354                                 if (audio > 0 && video == 0)
355                                         *media_type = MEDIA_SVC_MEDIA_TYPE_MUSIC;
356                         }
357                 }
358
359                 return MS_MEDIA_ERR_NONE;
360         }
361
362         /* ETC */
363         *media_type = MEDIA_SVC_MEDIA_TYPE_OTHER;
364
365         for (idx = 0; idx < SOUND_MIME_NUM; idx++) {
366                 if (strcmp(mime_type, sound_mime_table[idx]) == 0) {
367                         *media_type = MEDIA_SVC_MEDIA_TYPE_SOUND;
368                         return MS_MEDIA_ERR_NONE;
369                 }
370         }
371
372         /*"asf" must check video stream and then categorize in directly. */
373         if (strcmp(mime_type, "application/vnd.ms-asf") == 0) {
374                 if (mm_file_get_stream_info(path, &audio, &video) == FILEINFO_ERROR_NONE) {
375                         if (audio > 0 && video == 0)
376                                 *media_type = MEDIA_SVC_MEDIA_TYPE_MUSIC;
377                         else
378                                 *media_type = MEDIA_SVC_MEDIA_TYPE_VIDEO;
379                 }
380
381                 return MS_MEDIA_ERR_NONE;
382         }
383
384         if (strcmp(mime_type, "application/epub+zip") == 0 || strcmp(mime_type, "application/pdf") == 0)
385                 *media_type = MEDIA_SVC_MEDIA_TYPE_BOOK;
386
387         return MS_MEDIA_ERR_NONE;
388 }
389
390 /*
391 drm_contentifo is not NULL, if the file is OMA DRM.
392 If the file is not OMA DRM, drm_contentinfo must be NULL.
393 */
394 static int __media_svc_get_mime_type(const char *path, char *mimetype)
395 {
396         media_svc_retvm_if(path == NULL, MS_MEDIA_ERR_INVALID_PARAMETER, "path is NULL");
397
398         /*in case of normal files or failure to get mime in drm */
399         if (aul_get_mime_from_file(path, mimetype, 255) < 0) {
400                 media_svc_error("aul_get_mime_from_file fail");
401                 return MS_MEDIA_ERR_INTERNAL;
402         }
403
404         return MS_MEDIA_ERR_NONE;
405 }
406
407 static bool __media_svc_get_file_ext(const char *file_path, char *file_ext)
408 {
409         int i = 0;
410
411         for (i = strlen(file_path); i >= 0; i--) {
412                 if (file_path[i] == '.') {
413                         SAFE_STRLCPY(file_ext, &file_path[i + 1], MEDIA_SVC_FILE_EXT_LEN_MAX);
414                         return true;
415                 }
416
417                 if (file_path[i] == '/')
418                         return false;
419         }
420         return false;
421 }
422
423 static int __media_svc_safe_atoi(char *buffer, int *si)
424 {
425         char *end = NULL;
426         errno = 0;
427         media_svc_retvm_if(buffer == NULL || si == NULL, MS_MEDIA_ERR_INTERNAL, "invalid parameter");
428
429         const long sl = strtol(buffer, &end, 10);
430
431         media_svc_retvm_if(end == buffer, MS_MEDIA_ERR_INTERNAL, "not a decimal number");
432         media_svc_retvm_if('\0' != *end, MS_MEDIA_ERR_INTERNAL, "extra characters at end of input: %s", end);
433         media_svc_retvm_if((LONG_MIN == sl || LONG_MAX == sl) && (ERANGE == errno), MS_MEDIA_ERR_INTERNAL, "out of range of type long");
434         media_svc_retvm_if(sl > INT_MAX, MS_MEDIA_ERR_INTERNAL, "greater than INT_MAX");
435         media_svc_retvm_if(sl < INT_MIN, MS_MEDIA_ERR_INTERNAL, "less than INT_MIN");
436
437         *si = (int)sl;
438
439         return MS_MEDIA_ERR_NONE;
440 }
441
442 static int __media_svc_save_image(unsigned char *image, unsigned int size, char *image_path, uid_t uid)
443 {
444         int ret = MS_MEDIA_ERR_NONE;
445         struct statfs fs;
446         char *thumb_path = NULL;
447         long bsize_kbytes = 0;
448         GError *error = NULL;
449
450         media_svc_retvm_if(!image || size == 0, MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid image");
451         media_svc_sec_debug("start save image, path [%s] image size [%d]", image_path, size);
452
453         ret = ms_user_get_root_thumb_store_path(uid, &thumb_path);
454         media_svc_retvm_if(ret != MS_MEDIA_ERR_NONE, ret, "ms_user_get_root_thumb_store_path error");
455
456         ret = statfs(thumb_path, &fs);
457         g_free(thumb_path);
458         media_svc_retvm_if(ret == -1, MS_MEDIA_ERR_INTERNAL, "statfs failed");
459
460         bsize_kbytes = fs.f_bsize >> 10;
461         media_svc_retvm_if((bsize_kbytes * fs.f_bavail) < 1024, MS_MEDIA_ERR_NOT_ENOUGH_SPACE, "Not enough space");
462
463         if (!g_file_set_contents(image_path, (const gchar *)image, (gssize)size, &error)) {
464                 media_svc_error("g_file_set_contents faild:%s", error->message);
465                 g_error_free(error);
466                 return MS_MEDIA_ERR_INTERNAL;
467         }
468
469         return MS_MEDIA_ERR_NONE;
470 }
471
472 static char *__media_svc_get_title_from_filepath(const char *path)
473 {
474         char *filename = NULL;
475         char *title = NULL;
476         char *last_dot = NULL;
477
478         media_svc_retvm_if(!STRING_VALID(path), NULL, "Invalid path");
479
480         filename = g_path_get_basename(path);
481
482         last_dot = strrchr(filename, '.');
483         if (last_dot) {
484                 title = g_strndup(filename, last_dot - filename);
485                 g_free(filename);
486         } else {
487                 title = filename;
488         }
489
490         media_svc_debug("extract title is [%s]", title);
491
492         return title;
493 }
494
495 void _media_svc_remove_file(const char *path)
496 {
497         if (!STRING_VALID(path))
498                 return;
499
500         if (remove(path) != 0)
501                 media_svc_stderror("fail to remove file result");
502 }
503
504 int _media_svc_get_thumbnail_path(char *thumb_path, const char *pathname, const char *img_format, uid_t uid)
505 {
506         int ret = MS_MEDIA_ERR_NONE;
507         char file_ext[MEDIA_SVC_FILE_EXT_LEN_MAX + 1] = {0, };
508         char hash[THUMB_HASH_LEN] = {0, };
509         char *thumb_dir = NULL;
510
511         ret = ms_user_get_root_thumb_store_path(uid, &thumb_dir);
512         media_svc_retvm_if(!STRING_VALID(thumb_dir), MS_MEDIA_ERR_INTERNAL, "ms_user_get_root_thumb_store_path failed");
513
514         if (!g_file_test(thumb_dir, G_FILE_TEST_IS_DIR)) {
515                 media_svc_error("Wrong path[%s]", thumb_dir);
516                 g_free(thumb_dir);
517                 return MS_MEDIA_ERR_INTERNAL;
518         }
519
520         memset(file_ext, 0, sizeof(file_ext));
521         if (!__media_svc_get_file_ext(pathname, file_ext))
522                 media_svc_error("get file ext fail");
523
524         ret = mb_svc_generate_hash_code(pathname, hash, THUMB_HASH_LEN);
525         if (ret != MS_MEDIA_ERR_NONE) {
526                 media_svc_error("mb_svc_generate_hash_code failed : %d", ret);
527                 g_free(thumb_dir);
528                 return MS_MEDIA_ERR_INTERNAL;
529         }
530
531         if (img_format) {
532                 /* 'img_format' is mime-type */
533                 if (!g_str_has_prefix(img_format, IMAGE_PREFIX) || strlen(img_format) == IMAGE_PREFIX_LEN) {
534                         media_svc_error("Not proper img format");
535                         g_free(thumb_dir);
536                         return MS_MEDIA_ERR_INTERNAL;
537                 }
538
539                 snprintf(thumb_path, MEDIA_SVC_PATHNAME_SIZE, "%s/.%s-%s.%s", thumb_dir, file_ext, hash, img_format + IMAGE_PREFIX_LEN);
540         } else {
541                 if (strcasecmp(file_ext, "PNG") == 0)
542                         snprintf(thumb_path, MEDIA_SVC_PATHNAME_SIZE, "%s/.%s-%s.png", thumb_dir, file_ext, hash);
543                 else
544                         snprintf(thumb_path, MEDIA_SVC_PATHNAME_SIZE, "%s/.%s-%s.jpg", thumb_dir, file_ext, hash);
545         }
546
547         g_free(thumb_dir);
548
549         return MS_MEDIA_ERR_NONE;
550 }
551
552 int _media_svc_get_file_time(const char *full_path)
553 {
554         struct stat statbuf = { 0, };
555
556         if (stat(full_path, &statbuf) == -1) {
557                 media_svc_stderror("stat fails.");
558                 return 0;
559         }
560
561         return statbuf.st_mtime;
562 }
563
564 int _media_svc_set_media_info(media_svc_content_info_s *content_info, const char *storage_id, ms_user_storage_type_e storage_type, const char *path, bool refresh)
565 {
566         int ret = MS_MEDIA_ERR_NONE;
567         bool drm_type = false;
568         char mime_type[256] = {0, };
569         media_svc_media_type_e media_type;
570
571         media_svc_retvm_if(!_media_svc_is_valid_storage_type(storage_type), MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid storage_type");
572         media_svc_retvm_if(!STRING_VALID(path), MS_MEDIA_ERR_INVALID_PARAMETER, "path is NULL");
573
574         content_info->path = g_strdup(path);
575         media_svc_retv_del_if(content_info->path == NULL, MS_MEDIA_ERR_INTERNAL, content_info);
576
577         struct stat st;
578         memset(&st, 0, sizeof(struct stat));
579         if (stat(path, &st) == 0) {
580                 content_info->modified_time = st.st_mtime;
581                 content_info->timeline = content_info->modified_time;
582                 content_info->size = st.st_size;
583         } else {
584                 media_svc_stderror("stat failed");
585         }
586
587         /* refresh is TRUE when file modified. so only modified_time and size are changed*/
588         if (refresh) {
589                 media_svc_debug("refresh");
590                 return MS_MEDIA_ERR_NONE;
591         }
592
593         content_info->storage_uuid = g_strdup(storage_id);
594         media_svc_retv_del_if(content_info->storage_uuid == NULL, MS_MEDIA_ERR_INTERNAL, content_info);
595
596         content_info->storage_type = storage_type;
597         time(&content_info->added_time);
598
599         content_info->media_uuid = __media_info_generate_uuid();
600         media_svc_retv_del_if(content_info->media_uuid == NULL, MS_MEDIA_ERR_INTERNAL, content_info);
601
602         content_info->file_name = g_path_get_basename(path);
603         media_svc_retv_del_if(content_info->file_name == NULL, MS_MEDIA_ERR_INTERNAL, content_info);
604
605         /* if the file is DRM file, drm_type value is DRM_TRUE(1).
606         if drm_contentinfo is not NULL, the file is OMA DRM.*/
607         ret = __media_svc_get_mime_type(path, mime_type);
608         media_svc_retv_del_if(ret != MS_MEDIA_ERR_NONE, ret, content_info);
609
610         media_svc_debug("mime [%s]", mime_type);
611         content_info->is_drm = drm_type;
612
613         ret = __media_svc_get_media_type(path, mime_type, &media_type);
614         media_svc_retv_del_if(ret != MS_MEDIA_ERR_NONE, ret, content_info);
615
616         content_info->mime_type = g_strdup(mime_type);
617         media_svc_retv_del_if(content_info->mime_type == NULL, MS_MEDIA_ERR_INTERNAL, content_info);
618
619         media_svc_sec_debug("storage[%d], path[%s], media_type[%d]", storage_type, path, media_type);
620
621         content_info->media_type = media_type;
622
623         return MS_MEDIA_ERR_NONE;
624 }
625
626 static int __image_360_check(const char *path)
627 {
628         FILE *fp = NULL;
629         size_t size = 0, app1_size = 0, exif_app1_xmp_size = 0;
630         unsigned char exif_header[4] = {0, };
631         unsigned char exif_app1[2] = {0, };
632         unsigned char exif_app1_xmp[2] = {0, };
633         unsigned char exif_app1_xmp_t[2] = {0, };
634         GString *xmp_data = NULL;
635         int fdata = 0;
636         int result = 0;
637
638         memset(exif_header, 0x00, sizeof(exif_header));
639         memset(exif_app1, 0x00, sizeof(exif_app1));
640         memset(exif_app1_xmp, 0x00, sizeof(exif_app1_xmp));
641         memset(exif_app1_xmp_t, 0x00, sizeof(exif_app1_xmp_t));
642
643         fp = fopen(path, "rb");
644         if (fp == NULL)
645                 goto ERROR;
646
647         size = fread(exif_header, 1, sizeof(exif_header), fp);
648         if (size != sizeof(exif_header))
649                 goto ERROR;
650
651         if ((exif_header[0] == 0xff) && (exif_header[1] == 0xd8) && (exif_header[2] == 0xff) && (exif_header[3] == 0xe1)) {
652                 size = fread(exif_app1, 1, sizeof(exif_app1), fp);
653                 if (size != sizeof(exif_app1))
654                         goto ERROR;
655
656                 if ((size_t)((exif_app1[0] << 8) | (exif_app1[1])) <= 2)
657                         goto ERROR;
658
659                 app1_size = (size_t)((exif_app1[0] << 8) | (exif_app1[1])) - 2 ;
660                 if (fseek(fp, app1_size, SEEK_CUR) != 0)
661                         goto ERROR;
662
663                 size = fread(exif_app1_xmp, 1, sizeof(exif_app1_xmp), fp);
664                 if (size != sizeof(exif_app1_xmp))
665                         goto ERROR;
666
667                 if ((exif_app1_xmp[0] == 0xff) && (exif_app1_xmp[1] == 0xe1)) {
668                         size = fread(exif_app1_xmp_t, 1, sizeof(exif_app1_xmp_t), fp);
669                         if (size != sizeof(exif_app1_xmp_t))
670                                 goto ERROR;
671
672                         if ((size_t)((exif_app1_xmp_t[0] << 8) | (exif_app1_xmp_t[1])) <= 2)
673                                 goto ERROR;
674
675                         exif_app1_xmp_size = (size_t)((exif_app1_xmp_t[0] << 8) | (exif_app1_xmp_t[1])) - 2;
676
677                         xmp_data = g_string_sized_new(exif_app1_xmp_size);
678
679                         do {
680                                 exif_app1_xmp_size--;
681                                 fdata = fgetc(fp);
682                                 if (fdata == EOF)
683                                         continue;
684                                 if (fdata == '\0')
685                                         continue;
686
687                                 xmp_data = g_string_append_c(xmp_data, (gchar)fdata);
688                         } while (exif_app1_xmp_size > 0);
689
690                         if (strstr(xmp_data->str, "UsePanoramaViewer") &&
691                                 strstr(xmp_data->str, "True") &&
692                                 strstr(xmp_data->str, "ProjectionType") &&
693                                 strstr(xmp_data->str, "equirectangular"))
694                                 result = 1;
695
696                         g_string_free(xmp_data, TRUE);
697                 }
698         }
699
700 ERROR:
701         if (fp) {
702                 fclose(fp);
703                 fp = NULL;
704         }
705
706         return result;
707 }
708
709 static char * __media_svc_get_title(MMHandleType tag, const char *path)
710 {
711         int ret = FILEINFO_ERROR_NONE;
712         char *p = NULL;
713         int size = 0;
714         char *title = NULL;
715
716         if (tag) {
717                 ret = mm_file_get_attrs(tag, MM_FILE_TAG_TITLE, &p, &size, NULL);
718                 if (ret == FILEINFO_ERROR_NONE && size > 0) {
719                         while(p && isspace(*p))
720                                 p++;
721
722                         return g_strdup(p);
723                 }
724         }
725
726         title = __media_svc_get_title_from_filepath(path);
727         if (title)
728                 return title;
729
730         media_svc_error("Can't extract title");
731
732         return g_strdup(MEDIA_SVC_TAG_UNKNOWN);
733 }
734
735 char * _media_svc_get_title_by_path(const char *path)
736 {
737         /* No MMHandleType in media-svc.c */
738         return __media_svc_get_title(NULL, path);
739 }
740
741 int _media_svc_extract_image_metadata(media_svc_content_info_s *content_info)
742 {
743         double value = 0.0;
744         int orient_value = 0;
745         int exif_width = 0;
746         int exif_height = 0;
747         ExifData *ed = NULL;
748         bool has_datetaken = false;
749         double fnumber = 0.0;
750         int iso = 0;
751         char *path = NULL;
752
753         char buf[MEDIA_SVC_METADATA_LEN_MAX + 1] = { '\0' };
754
755         media_svc_retvm_if(!content_info, MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid content_info");
756         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);
757         media_svc_retvm_if(!STRING_VALID(content_info->path), MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid path");
758
759         path = content_info->path;
760         content_info->media_meta.title = __media_svc_get_title(NULL, path);
761
762         content_info->media_meta.latitude = MEDIA_SVC_DEFAULT_GPS_VALUE;
763         content_info->media_meta.longitude = MEDIA_SVC_DEFAULT_GPS_VALUE;
764         content_info->media_meta.altitude = MEDIA_SVC_DEFAULT_GPS_VALUE;
765
766         /* Not used. But to preserved the behavior, set MEDIA_SVC_TAG_UNKNOWN. */
767         content_info->media_meta.album = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
768         content_info->media_meta.artist = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
769         content_info->media_meta.album_artist = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
770         content_info->media_meta.genre = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
771         content_info->media_meta.composer = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
772         content_info->media_meta.year = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
773         content_info->media_meta.copyright = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
774         content_info->media_meta.track_num = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
775
776         /* Load an ExifData object from an EXIF file */
777         ed = exif_data_new_from_file(path);
778         if (!ed) {
779                 media_svc_sec_debug("There is no exif data in [ %s ]", path);
780                 goto GET_WIDTH_HEIGHT;
781         }
782
783         content_info->media_meta.is_360 = __image_360_check(path);
784
785         memset(buf, 0x00, sizeof(buf));
786         if (__media_svc_get_exif_gps_double(ed, &value, EXIF_TAG_GPS_LATITUDE) == MS_MEDIA_ERR_NONE) {
787                 if (__media_svc_get_exif_gps_str(ed, buf, EXIF_TAG_GPS_LATITUDE_REF) == MS_MEDIA_ERR_NONE) {
788                         if (!g_strcmp0(buf, "S"))
789                                 value *= -1;
790                         content_info->media_meta.latitude = value;
791                 }
792         }
793
794         memset(buf, 0x00, sizeof(buf));
795         if (__media_svc_get_exif_gps_double(ed, &value, EXIF_TAG_GPS_LONGITUDE) == MS_MEDIA_ERR_NONE) {
796                 if (__media_svc_get_exif_gps_str(ed, buf, EXIF_TAG_GPS_LONGITUDE_REF) == MS_MEDIA_ERR_NONE) {
797                         if (!g_strcmp0(buf, "W"))
798                                 value *= -1;
799
800                         content_info->media_meta.longitude = value;
801                 }
802         }
803
804         memset(buf, 0x00, sizeof(buf));
805         if (__media_svc_get_exif_info(ed, buf, NULL, NULL, EXIF_TAG_IMAGE_DESCRIPTION) == MS_MEDIA_ERR_NONE) {
806                 if (strlen(buf) > 0)
807                         content_info->media_meta.description = g_strdup(buf);
808                 else
809                         content_info->media_meta.description = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
810         }
811
812         memset(buf, 0x00, sizeof(buf));
813         if (!has_datetaken && __media_svc_get_exif_info(ed, buf, NULL, NULL, EXIF_TAG_DATE_TIME_ORIGINAL) == MS_MEDIA_ERR_NONE) {
814                 if (strlen(buf) > 0) {
815                         has_datetaken = true;
816                         content_info->media_meta.datetaken = g_strdup(buf);
817
818                         /* This is same as recorded_date */
819                         content_info->media_meta.recorded_date = g_strdup(buf);
820                 }
821         }
822
823         memset(buf, 0x00, sizeof(buf));
824         if (!has_datetaken && __media_svc_get_exif_info(ed, buf, NULL, NULL, EXIF_TAG_DATE_TIME) == MS_MEDIA_ERR_NONE) {
825                 if (strlen(buf) > 0) {
826                         has_datetaken = true;
827                         content_info->media_meta.datetaken = g_strdup(buf);
828
829                         /* This is same as recorded_date */
830                         content_info->media_meta.recorded_date = g_strdup(buf);
831                 }
832         }
833
834         if (has_datetaken) {
835                 content_info->timeline = __media_svc_get_timeline_from_str(content_info->media_meta.datetaken);
836                 if (content_info->timeline == 0)
837                         content_info->timeline = content_info->modified_time;
838                 else
839                         media_svc_debug("Timeline : %ld", content_info->timeline);
840         }
841
842         memset(buf, 0x00, sizeof(buf));
843         /* Get exposure_time value from exif. */
844         if (__media_svc_get_exif_info(ed, buf, NULL, NULL, EXIF_TAG_EXPOSURE_TIME) == MS_MEDIA_ERR_NONE) {
845                 if (strlen(buf) > 0)
846                         content_info->media_meta.exposure_time = g_strdup(buf);
847         }
848
849         /* Get fnumber value from exif. */
850         if (__media_svc_get_exif_info(ed, NULL, NULL, &fnumber, EXIF_TAG_FNUMBER) == MS_MEDIA_ERR_NONE)
851                 content_info->media_meta.fnumber = fnumber;
852
853         /* Get iso value from exif. */
854         if (__media_svc_get_exif_info(ed, NULL, &iso, NULL, EXIF_TAG_ISO_SPEED_RATINGS) == MS_MEDIA_ERR_NONE)
855                 content_info->media_meta.iso = iso;
856
857         memset(buf, 0x00, sizeof(buf));
858         /* Get model value from exif. */
859         if (__media_svc_get_exif_info(ed, buf, NULL, NULL, EXIF_TAG_MODEL) == MS_MEDIA_ERR_NONE) {
860                 if (strlen(buf) > 0)
861                         content_info->media_meta.model = g_strdup(buf);
862         }
863
864         /* Get orientation value from exif. */
865         if (__media_svc_get_exif_info(ed, NULL, &orient_value, NULL, EXIF_TAG_ORIENTATION) == MS_MEDIA_ERR_NONE) {
866                 if (orient_value >= NOT_AVAILABLE && orient_value <= ROT_270)
867                         content_info->media_meta.orientation = orient_value;
868         }
869
870         /* Get width value from exif. */
871         if (__media_svc_get_exif_info(ed, NULL, &exif_width, NULL, EXIF_TAG_PIXEL_X_DIMENSION) == MS_MEDIA_ERR_NONE) {
872                 if (exif_width > 0)
873                         content_info->media_meta.width = exif_width;
874         }
875
876         /* Get height value from exif. */
877         if (__media_svc_get_exif_info(ed, NULL, &exif_height, NULL, EXIF_TAG_PIXEL_Y_DIMENSION) == MS_MEDIA_ERR_NONE) {
878                 if (exif_height > 0)
879                         content_info->media_meta.height = exif_height;
880         }
881
882         if (ed)
883                 exif_data_unref(ed);
884
885 GET_WIDTH_HEIGHT:
886
887         if (content_info->media_meta.width == 0 || content_info->media_meta.height == 0) {
888                 /*Get image width, height*/
889                 unsigned int img_width = 0;
890                 unsigned int img_height = 0;
891                 mm_util_img_codec_type img_type = IMG_CODEC_UNKNOWN_TYPE;
892
893                 mm_util_extract_image_info(path, &img_type, &img_width, &img_height);
894                 if (content_info->media_meta.width == 0)
895                         content_info->media_meta.width = img_width;
896
897                 if (content_info->media_meta.height == 0)
898                         content_info->media_meta.height = img_height;
899         }
900
901         return MS_MEDIA_ERR_NONE;
902 }
903
904 static char * __media_svc_get_tag_str_value(MMHandleType tag, const char *tag_name)
905 {
906         int ret = FILEINFO_ERROR_NONE;
907         char *p = NULL;
908         int size = 0;
909
910         ret = mm_file_get_attrs(tag, tag_name, &p, &size, NULL);
911         if (ret == FILEINFO_ERROR_NONE && size > 0)
912                 return g_strdup(p);
913
914         return g_strdup(MEDIA_SVC_TAG_UNKNOWN);
915 }
916
917 int _media_svc_extract_music_metadata_for_update(media_svc_content_info_s *content_info, const char *path)
918 {
919         MMHandleType tag = 0;
920         int mmf_error = FILEINFO_ERROR_NONE;
921
922         content_info->path = g_strdup(path);
923
924         mmf_error = mm_file_create_tag_attrs_no_albumart(&tag, content_info->path);
925         if (mmf_error == FILEINFO_ERROR_NONE) {
926                 content_info->media_meta.title = __media_svc_get_title(tag, content_info->path);
927                 content_info->media_meta.album = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_ALBUM);
928                 content_info->media_meta.artist = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_ARTIST);
929                 content_info->media_meta.album_artist = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_ALBUM_ARTIST);
930                 content_info->media_meta.genre = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_GENRE);
931                 content_info->media_meta.description = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_DESCRIPTION);
932                 content_info->media_meta.composer = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_AUTHOR);
933                 content_info->media_meta.copyright = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_COPYRIGHT);
934         } else {
935                 content_info->media_meta.title = __media_svc_get_title(NULL, content_info->path);
936         }
937
938         mm_file_destroy_tag_attrs(tag);
939
940         return MS_MEDIA_ERR_NONE;
941 }
942
943 int _media_svc_extract_media_metadata(sqlite3 *handle, bool is_direct, media_svc_content_info_s *content_info, uid_t uid)
944 {
945         MMHandleType content = 0;
946         MMHandleType tag = 0;
947         char *p = NULL;
948         unsigned char *image = NULL;
949         unsigned int size = 0;
950         int mmf_error = FILEINFO_ERROR_NONE;
951         int album_id = 0;
952         int ret = MS_MEDIA_ERR_NONE;
953         int convert_value = 0;
954         int cdis_value = 0;
955
956         /*Get Content Tag attribute ===========*/
957         if (content_info->storage_type == MS_USER_STORAGE_EXTERNAL_USB)
958                 mmf_error = mm_file_create_tag_attrs_no_albumart(&tag, content_info->path);
959         else
960                 mmf_error = mm_file_create_tag_attrs(&tag, content_info->path);
961
962         if (mmf_error == FILEINFO_ERROR_NONE) {
963                 content_info->media_meta.title = __media_svc_get_title(tag, content_info->path);
964                 content_info->media_meta.album = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_ALBUM);
965                 content_info->media_meta.artist = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_ARTIST);
966                 content_info->media_meta.album_artist = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_ALBUM_ARTIST);
967                 content_info->media_meta.genre = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_GENRE);
968                 content_info->media_meta.description = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_DESCRIPTION);
969                 content_info->media_meta.composer = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_AUTHOR);
970                 content_info->media_meta.copyright = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_COPYRIGHT);
971                 content_info->media_meta.track_num = __media_svc_get_tag_str_value(tag, MM_FILE_TAG_TRACK_NUM);
972
973                 mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_RECDATE, &p, &size, NULL);
974                 if ((mmf_error == FILEINFO_ERROR_NONE) && (size > 0)) {
975                         if (g_str_has_suffix(content_info->mime_type, "mp4") || g_str_has_suffix(content_info->mime_type, "3gpp")) {
976                                 /*Creation time format is 2013-01-01 00:00:00 +0000. change it to 2013:01:01 00:00:00  +0000 like exif time format*/
977                                 char *p_value = g_strdelimit(g_strdup(p), "-", ':');
978                                 content_info->media_meta.recorded_date = g_strdup_printf("%s +0000", p_value);
979                                 g_free(p_value);
980                         } else {
981                                 content_info->media_meta.recorded_date = g_strdup(p);
982                         }
983
984                         if (STRING_VALID(content_info->media_meta.recorded_date)) {
985                                 content_info->timeline = __media_svc_get_timeline_from_str(content_info->media_meta.recorded_date);
986                                 if (content_info->timeline == 0)
987                                         content_info->timeline = content_info->modified_time;
988
989                                 /* This is same as datetaken */
990                                 /* Remove compensation string */
991                                 if (strlen(content_info->media_meta.recorded_date) > MEDIA_SVC_DEFAULT_FORMAT_LEN) {
992                                         content_info->media_meta.datetaken = g_strndup(content_info->media_meta.recorded_date, MEDIA_SVC_DEFAULT_FORMAT_LEN);
993                                         g_free(content_info->media_meta.recorded_date);
994                                         content_info->media_meta.recorded_date = g_strdup(content_info->media_meta.datetaken);
995                                 } else {
996                                         content_info->media_meta.datetaken = g_strdup(content_info->media_meta.recorded_date);
997                                 }
998                         }
999                 }
1000
1001                 mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_DATE, &p, &size, NULL);
1002                 if (mmf_error == FILEINFO_ERROR_NONE && size == 4) {
1003                         if (__media_svc_safe_atoi(p, &convert_value) == MS_MEDIA_ERR_NONE)
1004                                 content_info->media_meta.year = g_strdup(p);
1005                 }
1006
1007                 if (!content_info->media_meta.year)
1008                                 content_info->media_meta.year = g_strdup(MEDIA_SVC_TAG_UNKNOWN);
1009
1010                 mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_RATING, &p, &size, NULL);
1011                 if (mmf_error == FILEINFO_ERROR_NONE && size > 0) {
1012                         if (__media_svc_safe_atoi(p, &convert_value) == MS_MEDIA_ERR_NONE)
1013                                 content_info->media_meta.rating = convert_value;
1014                 } else {
1015                         content_info->media_meta.rating = 0;
1016                 }
1017
1018                 mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_SPHERICAL, &content_info->media_meta.is_360, NULL);
1019
1020                 /*Do not extract artwork for the USB Storage content*/
1021                 if (content_info->storage_type != MS_USER_STORAGE_EXTERNAL_USB) {
1022                         mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_ARTWORK, &image, &size, NULL);
1023                         if (mmf_error != FILEINFO_ERROR_NONE)
1024                                 media_svc_error("fail to get tag artwork - err(%x)", mmf_error);
1025
1026                         mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_ARTWORK_SIZE, &size, NULL);
1027                         if (mmf_error != FILEINFO_ERROR_NONE)
1028                                 media_svc_error("fail to get artwork size - err(%x)", mmf_error);
1029
1030                         if (image != NULL && size > 0) {
1031                                 char thumb_path[MEDIA_SVC_PATHNAME_SIZE] = "\0";
1032                                 int artwork_mime_size = -1;
1033
1034                                 mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_ARTWORK_MIME, &p, &artwork_mime_size, NULL);
1035                                 if ((mmf_error == FILEINFO_ERROR_NONE) && (artwork_mime_size > 0)) {
1036                                         ret = _media_svc_get_thumbnail_path(thumb_path, content_info->path, p, uid);
1037                                         if (ret != MS_MEDIA_ERR_NONE) {
1038                                                 media_svc_error("Fail to Get Thumbnail Path");
1039                                         } else {
1040                                                 ret = __media_svc_save_image(image, size, thumb_path, uid);
1041                                                 if (ret != MS_MEDIA_ERR_NONE) {
1042                                                         media_svc_error("Fail to Save Image");
1043                                                 } else {
1044                                                         content_info->thumbnail_path = g_strdup(thumb_path);
1045                                                 }
1046                                         }
1047                                 }
1048                         }
1049                 }
1050
1051                 /*Initialize album_id to 0. below code will set the album_id*/
1052                 content_info->album_id = album_id;
1053                 ret = _media_svc_get_album_id(handle, content_info->media_meta.album, content_info->media_meta.artist, &album_id);
1054                 if (ret != MS_MEDIA_ERR_NONE) {
1055                         if (ret == MS_MEDIA_ERR_DB_NO_RECORD) {
1056                                 media_svc_debug("album does not exist. So start to make album art");
1057                                 if ((g_strcmp0(content_info->media_meta.album, MEDIA_SVC_TAG_UNKNOWN)) &&
1058                                         (g_strcmp0(content_info->media_meta.artist, MEDIA_SVC_TAG_UNKNOWN)))
1059                                         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);
1060                                 else
1061                                         ret = _media_svc_append_album(handle, is_direct, content_info->media_meta.album, content_info->media_meta.artist, NULL, &album_id, uid);
1062
1063                                 content_info->album_id = album_id;
1064                         }
1065                 } else {
1066                         content_info->album_id = album_id;
1067                 }
1068
1069                 content_info->media_meta.longitude = MEDIA_SVC_DEFAULT_GPS_VALUE;
1070                 content_info->media_meta.latitude = MEDIA_SVC_DEFAULT_GPS_VALUE;
1071                 content_info->media_meta.altitude = MEDIA_SVC_DEFAULT_GPS_VALUE;
1072
1073                 if (content_info->media_type == MEDIA_SVC_MEDIA_TYPE_VIDEO) {
1074                         double longitude = 0.0;
1075                         double latitude = 0.0;
1076                         double altitude = 0.0;
1077
1078                         mm_file_get_attrs(tag, MM_FILE_TAG_LONGITUDE, &longitude,
1079                                 MM_FILE_TAG_LATIDUE, &latitude,
1080                                 MM_FILE_TAG_ALTIDUE, &altitude,
1081                                 NULL);
1082
1083                         content_info->media_meta.longitude = (longitude == 0.0) ? MEDIA_SVC_DEFAULT_GPS_VALUE : longitude;
1084                         content_info->media_meta.latitude = (latitude == 0.0) ? MEDIA_SVC_DEFAULT_GPS_VALUE : latitude;
1085                         content_info->media_meta.altitude = (altitude == 0.0) ? MEDIA_SVC_DEFAULT_GPS_VALUE : altitude;
1086
1087                         mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_CDIS, &cdis_value, NULL);
1088                         if (mmf_error != FILEINFO_ERROR_NONE)
1089                                 cdis_value = 0;
1090
1091                         media_svc_debug("CDIS : %d", cdis_value);
1092
1093                         mmf_error = mm_file_get_attrs(tag, MM_FILE_TAG_ROTATE, &p, &size, NULL);
1094                         if ((mmf_error == FILEINFO_ERROR_NONE) && (size > 0)) {
1095                                 content_info->media_meta.orientation = atoi(p);
1096                         } else {
1097                                 content_info->media_meta.orientation = 0;
1098                                 media_svc_debug("fail to get video orientation attr - err(%x)", mmf_error);
1099                         }
1100                 }
1101
1102                 mmf_error = mm_file_destroy_tag_attrs(tag);
1103                 if (mmf_error != FILEINFO_ERROR_NONE)
1104                         media_svc_error("fail to free tag attr - err(%x)", mmf_error);
1105         }       else {
1106                 content_info->media_meta.title = __media_svc_get_title(NULL, content_info->path);
1107                 content_info->album_id = album_id;
1108         }
1109
1110         /*Get Content attribute ===========*/
1111         if (cdis_value == 1)
1112                 mmf_error = mm_file_create_content_attrs_safe(&content, content_info->path);
1113         else
1114                 mmf_error = mm_file_create_content_attrs_simple(&content, content_info->path);
1115
1116         media_svc_retvm_if(mmf_error != FILEINFO_ERROR_NONE, MS_MEDIA_ERR_NONE, "mm_file_create_content_attrs failed");
1117
1118         if (content_info->media_type == MEDIA_SVC_MEDIA_TYPE_VIDEO) {
1119                 int audio_bitrate = 0;
1120                 int video_bitrate = 0;
1121
1122                 mm_file_get_attrs(content, MM_FILE_CONTENT_DURATION, &content_info->media_meta.duration,
1123                         MM_FILE_CONTENT_AUDIO_BITRATE, &audio_bitrate,
1124                         MM_FILE_CONTENT_VIDEO_BITRATE, &video_bitrate,
1125                         MM_FILE_CONTENT_VIDEO_WIDTH, &content_info->media_meta.width,
1126                         MM_FILE_CONTENT_VIDEO_HEIGHT, &content_info->media_meta.height,
1127                         NULL);
1128
1129                 content_info->media_meta.bitrate = audio_bitrate + video_bitrate;
1130         } else {
1131                 mm_file_get_attrs(content, MM_FILE_CONTENT_DURATION, &content_info->media_meta.duration,
1132                         MM_FILE_CONTENT_AUDIO_BITRATE, &content_info->media_meta.bitrate,
1133                         MM_FILE_CONTENT_AUDIO_SAMPLERATE, &content_info->media_meta.samplerate,
1134                         MM_FILE_CONTENT_AUDIO_CHANNELS, &content_info->media_meta.channel,
1135                         MM_FILE_CONTENT_AUDIO_BITPERSAMPLE, &content_info->media_meta.bitpersample,
1136                         NULL);
1137         }
1138
1139         mm_file_destroy_content_attrs(content);
1140
1141         return MS_MEDIA_ERR_NONE;
1142 }
1143
1144 static gchar * __media_svc_get_zipfile_string(zip_t *z, const char *fname)
1145 {
1146         int err = 0;
1147         zip_int64_t index_num = 0;
1148         zip_file_t *file = NULL;
1149         zip_stat_t sb = {0, };
1150         gchar *buf = NULL;
1151
1152         media_svc_retvm_if(!z, NULL, "z is NULL");
1153         media_svc_retvm_if(!fname, NULL, "fname is NULL");
1154
1155         index_num = zip_name_locate(z, fname, ZIP_FL_NOCASE);
1156         media_svc_retvm_if(index_num == -1, NULL, "fname is not exists [%s]", fname);
1157
1158         err = zip_stat_index(z, index_num, ZIP_STAT_SIZE, &sb);
1159         media_svc_retvm_if(err == -1, NULL, "zip_stat_index failed");
1160
1161         file = zip_fopen_index(z, index_num, ZIP_FL_UNCHANGED);
1162         media_svc_retvm_if(!file, NULL, "zip_fopen_index failed");
1163
1164         buf = g_malloc0(sb.size + 1);
1165
1166         err = zip_fread(file, buf, sb.size);
1167         zip_fclose(file);
1168
1169         if (err == -1) {
1170                 g_free(buf);
1171                 buf = NULL;
1172         }
1173
1174         return buf;
1175 }
1176
1177 static xmlNodePtr __media_svc_find_node(xmlNodePtr node, const char *key)
1178 {
1179         xmlNodePtr tmp = NULL;
1180
1181         media_svc_retvm_if(!node, NULL, "node is NULL");
1182         media_svc_retvm_if(!key, NULL, "key is NULL");
1183
1184         for (tmp = node->children; tmp; tmp = tmp->next) {
1185                 if (xmlIsBlankNode(tmp))
1186                         continue;
1187
1188                 if (g_str_has_suffix((gchar *)tmp->name, key))
1189                         return tmp;
1190         }
1191
1192         return NULL;
1193 }
1194
1195 static char * __media_svc_remove_escape_c(const char *value)
1196 {
1197         int start = -1;
1198         int end = 0;
1199         int len, i;
1200
1201         media_svc_retv_if(!value, NULL);
1202
1203         len = strlen(value);
1204
1205         for (i = 0; i < len; i++) {
1206                 if (value[i] != 10 && value[i] != 32) { // 10='\n' 32=' '
1207                         if (start == -1)
1208                                 start = i;
1209
1210                         end = i;
1211                 }
1212         }
1213
1214         end = end - start + 1;
1215
1216         return g_strndup(value + start, end);
1217 }
1218
1219 static char * __media_svc_find_and_get_value(xmlNodePtr node, const char *key)
1220 {
1221         xmlNodePtr tmp = NULL;
1222         char *tmp_res = NULL;
1223         char *res = NULL;
1224
1225         media_svc_retvm_if(!node, NULL, "node is NULL");
1226         media_svc_retvm_if(!key, NULL, "key is NULL");
1227
1228         for (tmp = node->children; tmp; tmp = tmp->next) {
1229                 if (xmlIsBlankNode(tmp))
1230                         continue;
1231
1232                 if (tmp->children) {
1233                         tmp_res = __media_svc_find_and_get_value(tmp, key);
1234                         if (tmp_res) {
1235                                 res = __media_svc_remove_escape_c(tmp_res);
1236                                 xmlFree(tmp_res);
1237                                 return res;
1238                         }
1239                 }
1240
1241                 if (g_str_has_suffix((gchar *)tmp->name, key))
1242                         return (char *)xmlNodeGetContent(tmp);
1243         }
1244
1245         return NULL;
1246 }
1247
1248 static gboolean __media_svc_get_epub_root_file(zip_t *z, char **opf_file)
1249 {
1250         gchar *buf = NULL;
1251         gchar *tmp_buf = NULL;
1252         xmlDocPtr doc = NULL;
1253         xmlNodePtr node = NULL;
1254
1255         media_svc_retvm_if(!z, FALSE, "z is NULL");
1256         media_svc_retvm_if(!opf_file, FALSE, "opf_file is NULL");
1257
1258         buf = __media_svc_get_zipfile_string(z, "META-INF/container.xml");
1259         media_svc_retvm_if(!buf, FALSE, "buf is NULL");
1260
1261         tmp_buf = g_strrstr(buf, ">");
1262         if (tmp_buf)
1263                 *(tmp_buf + 1) = '\0';
1264
1265         doc = xmlParseDoc((const xmlChar *)buf);
1266         g_free(buf);
1267         media_svc_retvm_if(!doc, FALSE, "doc is NULL");
1268
1269         node = xmlDocGetRootElement(doc);
1270         node = __media_svc_find_node(node, "rootfiles");
1271         node = __media_svc_find_node(node, "rootfile");
1272
1273         *opf_file = (char *)xmlGetProp(node, (const xmlChar *)"full-path");
1274         media_svc_sec_debug("OPF [%s]", *opf_file);
1275         xmlFreeDoc(doc);
1276
1277         return TRUE;
1278 }
1279
1280 static gboolean __media_svc_get_xml_metadata(const xmlChar *buffer, gboolean is_pdf, media_svc_content_info_s *content_info)
1281 {
1282         xmlDocPtr doc = NULL;
1283         xmlNodePtr root = NULL;
1284
1285         media_svc_retvm_if(!buffer, FALSE, "buffer is NULL");
1286         media_svc_retvm_if(!content_info, FALSE, "content_info is NULL");
1287
1288         doc = xmlParseDoc(buffer);
1289         media_svc_retv_if(!doc, FALSE);
1290
1291         root = xmlDocGetRootElement(doc);
1292         if (!root) {
1293                 xmlFreeDoc(doc);
1294                 return FALSE;
1295         }
1296
1297         content_info->media_meta.title = __media_svc_find_and_get_value(root, "title");
1298         if (is_pdf && !content_info->media_meta.title) {
1299                 xmlFreeDoc(doc);
1300                 return FALSE;
1301         }
1302
1303         content_info->media_meta.composer = __media_svc_find_and_get_value(root, "creator");
1304         if (!content_info->media_meta.composer)
1305                 content_info->media_meta.composer = __media_svc_find_and_get_value(root, "author");
1306
1307         content_info->media_meta.copyright = __media_svc_find_and_get_value(root, "publisher");
1308         content_info->media_meta.recorded_date = __media_svc_find_and_get_value(root, "date");
1309         content_info->media_meta.genre = __media_svc_find_and_get_value(root, "subject");
1310         content_info->media_meta.description = __media_svc_find_and_get_value(root, "description");
1311
1312         xmlFreeDoc(doc);
1313
1314         return TRUE;
1315 }
1316
1317 static int __media_svc_get_epub_metadata(media_svc_content_info_s *content_info)
1318 {
1319         int err = 0;
1320         zip_t *z = NULL;
1321         gchar *buf = NULL;
1322         char *opf_path = NULL;
1323
1324         media_svc_retvm_if(!content_info, MS_MEDIA_ERR_INVALID_PARAMETER, "content_info is NULL");
1325
1326         //1. open epub
1327         z = zip_open(content_info->path, ZIP_RDONLY, &err);
1328         media_svc_retvm_if(err == -1, MS_MEDIA_ERR_INTERNAL, "zip_open failed");
1329
1330         //2. find and read opf file
1331         if (!__media_svc_get_epub_root_file(z, &opf_path)) {
1332                 media_svc_error("__media_svc_get_epub_root_file failed");
1333                 zip_close(z);
1334                 return MS_MEDIA_ERR_INTERNAL;
1335         }
1336
1337         //3. get metadata
1338         buf = __media_svc_get_zipfile_string(z, opf_path);
1339         xmlFree(opf_path);
1340         zip_close(z);
1341         media_svc_retvm_if(!buf, MS_MEDIA_ERR_INTERNAL, "__media_svc_get_zipfile_string failed");
1342
1343         if (!__media_svc_get_xml_metadata((const xmlChar *)buf, FALSE, content_info))
1344                 media_svc_error("__media_svc_get_xml_metadata failed");
1345
1346         g_free(buf);
1347
1348         return MS_MEDIA_ERR_NONE;
1349 }
1350
1351 static int __media_svc_get_pdf_metadata(media_svc_content_info_s *content_info)
1352 {
1353     int fd = 0;
1354     int start_pos = 0;
1355     int end_pos = 0;
1356     int cur_pos = 0;
1357     int search_limit = 0;
1358     char tmp[MEDIA_SVC_PDF_BUF_SIZE + 1] = {0, };
1359     gchar *meta_buf = NULL;
1360     char *found = NULL;
1361
1362         media_svc_retvm_if(!content_info, MS_MEDIA_ERR_INVALID_PARAMETER, "content_info is NULL");
1363         media_svc_retvm_if(content_info->size < 256, MS_MEDIA_ERR_INTERNAL, "open failed");
1364
1365         fd = open(content_info->path, O_RDONLY);
1366         media_svc_retvm_if(fd < 0, MS_MEDIA_ERR_INTERNAL, "open failed");
1367
1368         search_limit = content_info->size - MEDIA_SVC_PDF_TAG_TAIL_LEN;
1369
1370         while (cur_pos <= search_limit) {
1371                 if (lseek(fd, cur_pos, SEEK_SET) == -1)
1372                         break;
1373
1374                 memset(&tmp, 0x00, MEDIA_SVC_PDF_BUF_SIZE + 1);
1375
1376                 if (read(fd, &tmp, MEDIA_SVC_PDF_BUF_SIZE) != MEDIA_SVC_PDF_BUF_SIZE) {
1377                         media_svc_error("read failed");
1378                         break;
1379                 }
1380
1381                 //1.Find <x:xmpmeta .. </x:xmpmeta> block
1382                 if (start_pos == 0 && (found = strstr(tmp, "<x:xmpmeta"))) {
1383                         start_pos = cur_pos + (found - tmp);
1384 //                      media_svc_error("FIND START_POS[%d]", start_pos);
1385                         found = NULL;
1386                 }
1387
1388
1389                 if (start_pos != 0 && (found = strstr(tmp, "</x:xmpmeta>"))) {
1390                         end_pos = cur_pos + (found - tmp) + MEDIA_SVC_PDF_TAG_TAIL_LEN;
1391 //                      media_svc_error("FIND END_POS[%d]", end_pos);
1392                         found = NULL;
1393                 }
1394
1395                 //2.get metadata using xml parser
1396                 if (start_pos && end_pos) {
1397                         if (lseek(fd, start_pos, SEEK_SET) == -1)
1398                                 break;
1399
1400                         meta_buf = g_malloc0(end_pos - start_pos + 1);
1401
1402                         if (read(fd, meta_buf, end_pos - start_pos) == end_pos - start_pos) {
1403                                 if (__media_svc_get_xml_metadata((const xmlChar *)meta_buf, TRUE, content_info)) {
1404                                         g_free(meta_buf);
1405                                         break;
1406                                 }
1407                         }
1408
1409                         g_free(meta_buf);
1410
1411                         start_pos = 0;
1412                         end_pos = 0;
1413                 }
1414
1415                 cur_pos += 240;
1416
1417         }
1418
1419         close(fd);
1420
1421         return MS_MEDIA_ERR_NONE;
1422 }
1423
1424 int _media_svc_extract_book_metadata(media_svc_content_info_s *content_info)
1425 {
1426         media_svc_retvm_if(!content_info, MS_MEDIA_ERR_INVALID_PARAMETER, "content info is NULL");
1427
1428         if (g_str_has_suffix(content_info->mime_type, "epub+zip"))
1429                 return __media_svc_get_epub_metadata(content_info);
1430         else
1431                 return __media_svc_get_pdf_metadata(content_info);
1432 }
1433
1434 void _media_svc_destroy_content_info(media_svc_content_info_s *content_info)
1435 {
1436         media_svc_retm_if(!content_info, "content info is NULL");
1437
1438         /* Delete media_svc_content_info_s */
1439         g_free(content_info->media_uuid);
1440         g_free(content_info->path);
1441         g_free(content_info->file_name);
1442         g_free(content_info->mime_type);
1443         g_free(content_info->thumbnail_path);
1444         g_free(content_info->storage_uuid);
1445
1446         /* Delete media_svc_content_meta_s */
1447         g_free(content_info->media_meta.title);
1448         g_free(content_info->media_meta.album);
1449         g_free(content_info->media_meta.artist);
1450         g_free(content_info->media_meta.album_artist);
1451         g_free(content_info->media_meta.genre);
1452         g_free(content_info->media_meta.composer);
1453         g_free(content_info->media_meta.year);
1454         g_free(content_info->media_meta.recorded_date);
1455         g_free(content_info->media_meta.copyright);
1456         g_free(content_info->media_meta.track_num);
1457         g_free(content_info->media_meta.description);
1458         g_free(content_info->media_meta.datetaken);
1459         g_free(content_info->media_meta.exposure_time);
1460         g_free(content_info->media_meta.model);
1461
1462         g_free(content_info->file_name_pinyin);
1463         g_free(content_info->media_meta.title_pinyin);
1464         g_free(content_info->media_meta.album_pinyin);
1465         g_free(content_info->media_meta.artist_pinyin);
1466         g_free(content_info->media_meta.album_artist_pinyin);
1467         g_free(content_info->media_meta.genre_pinyin);
1468         g_free(content_info->media_meta.composer_pinyin);
1469 }
1470
1471 int _media_svc_create_thumbnail(const char *path, char *thumb_path, media_svc_media_type_e media_type, uid_t uid)
1472 {
1473         int ret = MS_MEDIA_ERR_NONE;
1474
1475         media_svc_retvm_if(!path, MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid path");
1476         media_svc_retvm_if(!thumb_path, MS_MEDIA_ERR_INVALID_PARAMETER, "Invalid thumb_path");
1477         media_svc_retvm_if(!g_file_test(path, G_FILE_TEST_IS_REGULAR), MS_MEDIA_ERR_INVALID_PARAMETER, "File doesn't exist[%s]", path);
1478
1479         ms_user_storage_type_e store_type = -1;
1480         ret = ms_user_get_storage_type(uid, path, &store_type);
1481
1482         if ((ret != MS_MEDIA_ERR_NONE) || ((store_type != MS_USER_STORAGE_INTERNAL) && (store_type != MS_USER_STORAGE_EXTERNAL))) {
1483                 media_svc_sec_error("origin path(%s) is invalid. err : [%d] store_type [%d]", path, ret, store_type);
1484                 return MS_MEDIA_ERR_INVALID_PARAMETER;
1485         }
1486
1487         media_svc_sec_debug("Path[%s] Type[%d]", path, media_type);
1488
1489         //1. make hash path
1490         ret = _media_svc_get_thumbnail_path(thumb_path, path, NULL, uid);
1491         if (ret != MS_MEDIA_ERR_NONE) {
1492                 media_svc_error("_media_svc_get_thumbnail_path failed - %d", ret);
1493                 SAFE_STRLCPY(thumb_path, "", MAX_FILEPATH_LEN);
1494                 return ret;
1495         }
1496
1497         //2. save thumbnail
1498         if (media_type == MEDIA_SVC_MEDIA_TYPE_IMAGE)
1499                 return create_image_thumbnail_to_file(path, MEDIA_SVC_THUMB_WIDTH, MEDIA_SVC_THUMB_HEIGHT, thumb_path, true);
1500         else
1501                 return create_video_thumbnail_to_file(path, MEDIA_SVC_THUMB_WIDTH, MEDIA_SVC_THUMB_HEIGHT, thumb_path, true);
1502
1503 }
1504
1505 int _media_svc_get_pinyin_str(const char *src_str, char **pinyin_str)
1506 {
1507         int ret = MS_MEDIA_ERR_NONE;
1508         int size = 0;
1509         pinyin_name_s *pinyinname = NULL;
1510
1511         media_svc_retvm_if(!STRING_VALID(src_str), MS_MEDIA_ERR_INVALID_PARAMETER, "String is NULL");
1512         media_svc_retvm_if(pinyin_str == NULL, MS_MEDIA_ERR_INVALID_PARAMETER, "pinyin_str is NULL");
1513
1514         *pinyin_str = NULL;
1515
1516         ret = _media_svc_convert_chinese_to_pinyin(src_str, &pinyinname, &size);
1517         if (ret == MS_MEDIA_ERR_NONE) {
1518                 if (size > 0 && STRING_VALID(pinyinname[0].pinyin_name))
1519                         *pinyin_str = g_strdup(pinyinname[0].pinyin_name);
1520                 else
1521                         *pinyin_str = g_strdup(src_str);        /* Return Original Non China Character */
1522         }
1523
1524         _media_svc_pinyin_free(pinyinname, size);
1525
1526         return ret;
1527 }
1528
1529 bool _media_svc_check_pinyin_support(void)
1530 {
1531         int ret = SYSTEM_INFO_ERROR_NONE;
1532         bool is_supported = false;
1533         static int media_svc_pinyin_support = -1;
1534
1535         if (media_svc_pinyin_support == -1) {
1536                 ret = system_info_get_platform_bool("http://tizen.org/feature/content.filter.pinyin", &is_supported);
1537                 if (ret != SYSTEM_INFO_ERROR_NONE) {
1538                         media_svc_debug("SYSTEM_INFO_ERROR: content.filter.pinyin [%d]", ret);
1539                         return false;
1540                 }
1541
1542                 media_svc_pinyin_support = is_supported;
1543         }
1544
1545         return media_svc_pinyin_support;
1546 }
1547
1548 int _media_svc_get_media_type(const char *path, int *mediatype)
1549 {
1550         int ret = MS_MEDIA_ERR_NONE;
1551         char mime_type[256] = {0};
1552         media_svc_media_type_e media_type = MEDIA_SVC_MEDIA_TYPE_OTHER;
1553
1554         media_svc_retvm_if(mediatype == NULL, MS_MEDIA_ERR_INVALID_PARAMETER, "mediatype is NULL");
1555
1556         ret = __media_svc_get_mime_type(path, mime_type);
1557         if (ret == MS_MEDIA_ERR_NONE)
1558                 __media_svc_get_media_type(path, mime_type, &media_type);
1559         else
1560                 media_svc_error("__media_svc_get_mime_type failed");
1561
1562         *mediatype = media_type;
1563
1564         return ret;
1565 }
1566
1567 bool _media_svc_is_valid_storage_type(ms_user_storage_type_e storage_type)
1568 {
1569         switch (storage_type) {
1570         case MS_USER_STORAGE_INTERNAL:
1571         case MS_USER_STORAGE_EXTERNAL:
1572         case MS_USER_STORAGE_EXTERNAL_USB:
1573                 return true;
1574         default:
1575                 media_svc_error("storage type is incorrect[%d]", storage_type);
1576                 return false;
1577         }
1578 }
1579
1580 bool _media_svc_is_keyword_included(const char *path, const char *keyword)
1581 {
1582         bool ret = false;
1583         void *handle = NULL;
1584         bool (*svc_search) (const char *, const char *);
1585
1586         media_svc_retvm_if(!path, false, "Invalid path");
1587         media_svc_retvm_if(!keyword, false, "Invalid keyword");
1588
1589         handle = dlopen(PATH_PLUGIN_LIB, RTLD_LAZY);
1590         media_svc_retvm_if(!handle, false, "dlopen failed");
1591
1592         if (g_str_has_suffix(path, "epub") || g_str_has_suffix(path, "EPUB"))
1593                 svc_search = dlsym(handle, "media_svc_epub_is_keyword_included");
1594         else
1595                 svc_search = dlsym(handle, "media_svc_pdf_is_keyword_included");
1596
1597         if (!svc_search) {
1598                 media_svc_error("dlsym failed - %s", dlerror());
1599                 dlclose(handle);
1600                 return false;
1601         }
1602
1603         ret = svc_search(path, keyword);
1604         dlclose(handle);
1605
1606         return ret;
1607 }
1608
1609 static int __media_svc_create_wordbook_db(const char *path, sqlite3 **handle)
1610 {
1611         int ret = SQLITE_OK;
1612         sqlite3 *db_handle = NULL;
1613         char *err = NULL;
1614
1615         ret = sqlite3_open_v2(path, &db_handle, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL);
1616         media_svc_retvm_if(ret != SQLITE_OK, ret, "sqlite3_open_v2 failed : %d", ret);
1617
1618         ret = sqlite3_exec(db_handle, "PRAGMA journal_mode = OFF;", NULL, NULL, &err);
1619         if (ret != SQLITE_OK)
1620                 goto ERROR;
1621
1622         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);
1623         if (ret != SQLITE_OK)
1624                 goto ERROR;
1625
1626         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);
1627         if (ret != SQLITE_OK)
1628                 goto ERROR;
1629
1630         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);
1631         if (ret != SQLITE_OK)
1632                 goto ERROR;
1633
1634         *handle = db_handle;
1635
1636         return SQLITE_OK;
1637
1638 ERROR:
1639         media_svc_error("sqlite3_exec failed : %s", err);
1640         SQLITE3_SAFE_FREE(err);
1641         sqlite3_close_v2(db_handle);
1642
1643         return ret;
1644 }
1645
1646 static bool __media_svc_get_wordbook_handle(uid_t uid, sqlite3 **handle)
1647 {
1648         int ret = SQLITE_OK;
1649         char *db_path = NULL;
1650
1651         ms_user_get_wordbook_db_path(uid, &db_path);
1652         if (!db_path)
1653                 return false;
1654
1655         ret = sqlite3_open_v2(db_path, handle, SQLITE_OPEN_READWRITE, NULL);
1656         if (ret != SQLITE_OK) {
1657                 ret = __media_svc_create_wordbook_db(db_path, handle);
1658                 free(db_path);
1659                 media_svc_retvm_if(ret != SQLITE_OK, false, "__media_svc_create_wordbook_db failed : %d", ret);
1660         } else {
1661                 ret = sqlite3_exec(*handle, "PRAGMA journal_mode = OFF;", NULL, NULL, NULL);
1662                 if (ret != SQLITE_OK)
1663                         media_svc_error("Failed to change journal mode [%d]", ret);
1664         }
1665
1666         return true;
1667 }
1668
1669 static bool __media_svc_is_exist_in_wordbook(sqlite3 *db_handle, const char *path)
1670 {
1671         int ret = SQLITE_OK;
1672         char *err = NULL;
1673         char *query = NULL;
1674
1675         query = sqlite3_mprintf("UPDATE files SET validity=1 WHERE path = %Q", path);
1676
1677         ret = sqlite3_exec(db_handle, query, NULL, NULL, &err);
1678         SQLITE3_SAFE_FREE(query);
1679         if (ret != SQLITE_OK) {
1680                 media_svc_error("Query failed. [%s]", err);
1681                 SQLITE3_SAFE_FREE(err);
1682                 return false;
1683         }
1684
1685         return sqlite3_changes(db_handle) > 0 ? true : false;
1686 }
1687
1688 static void __media_svc_insert_to_wordbook(sqlite3 *db_handle, const char *path)
1689 {
1690         void *handle = NULL;
1691         void (*svc_update) (sqlite3 *, const char *);
1692         char *query = NULL;
1693
1694         query = sqlite3_mprintf("INSERT INTO files(path) VALUES(%Q);", path);
1695         sqlite3_exec(db_handle, query, NULL, NULL, NULL);
1696         sqlite3_free(query);
1697
1698         handle = dlopen(PATH_PLUGIN_LIB, RTLD_LAZY);
1699         if (!handle) {
1700                 media_svc_error("dlopen failed");
1701                 return;
1702         }
1703
1704         if (g_str_has_suffix(path, "epub") || g_str_has_suffix(path, "EPUB"))
1705                 svc_update = dlsym(handle, "media_svc_epub_insert_to_db");
1706         else
1707                 svc_update = dlsym(handle, "media_svc_pdf_insert_to_db");
1708
1709         if (!svc_update) {
1710                 media_svc_error("dlsym failed - %s", dlerror());
1711                 dlclose(handle);
1712                 return;
1713         }
1714
1715         svc_update(db_handle, path);
1716         dlclose(handle);
1717 }
1718
1719 void _media_svc_update_wordbook(const char *path, uid_t uid)
1720 {
1721         sqlite3 *db_handle = NULL;
1722
1723         if (!path) {
1724                 media_svc_error("Invalid path");
1725                 return;
1726         }
1727
1728         // check db..
1729         if (!__media_svc_get_wordbook_handle(uid, &db_handle))
1730                 return;
1731
1732         if (__media_svc_is_exist_in_wordbook(db_handle, path)) {
1733                 sqlite3_close_v2(db_handle);
1734                 return;
1735         }
1736
1737         // if no item, insert to db..
1738         __media_svc_insert_to_wordbook(db_handle, path);
1739         sqlite3_close_v2(db_handle);
1740 }
1741
1742 void _media_svc_clean_wordbook(uid_t uid)
1743 {
1744         sqlite3 *db_handle = NULL;
1745
1746         if (!__media_svc_get_wordbook_handle(uid, &db_handle))
1747                 return;
1748
1749         sqlite3_exec(db_handle, "DELETE FROM files where validity = 0;", NULL, NULL, NULL);
1750         sqlite3_exec(db_handle, "UPDATE files SET validity = 0;", NULL, NULL, NULL);
1751         sqlite3_close_v2(db_handle);
1752 }
1753
1754 bool _media_svc_get_matched_list(const char *keyword, uid_t uid, GList **list)
1755 {
1756         int ret = SQLITE_OK;
1757         sqlite3 *handle = NULL;
1758         sqlite3_stmt *stmt = NULL;
1759         char *query = NULL;
1760
1761         media_svc_retvm_if(!list, false, "list is NULL");
1762         media_svc_retvm_if(!keyword, false, "keyword is NULL");
1763         media_svc_retvm_if(!__media_svc_get_wordbook_handle(uid, &handle), false, "Failed to get handle");
1764
1765         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);
1766         ret = sqlite3_prepare_v2(handle, query, -1, &stmt, NULL);
1767         SQLITE3_SAFE_FREE(query);
1768
1769         if (ret != SQLITE_OK) {
1770                 media_svc_error("Query failed[%d]", ret);
1771                 sqlite3_close_v2(handle);
1772                 return false;
1773         }
1774
1775         while (sqlite3_step(stmt) == SQLITE_ROW)
1776                 *list = g_list_append(*list, g_strdup((char *)sqlite3_column_text(stmt, 0)));
1777
1778         sqlite3_finalize(stmt);
1779         sqlite3_close_v2(handle);
1780
1781         return true;
1782 }