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