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