ceca1ba4405acadb3edf830a1f5a6457e0595ab0
[framework/web/wrt-installer.git] / src / pkg-manager / backendlib.cpp
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16 /**
17  *
18  *
19  * @file       backendlib.cpp
20  * @author     Soyoung Kim (sy037.kim@samsung.com)
21  * @version    0.1
22  * @brief      This is implementation file for providing widget information
23  *             to package manager
24  */
25 #include "package-manager-plugin.h"
26 #include <package-manager.h>
27 #include <regex.h>
28 #include <dlog.h>
29 #include <dpl/wrt-dao-ro/global_config.h>
30 #include <vcore/VCore.h>
31 #include <vconf.h>
32 #include <dpl/wrt-dao-ro/WrtDatabase.h>
33 #include <dpl/wrt-dao-ro/widget_dao_read_only.h>
34 #include <dpl/wrt-dao-ro/feature_dao_read_only.h>
35 #include <dpl/wrt-dao-ro/widget_config.h>
36 #include <string>
37 #include <dpl/db/sql_connection.h>
38 #include <dpl/log/log.h>
39 #include <dpl/foreach.h>
40 #include <dpl/utils/folder_size.h>
41 #include <dpl/wrt-dao-ro/wrt_db_types.h>
42 #include <dpl/copy.h>
43 #include <dpl/abstract_waitable_input_adapter.h>
44 #include <dpl/abstract_waitable_output_adapter.h>
45 #include <dpl/zip_input.h>
46 #include <dpl/binary_queue.h>
47 #include <dpl/file_input.h>
48 #include <dpl/wrt-dao-ro/config_parser_data.h>
49 #include "root_parser.h"
50 #include "widget_parser.h"
51 #include "parser_runner.h"
52
53 using namespace WrtDB;
54
55 #undef TRUE
56 #undef FALSE
57 #define TRUE 0
58 #define FALSE -1
59 #define GET_DIRECTORY_SIZE_KB(x)    (x) / 1024
60
61 #ifdef __cplusplus
62 extern "C"
63 {
64 #endif
65
66 static void pkg_native_plugin_on_unload();
67 static int pkg_plugin_app_is_installed(const char *pkg_name);
68 static int pkg_plugin_get_installed_apps_list(const char *category,
69                                               const char *option,
70                                               package_manager_pkg_info_t **list,
71                                               int *count);
72 static int pkg_plugin_get_app_detail_info(
73     const char *pkg_name,
74     package_manager_pkg_detail_info_t *
75     pkg_detail_info);
76 static int pkg_plugin_get_app_detail_info_from_package(
77     const char *pkg_path,
78     package_manager_pkg_detail_info_t
79     *pkg_detail_info);
80
81 pkgmgr_info *pkgmgr_client_check_pkginfo_from_file(const char *pkg_path);
82
83 static void pkg_native_plugin_on_unload()
84 {
85     LogDebug("pkg_native_plugin_unload() is called");
86 }
87
88 static int pkg_plugin_app_is_installed(const char *pkg_name)
89 {
90     const char* REG_PKGID_PATTERN = "^[a-zA-Z0-9]{10}$";
91     LogDebug("pkg_plugin_app_is_installed() is called");
92
93     WrtDB::WrtDatabase::attachToThreadRO();
94
95     regex_t reg;
96     if (regcomp(&reg, REG_PKGID_PATTERN, REG_NOSUB | REG_EXTENDED) != 0) {
97         LogDebug("Regcomp failed");
98     }
99
100     WrtDB::TizenAppId appid;
101
102     if (!(regexec(&reg, pkg_name,
103                     static_cast<size_t>(0), NULL, 0) == 0))
104     {
105         LogError("Invalid argument : " << pkg_name);
106         return FALSE;
107     }
108
109     Try {
110         WrtDB::TizenPkgId pkgid(DPL::FromUTF8String(pkg_name));
111         appid = WidgetDAOReadOnly::getTzAppId(pkgid);
112         LogDebug("appid : " << appid);
113     } Catch(WidgetDAOReadOnly::Exception::WidgetNotExist) {
114         WrtDB::WrtDatabase::detachFromThread();
115         return FALSE;
116     }
117     WrtDB::WrtDatabase::detachFromThread();
118     return TRUE;
119 }
120
121 static int pkg_plugin_get_installed_apps_list(const char * /*category*/,
122                                               const char * /*option*/,
123                                               package_manager_pkg_info_t **list,
124                                               int *count)
125 {
126     LogDebug("pkg_plugin_get_installed_apps_list() is called");
127
128     package_manager_pkg_info_t *pkg_list = NULL;
129     package_manager_pkg_info_t *pkg_last = NULL;
130
131     WrtDB::WrtDatabase::attachToThreadRO();
132     TizenAppIdList tizenAppidList = WidgetDAOReadOnly::getTizenAppidList();
133     *count = 0;
134
135     FOREACH(iterator, tizenAppidList) {
136         package_manager_pkg_info_t *pkg_info =
137             static_cast<package_manager_pkg_info_t*>
138             (malloc(sizeof(package_manager_pkg_info_t)));
139
140         if (NULL == pkg_list) {
141             pkg_list = pkg_info;
142             pkg_last = pkg_info;
143         } else {
144             pkg_last->next = pkg_info;
145         }
146
147         TizenAppId tzAppid = *iterator;
148         WidgetDAOReadOnly widget(tzAppid);
149         strncpy(pkg_info->pkg_type, "wgt", PKG_TYPE_STRING_LEN_MAX);
150         snprintf(pkg_info->pkg_name, PKG_NAME_STRING_LEN_MAX, "%s",
151                  DPL::ToUTF8String(tzAppid).c_str());
152
153         DPL::Optional<DPL::String> version = widget.getVersion();
154         if (!version.IsNull()) {
155             strncpy(pkg_info->version,
156                     DPL::ToUTF8String(*version).c_str(),
157                     PKG_VERSION_STRING_LEN_MAX - 1);
158         }
159
160         (*count)++;
161         pkg_last = pkg_info;
162     }
163     *list = pkg_list;
164     WrtDB::WrtDatabase::detachFromThread();
165
166     return TRUE;
167 }
168
169 static int pkg_plugin_get_app_detail_info(
170     const char *pkg_name,
171     package_manager_pkg_detail_info_t *
172     pkg_detail_info)
173 {
174     LogDebug("pkg_plugin_get_app_detail_info() is called");
175
176     WrtDB::WrtDatabase::attachToThreadRO();
177
178     WrtDB::TizenAppId appid;
179     Try {
180         WrtDB::TizenPkgId pkgid(DPL::FromUTF8String(pkg_name));
181         appid = WidgetDAOReadOnly::getTzAppId(pkgid);
182         LogDebug("appid : " << appid);
183     } Catch(WidgetDAOReadOnly::Exception::WidgetNotExist) {
184         WrtDB::WrtDatabase::detachFromThread();
185         return FALSE;
186     }
187
188     WidgetDAOReadOnly widget(appid);
189
190     DPL::Optional<DPL::String> version = widget.getVersion();
191     DPL::Optional<DPL::String> id = widget.getGUID();
192     DPL::Optional<DPL::String> locale = widget.getDefaultlocale();
193
194     if (!version.IsNull()) {
195         strncpy(pkg_detail_info->version,
196                 DPL::ToUTF8String(*version).c_str(),
197                 PKG_VERSION_STRING_LEN_MAX - 1);
198     }
199     snprintf(pkg_detail_info->pkgid, PKG_NAME_STRING_LEN_MAX, "%s",
200              pkg_name);
201     snprintf(pkg_detail_info->optional_id, PKG_NAME_STRING_LEN_MAX, "%s",
202              DPL::ToUTF8String(appid).c_str());
203     WidgetLocalizedInfo localizedInfo;
204
205     if (locale.IsNull()) {
206         LogDebug("locale is NULL");
207         DPL::String languageTag(L"");
208         localizedInfo = widget.getLocalizedInfo(languageTag);
209     } else {
210         localizedInfo = widget.getLocalizedInfo(*locale);
211     }
212     DPL::Optional<DPL::String> desc(localizedInfo.description);
213
214     if (!desc.IsNull()) {
215         strncpy(pkg_detail_info->pkg_description,
216                 DPL::ToUTF8String(*desc).c_str(),
217                 PKG_VALUE_STRING_LEN_MAX - 1);
218     }
219     strncpy(pkg_detail_info->pkg_type, "wgt", PKG_TYPE_STRING_LEN_MAX);
220     strncpy(pkg_detail_info->pkg_name, pkg_name, PKG_NAME_STRING_LEN_MAX - 1);
221
222     std::string min_version = DPL::ToUTF8String((*widget.getMinimumWacVersion()));
223
224     strncpy(pkg_detail_info->min_platform_version, min_version.c_str(),
225             PKG_VERSION_STRING_LEN_MAX - 1);
226
227     /* set installed time */
228     pkg_detail_info->installed_time = widget.getInstallTime();
229
230     /* set Widget size */
231     DPL::String pkgName = DPL::FromUTF8String(pkg_name);
232     std::string installPath = WidgetConfig::GetWidgetBasePath(pkgName);
233     std::string persistentPath =
234         WidgetConfig::GetWidgetPersistentStoragePath(pkgName);
235     std::string tempPath =
236         WidgetConfig::GetWidgetTemporaryStoragePath(pkgName);
237     installPath += "/";
238     tempPath += "/";
239     persistentPath += "/";
240
241     size_t installedSize = Utils::getFolderSize(installPath);
242     size_t persistentSize = Utils::getFolderSize(persistentPath);
243     size_t appSize = installedSize - persistentSize;
244     size_t dataSize = persistentSize + Utils::getFolderSize(tempPath);
245
246     pkg_detail_info->installed_size = GET_DIRECTORY_SIZE_KB(installedSize);
247     pkg_detail_info->app_size = GET_DIRECTORY_SIZE_KB(appSize);
248     pkg_detail_info->data_size = GET_DIRECTORY_SIZE_KB(dataSize);
249
250     WrtDB::WrtDatabase::detachFromThread();
251     return TRUE;
252 }
253
254 int getConfigParserData(const std::string &widgetPath, ConfigParserData& configInfo)
255 {
256     const char* CONFIG_XML = "config.xml";
257     const char* WITH_OSP_XML = "res/wgt/config.xml";
258
259     Try {
260         ParserRunner parser;
261
262         std::unique_ptr<DPL::ZipInput> zipFile(
263                 new DPL::ZipInput(widgetPath));
264
265         std::unique_ptr<DPL::ZipInput::File> configFile;
266
267         // Open config.xml file
268         Try {
269             configFile.reset(zipFile->OpenFile(CONFIG_XML));
270         }
271         Catch(DPL::ZipInput::Exception::OpenFileFailed)
272         {
273             configFile.reset(zipFile->OpenFile(WITH_OSP_XML));
274         }
275
276         // Extract config
277         DPL::BinaryQueue buffer;
278         DPL::AbstractWaitableInputAdapter inputAdapter(configFile.get());
279         DPL::AbstractWaitableOutputAdapter outputAdapter(&buffer);
280         DPL::Copy(&inputAdapter, &outputAdapter);
281         parser.Parse(&buffer,
282                 ElementParserPtr(
283                     new RootParser<WidgetParser>(configInfo,
284                         DPL::
285                         FromUTF32String(
286                             L"widget"))));
287     }
288     Catch(DPL::ZipInput::Exception::OpenFailed)
289     {
290         LogError("Failed to open widget package");
291         return FALSE;
292     }
293     Catch(DPL::ZipInput::Exception::OpenFileFailed)
294     {
295         LogError("Failed to open config.xml file");
296         return FALSE;
297     }
298     Catch(DPL::CopyFailed)
299     {
300         LogError("Failed to extract config.xml file");
301         return FALSE;
302     }
303     Catch(DPL::FileInput::Exception::OpenFailed)
304     {
305         LogError("Failed to open config.xml file");
306         return FALSE;
307     }
308     Catch(ElementParser::Exception::ParseError)
309     {
310         LogError("Failed to parse config.xml file");
311         return FALSE;
312     }
313     Catch(DPL::ZipInput::Exception::SeekFileFailed)
314     {
315         LogError("Failed to seek widget archive - corrupted package?");
316         return FALSE;
317     }
318
319     return TRUE;
320 }
321
322 char* getIconInfo(const std::string widgetPath,
323         const std::string icon_name, int &icon_size)
324 {
325     Try {
326         std::unique_ptr<DPL::ZipInput> zipFile(
327                 new DPL::ZipInput(widgetPath));
328
329         std::unique_ptr<DPL::ZipInput::File> iconFile;
330
331         Try {
332             iconFile.reset(zipFile->OpenFile(icon_name));
333         }
334         Catch(DPL::ZipInput::Exception::OpenFileFailed)
335         {
336             LogDebug("This web app is hybrid web app");
337             std::string hybrid_icon = "res/wgt/" + icon_name;
338             iconFile.reset(zipFile->OpenFile(hybrid_icon));
339         }
340
341         DPL::BinaryQueue buffer;
342         DPL::AbstractWaitableInputAdapter inputAdapter(iconFile.get());
343         DPL::AbstractWaitableOutputAdapter outputAdapter(&buffer);
344         DPL::Copy(&inputAdapter, &outputAdapter);
345         icon_size = buffer.Size();
346         char *getBuffer = (char*) calloc(1, (sizeof(char) * icon_size) + 1);
347         buffer.Flatten(getBuffer, buffer.Size());
348         return getBuffer;
349     }
350     Catch(DPL::ZipInput::Exception::OpenFailed)
351     {
352         LogError("Failed to open widget package");
353         return NULL;
354     }
355     Catch(DPL::ZipInput::Exception::OpenFileFailed)
356     {
357         LogError("Failed to open icon file");
358         return NULL;
359     }
360 }
361
362 int getWidgetDetailInfoFromPackage(const char* pkgPath,
363         package_manager_pkg_detail_info_t* pkg_detail_info)
364 {
365     const std::string widget_path(pkgPath);
366     ConfigParserData configInfo;
367
368     if (FALSE == getConfigParserData(widget_path, configInfo)) {
369         return FALSE;
370     }
371
372     strncpy(pkg_detail_info->pkg_type, "wgt", PKG_TYPE_STRING_LEN_MAX);
373     if (!configInfo.tizenPkgId.IsNull()) {
374         strncpy(pkg_detail_info->pkgid,
375                 DPL::ToUTF8String(*configInfo.tizenPkgId).c_str(), PKG_TYPE_STRING_LEN_MAX - 1);
376     }
377     if (!configInfo.tizenAppId.IsNull()) {
378         strncpy(pkg_detail_info->pkg_name,
379                 DPL::ToUTF8String(*configInfo.tizenAppId).c_str(),
380                 PKG_NAME_STRING_LEN_MAX - 1);
381     }
382     if (!configInfo.version.IsNull()) {
383         strncpy(pkg_detail_info->version,
384                 DPL::ToUTF8String(*configInfo.version).c_str(),
385                 PKG_VERSION_STRING_LEN_MAX - 1);
386     }
387
388     DPL::Optional<DPL::String> name;
389     DPL::Optional<DPL::String> desc;
390
391     DPL::OptionalString defaultLocale = configInfo.defaultlocale;
392
393     char* language = vconf_get_str(VCONFKEY_LANGSET);
394
395     DPL::String inLocaleString = DPL::FromUTF8String(language);
396     DPL::String locString = inLocaleString.substr(
397             0, inLocaleString.find_first_of(L"."));
398     std::replace(locString.begin(), locString.end(), '_', '-');
399
400     FOREACH(localizedData, configInfo.localizedDataSet)
401     {
402         Locale i = localizedData->first;
403         std::transform( locString.begin(),
404                 locString.end(),
405                 locString.begin(),
406                 ::tolower );
407         std::transform( i.begin(), i.end(), i.begin(), ::tolower );
408         std::size_t found = locString.find(i);
409         std::size_t found2 = i.find(locString);
410
411         if (!!defaultLocale) {
412             if (defaultLocale == i) {
413                 name = localizedData->second.name;
414                 desc = localizedData->second.description;
415                 break;
416             }
417         } else if (found != std::string::npos
418                 || found2 != std::string::npos) {
419             name = localizedData->second.name;
420             desc = localizedData->second.description;
421             break;
422         }
423         else {
424             name = localizedData->second.name;
425             desc = localizedData->second.description;
426             continue;
427         }
428     }
429
430     if( !name.IsNull()) {
431         strncpy(pkg_detail_info->label, DPL::ToUTF8String(*name).c_str(),
432                 PKG_LABEL_STRING_LEN_MAX - 1);
433     }
434
435     if (!desc.IsNull()) {
436         strncpy(pkg_detail_info->pkg_description,
437                 DPL::ToUTF8String(*desc).c_str(),
438                 PKG_VALUE_STRING_LEN_MAX - 1);
439     }
440
441     if (!configInfo.tizenMinVersionRequired.IsNull()) {
442         strncpy(pkg_detail_info->min_platform_version,
443                 DPL::ToUTF8String(*configInfo.tizenMinVersionRequired).c_str(),
444                 PKG_VERSION_STRING_LEN_MAX - 1);
445     }
446
447     if (!configInfo.authorName.IsNull()) {
448         strncpy(pkg_detail_info->author,
449                 DPL::ToUTF8String(*configInfo.authorName).c_str(),
450                 PKG_VALUE_STRING_LEN_MAX - 1);
451     }
452
453
454     pkg_detail_info->privilege_list = NULL;
455     FOREACH(it, configInfo.featuresList) {
456         std::string featureInfo =  DPL::ToUTF8String(it->name);
457         LogDebug("privilege : " << featureInfo);
458         int length = featureInfo.size();
459         char *privilege = (char*) calloc(1, (sizeof(char) * (length + 1)));
460         snprintf(privilege, length + 1, "%s", featureInfo.c_str());
461         pkg_detail_info->privilege_list =
462             g_list_append(pkg_detail_info->privilege_list, privilege);
463     }
464
465     std::string icon_name;
466     FOREACH(i, configInfo.iconsList) {
467         LogDebug("icon name: " << i->src);
468         icon_name = DPL::ToUTF8String(i->src);
469         break;
470     }
471
472     pkg_detail_info->icon_buf = getIconInfo(widget_path, icon_name,
473             pkg_detail_info->icon_size);
474     LogDebug("icon size : " << pkg_detail_info->icon_size);
475
476     return TRUE;
477 }
478
479 static int pkg_plugin_get_app_detail_info_from_package(
480     const char * pkg_path,
481     package_manager_pkg_detail_info_t * pkg_detail_info)
482 {
483     LogDebug("pkg_plugin_get_app_detail_info_from_package() is called");
484     return getWidgetDetailInfoFromPackage(pkg_path, pkg_detail_info);
485 }
486
487 pkgmgr_info *pkgmgr_client_check_pkginfo_from_file(const char *pkg_path)
488 {
489     LogDebug("pkgmgr_client_check_pkginfo_from_file() is called");
490     package_manager_pkg_detail_info_t *pkg_detail_info;
491     pkg_detail_info = (package_manager_pkg_detail_info_t*)malloc(
492             sizeof(package_manager_pkg_detail_info_t));
493     int ret = getWidgetDetailInfoFromPackage(pkg_path, pkg_detail_info);
494     if (FALSE == ret) {
495         LogError("Failed to get package detail info ");
496         return NULL;
497     }
498     return reinterpret_cast<pkgmgr_info*>(pkg_detail_info);
499 }
500
501 __attribute__ ((visibility("default")))
502 int pkg_plugin_on_load(pkg_plugin_set *set)
503 {
504     DPL::Log::LogSystemSingleton::Instance().SetTag("WGT-BACKLIB");
505     if (NULL == set) {
506         return FALSE;
507     }
508     memset(set, 0x00, sizeof(pkg_plugin_set));
509
510     set->plugin_on_unload = pkg_native_plugin_on_unload;
511     set->pkg_is_installed = pkg_plugin_app_is_installed;
512     set->get_installed_pkg_list = pkg_plugin_get_installed_apps_list;
513     set->get_pkg_detail_info = pkg_plugin_get_app_detail_info;
514     set->get_pkg_detail_info_from_package =
515         pkg_plugin_get_app_detail_info_from_package;
516
517     return TRUE;
518 }
519
520 #ifdef __cplusplus
521 }
522 #endif