Update wrt-installer_0.0.52
[framework/web/wrt-installer.git] / src / jobs / widget_install / task_widget_config.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  * @file    task_widget_config.cpp
18  * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
19  * @version 1.0
20  * @brief   Implementation file for installer task widget config
21  */
22 #include <string>
23 #include <sstream>
24 #include <dpl/foreach.h>
25 #include <dpl/errno_string.h>
26 #include <dpl/wrt-dao-rw/feature_dao.h>
27 #include <dpl/wrt-dao-ro/global_config.h>
28 #include <dpl/utils/wrt_utility.h>
29 #include <root_parser.h>
30 #include <widget_parser.h>
31 #include <parser_runner.h>
32 #include <libiriwrapper.h>
33 #include <widget_install/task_widget_config.h>
34 #include <widget_install/job_widget_install.h>
35 #include <widget_install/widget_install_errors.h>
36 #include <widget_install/widget_install_context.h>
37 #include <dpl/utils/file_utils.h>
38 #include <dpl/utils/mime_type_utils.h>
39 #include <sys/stat.h>
40 #include <dpl/utils/wrt_global_settings.h>
41
42 namespace { // anonymous
43 const WidgetHandle WIDGET_HANDLE_START_VALUE = 1000;
44 const DPL::String BR = DPL::FromUTF8String("<br>");
45 const std::string WIDGET_NOT_COMPATIBLE = "This widget is "
46         "not compatible with WRT.<br><br>";
47 const std::string QUESTION = "Do you want to install it anyway?";
48 } // namespace anonymous
49
50 namespace Jobs {
51 namespace WidgetInstall {
52 void InstallerTaskWidgetPopupData::PopupData::addWidgetInfo(
53         const DPL::String &info)
54 {
55     widgetInfo = info;
56 }
57
58 TaskWidgetConfig::TaskWidgetConfig(InstallerContext& installContext) :
59     DPL::TaskDecl<TaskWidgetConfig>(this),
60     m_installContext(installContext),
61     WidgetInstallPopup(installContext)
62 {
63     AddStep(&TaskWidgetConfig::StepProcessConfigurationFile);
64     AddStep(&TaskWidgetConfig::ReadLocaleFolders);
65     AddStep(&TaskWidgetConfig::ProcessLocalizedStartFiles);
66     AddStep(&TaskWidgetConfig::ProcessLocalizedIcons);
67     AddStep(&TaskWidgetConfig::StepVerifyFeatures);
68
69     if (!GlobalSettings::TestModeEnabled() && !m_installContext.m_quiet) {
70         AddStep(&TaskWidgetConfig::StepCancelWidgetInstallationAfterVerifyFeatures);
71         AddStep(&TaskWidgetConfig::StepShowWidgetInfo);
72         AddStep(&TaskWidgetConfig::StepCancelWidgetInstallation);
73         AddStep(&TaskWidgetConfig::StepCheckMinVersionInfo);
74         AddStep(&TaskWidgetConfig::StepCancelWidgetInstallationAfterMinVersion);
75         AddStep(&TaskWidgetConfig::StepDeletePopupWin);
76     }
77 }
78
79 void TaskWidgetConfig::StepProcessConfigurationFile()
80 {
81     Try
82     {
83         std::string path;
84         LogInfo("path: " << m_installContext.tempWidgetRoot);
85         if (m_installContext.browserRequest) {
86             path = m_installContext.widgetSource;
87         } else {
88             path = m_installContext.tempWidgetRoot;
89         }
90
91         WidgetConfigurationManagerSingleton::Instance().processFile(
92             path,
93             m_installContext.widgetConfig);
94     }
95     Catch(WidgetConfigurationManager::Exception::ProcessFailed)
96     {
97         LogError("Parsing failed.");
98         ReThrow(Exceptions::WidgetConfigFileInvalid);
99     }
100     Try
101     {
102         // To get widget type for distribute WAC, TIZEN WebApp
103         setApplicationType();
104     }
105     Catch(WidgetConfigurationManager::Exception::ProcessFailed)
106     {
107         LogError("Config.xml has more than one namespace");
108         ReThrow(Exceptions::WidgetConfigFileInvalid);
109     }
110
111     m_installContext.job->UpdateProgress(
112         InstallerContext::INSTALL_WIDGET_CONFIG1,
113         "Parse elements of configuration file and save them");
114 }
115
116 void TaskWidgetConfig::ReadLocaleFolders()
117 {
118     LogDebug("Reading locale");
119     //Adding default locale
120     m_localeFolders.insert(L"");
121
122     std::string localePath = m_installContext.tempWidgetRoot + "/locales";
123     DIR* localeDir = opendir(localePath.c_str());
124     if (!localeDir) {
125         LogDebug("No /locales directory in the widget package.");
126         return;
127     }
128
129     struct dirent* dirent;
130     struct stat statStruct;
131     do {
132         errno = 0;
133         if ((dirent = readdir(localeDir))) {
134             DPL::String dirName = DPL::FromUTF8String(dirent->d_name);
135             std::string absoluteDirName = localePath + "/";
136             absoluteDirName += dirent->d_name;
137
138             if (stat(absoluteDirName.c_str(), &statStruct) != 0) {
139                 LogError("stat() failed with " << DPL::GetErrnoString());
140                 continue;
141             }
142
143             if (S_ISDIR(statStruct.st_mode)) {
144                 //Yes, we ignore current, parent & hidden directories
145                 if (dirName[0] != L'.') {
146                     LogDebug("Adding locale directory \"" << dirName << "\"");
147                     m_localeFolders.insert(dirName);
148                 }
149             }
150         }
151     }
152     while (dirent);
153
154     if (errno != 0) {
155         LogError("readdir() failed with " << DPL::GetErrnoString());
156     }
157
158     if (closedir(localeDir)) {
159         LogError("closedir() failed with " << DPL::GetErrnoString());
160     }
161 }
162
163 void TaskWidgetConfig::ProcessLocalizedStartFiles()
164 {
165     typedef DPL::String S;
166     ProcessStartFile(
167         m_installContext.widgetConfig.configInfo.startFile,
168         m_installContext.widgetConfig.configInfo.
169             startFileContentType,
170         m_installContext.widgetConfig.configInfo.startFileEncoding,
171         true);
172     ProcessStartFile(S(L"index.htm"), S(L"text/html"));
173     ProcessStartFile(S(L"index.html"), S(L"text/html"));
174     ProcessStartFile(S(L"index.svg"), S(L"image/svg+xml"));
175     ProcessStartFile(S(L"index.xhtml"), S(L"application/xhtml+xml"));
176     ProcessStartFile(S(L"index.xht"), S(L"application/xhtml+xml"));
177     // TODO: (l.wrzosek) we need better check if in current locales widget is valid.
178     FOREACH(it, m_installContext.widgetConfig.localizationData.startFiles) {
179         if (it->propertiesForLocales.size() > 0) {
180             return;
181         }
182     }
183     ThrowMsg(Exceptions::WidgetConfigFileInvalid,
184              L"The Widget has no valid start file");
185 }
186
187 void TaskWidgetConfig::ProcessStartFile(const DPL::OptionalString& path,
188         const DPL::OptionalString& type,
189         const DPL::OptionalString& encoding,
190         bool typeForcedInConfig)
191 {
192     using namespace WrtDB;
193
194     if (!!path) {
195         WidgetRegisterInfo::LocalizedStartFile startFileData;
196         startFileData.path = *path;
197
198         FOREACH(i, m_localeFolders) {
199             DPL::String pathPrefix = *i;
200             if (!pathPrefix.empty()) {
201                 pathPrefix = L"locales/" + pathPrefix + L"/";
202             }
203
204             DPL::String relativePath = pathPrefix + *path;
205             DPL::String absolutePath = DPL::FromUTF8String(
206                     m_installContext.tempWidgetRoot) + L"/" + relativePath;
207
208             // get property data from packaged app
209             if (FileUtils::FileExists(absolutePath)) {
210                 WidgetRegisterInfo::StartFileProperties startFileProperties;
211                 if (!!type) {
212                     startFileProperties.type = *type;
213                 } else {
214                     startFileProperties.type =
215                         MimeTypeUtils::identifyFileMimeType(absolutePath);
216                 }
217
218                 //proceed only if MIME type is supported
219                 if (MimeTypeUtils::isMimeTypeSupportedForStartFile(
220                         startFileProperties.type))
221                 {
222                     if (!!encoding) {
223                         startFileProperties.encoding = *encoding;
224                     } else {
225                         MimeTypeUtils::MimeAttributes attributes =
226                             MimeTypeUtils::getMimeAttributes(
227                             startFileProperties.type);
228                         if (attributes.count(L"charset") > 0) {
229                             startFileProperties.encoding =
230                                 attributes[L"charset"];
231                         } else {
232                             startFileProperties.encoding = L"UTF-8";
233                         }
234                     }
235
236                     startFileData.propertiesForLocales[*i] =
237                         startFileProperties;
238                 } else {
239                     //9.1.16.5.content.8
240                     //(there seems to be no similar requirement in .6,
241                     //so let's throw only when mime type is
242                     // provided explcitly in config.xml)
243                     if (typeForcedInConfig) {
244                         ThrowMsg(Exceptions::WidgetConfigFileInvalid,
245                                  "Unsupported MIME type for start file.");
246                     }
247                 }
248             } else {
249                 // set property data for hosted start url
250                 // Hosted start url only support TIZEN WebApp
251                 if (m_installContext.widgetConfig.type ==
252                         APP_TYPE_TIZENWEBAPP)
253                 {
254                     const char *startPath =
255                         DPL::ToUTF8String(startFileData.path).c_str();
256                     if (strstr(startPath, "http") == startPath) {
257                         WidgetRegisterInfo::StartFileProperties
258                             startFileProperties;
259                         if (!!type) {
260                             startFileProperties.type = *type;
261                         }
262                         if (!!encoding) {
263                             startFileProperties.encoding = *encoding;
264                         }
265                         startFileData.propertiesForLocales[*i] =
266                             startFileProperties;
267                     }
268                 }
269             }
270         }
271
272         m_installContext.widgetConfig.localizationData.startFiles.push_back(
273             startFileData);
274     }
275 }
276
277 void TaskWidgetConfig::ProcessLocalizedIcons()
278 {
279     using namespace WrtDB;
280     ProcessIcon(ConfigParserData::Icon(L"icon.svg"));
281     ProcessIcon(ConfigParserData::Icon(L"icon.ico"));
282     ProcessIcon(ConfigParserData::Icon(L"icon.png"));
283     ProcessIcon(ConfigParserData::Icon(L"icon.gif"));
284     ProcessIcon(ConfigParserData::Icon(L"icon.jpg"));
285
286     FOREACH(i, m_installContext.widgetConfig.configInfo.iconsList)
287     {
288         ProcessIcon(*i);
289     }
290 }
291
292 void TaskWidgetConfig::ProcessIcon(const WrtDB::ConfigParserData::Icon& icon)
293 {
294     LogInfo("enter");
295     bool isAnyIconValid = false;
296     //In case a default filename is passed as custom filename in config.xml, we
297     //need to keep a set of already processed filenames to avoid icon duplication
298     //in database.
299
300     using namespace WrtDB;
301
302     if (m_processedIconSet.count(icon.src) > 0) {
303         return;
304     }
305     m_processedIconSet.insert(icon.src);
306
307     LocaleSet localesAvailableForIcon;
308
309     FOREACH(i, m_localeFolders)
310     {
311         DPL::String pathPrefix = *i;
312         if (!pathPrefix.empty()) {
313             pathPrefix = L"locales/" + pathPrefix + L"/";
314         }
315
316         DPL::String relativePath = pathPrefix + icon.src;
317         DPL::String absolutePath;
318
319         if (m_installContext.browserRequest) {
320             // in case of browser installation
321             size_t pos = m_installContext.widgetSource.rfind("/");
322             absolutePath = DPL::FromUTF8String(
323                             m_installContext.widgetSource.substr(0, pos));
324         } else {
325             absolutePath = DPL::FromUTF8String(
326                             m_installContext.tempWidgetRoot);
327         }
328         absolutePath += L"/" + relativePath;
329
330         if (FileUtils::FileExists(absolutePath)) {
331             DPL::String type = MimeTypeUtils::identifyFileMimeType(absolutePath);
332
333             if (MimeTypeUtils::isMimeTypeSupportedForIcon(type)) {
334                 isAnyIconValid = true;
335                 localesAvailableForIcon.insert(*i);
336                 LogInfo("Icon absolutePath :" << absolutePath <<
337                         ", assigned locale :" << *i << ", type: " << type);
338             }
339         }
340     }
341
342     if(isAnyIconValid)
343     {
344         WidgetRegisterInfo::LocalizedIcon localizedIcon(icon,
345                                                         localesAvailableForIcon);
346         m_installContext.widgetConfig.localizationData.icons.push_back(
347             localizedIcon);
348     }
349 }
350
351 void TaskWidgetConfig::StepCancelWidgetInstallationAfterVerifyFeatures()
352 {
353     LogDebug("StepCancelWidgetInstallationAfterVerifyFeatures");
354     if (InfoPopupButton::WRT_POPUP_BUTTON_CANCEL == m_installCancel) {
355         m_installCancel = WRT_POPUP_BUTTON;
356         destroyPopup();
357         ThrowMsg(Exceptions::WidgetConfigFileInvalid, "Widget not allowed");
358     }
359 }
360
361 void TaskWidgetConfig::StepCancelWidgetInstallation()
362 {
363     if (InfoPopupButton::WRT_POPUP_BUTTON_CANCEL == m_installCancel) {
364         m_installCancel = WRT_POPUP_BUTTON;
365         destroyPopup();
366         ThrowMsg(Exceptions::NotAllowed, "Widget not allowed");
367     }
368 }
369
370 void TaskWidgetConfig::StepCancelWidgetInstallationAfterMinVersion()
371 {
372     if (InfoPopupButton::WRT_POPUP_BUTTON_CANCEL == m_installCancel) {
373         m_installCancel = WRT_POPUP_BUTTON;
374         destroyPopup();
375         ThrowMsg(Exceptions::NotAllowed, "WRT version incompatible.");
376     }
377 }
378
379 void TaskWidgetConfig::createInstallPopup(PopupType type, const std::string &label)
380 {
381     m_installContext.job->Pause();
382     if (m_popup)
383         destroyPopup();
384
385     bool ret = createPopup();
386     if (ret)
387     {
388         loadPopup( type, label);
389         showPopup();
390     }
391 }
392
393 void TaskWidgetConfig::StepDeletePopupWin()
394 {
395     destroyPopup();
396 }
397
398 void TaskWidgetConfig::StepShowWidgetInfo()
399 {
400     if (!m_popupData.widgetInfo.empty()) {
401             std::string label = DPL::ToUTF8String(m_popupData.widgetInfo);
402             createInstallPopup(PopupType::WIDGET_FEATURE_INFO, label);
403         m_installContext.job->UpdateProgress(
404             InstallerContext::INSTALL_WIDGET_CONFIG2,
405             "Show Widget Info Finished");
406     }
407 }
408
409 void TaskWidgetConfig::StepCheckMinVersionInfo()
410 {
411     if (!isMinVersionCompatible(
412                 m_installContext.widgetConfig.type.appType,
413                 m_installContext.widgetConfig.minVersion)) {
414         std::string label = WIDGET_NOT_COMPATIBLE + QUESTION;
415         createInstallPopup(PopupType::WIDGET_MIN_VERSION, label);
416     }
417
418     m_installContext.job->UpdateProgress(
419             InstallerContext::INSTALL_WIDGET_CONFIG2,
420             "Check MinVersion Finished");
421 }
422
423 void TaskWidgetConfig::StepVerifyFeatures()
424 {
425     using namespace WrtDB;
426     ConfigParserData &data = m_installContext.widgetConfig.configInfo;
427     ConfigParserData::FeaturesList list = data.featuresList;
428     ConfigParserData::FeaturesList newList;
429
430     //in case of tests, this variable is unused
431     std::string featureInfo;
432     FOREACH(it, list)
433     {
434         // check feature vender for permission
435         // WAC, TIZEN WebApp cannot use other feature
436
437         if (!isFeatureAllowed(m_installContext.widgetConfig.type.appType,
438                               it->name))
439         {
440             LogInfo("This application type not allowed to use this feature");
441             ThrowMsg(
442                 Exceptions::WidgetConfigFileInvalid,
443                 "This app type [" <<
444                 m_installContext.widgetConfig.type.getApptypeToString() <<
445                 "] cannot be allowed to use [" <<
446                 DPL::ToUTF8String(it->name) + "] feature");
447         }
448         if (!WrtDB::FeatureDAOReadOnly::isFeatureInstalled(
449                 DPL::ToUTF8String(it->name))) {
450             LogWarning("Feature not found. Checking if required :[" <<
451                        DPL::ToUTF8String(it->name) << "]");
452
453             if (it->required) {
454                 /**
455                  * WL-3210 The WRT MUST inform the user if a widget cannot be
456                  * installed because one or more required features are not
457                  * supported.
458                  */
459                 std::ostringstream os;
460                 os << "Widget cannot be installed, required feature is missing:["
461                     << DPL::ToUTF8String(it->name) << "]";
462                 if (!GlobalSettings::TestModeEnabled() && !isTizenWebApp()) {
463                     std::string label = os.str();
464                     createInstallPopup(PopupType::WIDGET_WRONG_FEATURE_INFO, label);
465                 }
466                 ThrowMsg(Exceptions::WidgetConfigFileInvalid, os.str());
467             }
468         } else {
469             newList.insert(*it);
470             featureInfo += DPL::ToUTF8String(it->name);
471             featureInfo += DPL::ToUTF8String(BR);
472         }
473     }
474     data.featuresList = newList;
475     if (!featureInfo.empty()) {
476         m_popupData.addWidgetInfo(DPL::FromUTF8String(featureInfo));
477     }
478
479     m_installContext.job->UpdateProgress(
480         InstallerContext::INSTALL_WIDGET_CONFIG2,
481         "Widget Config step2 Finished");
482 }
483
484 void TaskWidgetConfig::setApplicationType()
485 {
486     using namespace WrtDB;
487     WidgetRegisterInfo* widgetInfo = &(m_installContext.widgetConfig);
488     ConfigParserData* configInfo = &(widgetInfo->configInfo);
489
490     FOREACH(iterator, configInfo->nameSpaces) {
491         LogInfo("namespace = [" << *iterator << "]");
492         AppType currentAppType = APP_TYPE_UNKNOWN;
493
494         if (*iterator == ConfigurationNamespace::W3CWidgetNamespaceName) {
495             continue;
496         } else if (
497             *iterator ==
498             ConfigurationNamespace::WacWidgetNamespaceNameForLinkElement ||
499             *iterator ==
500             ConfigurationNamespace::WacWidgetNamespaceName)
501         {
502             currentAppType = APP_TYPE_WAC20;
503         } else if (*iterator == ConfigurationNamespace::TizenWebAppNamespaceName) {
504             currentAppType = APP_TYPE_TIZENWEBAPP;
505         }
506
507         if (widgetInfo->type == APP_TYPE_UNKNOWN) {
508             widgetInfo->type = currentAppType;
509         } else if (widgetInfo->type == currentAppType) {
510             continue;
511         } else {
512             ThrowMsg(Exceptions::WidgetConfigFileInvalid,
513                      "Config.xml has more than one namespace");
514         }
515     }
516
517     // If there is no define, type set to WAC 2.0
518     if (widgetInfo->type == APP_TYPE_UNKNOWN) {
519         widgetInfo->type = APP_TYPE_WAC20;
520     }
521
522     LogInfo("type = [" << widgetInfo->type.getApptypeToString() << "]");
523 }
524
525 bool TaskWidgetConfig::isFeatureAllowed(WrtDB::AppType appType,
526                                         DPL::String featureName)
527 {
528     using namespace WrtDB;
529     LogInfo("AppType = [" <<
530             WidgetType(appType).getApptypeToString() << "]");
531     LogInfo("FetureName = [" << featureName << "]");
532
533     AppType featureType = APP_TYPE_UNKNOWN;
534     const char* feature = DPL::ToUTF8String(featureName).c_str();
535     // check prefix of  feature name
536     if (strstr(feature, PluginsPrefix::TIZENPluginsPrefix) == feature) {
537         // Tizen WebApp feature
538         featureType = APP_TYPE_TIZENWEBAPP;
539     } else if (strstr(feature, PluginsPrefix::WACPluginsPrefix) == feature) {
540         // WAC 2.0 feature
541         featureType = APP_TYPE_WAC20;
542     } else if (strstr(feature, PluginsPrefix::W3CPluginsPrefix) == feature) {
543         // W3C standard feature
544         // Both WAC and TIZEN WebApp are possible to use W3C plugins
545         return true;
546     } else {
547         // unknown feature
548         // unknown feature will be checked next step
549         return true;
550     }
551
552     if (appType == featureType) {
553         return true;
554     }
555     return false;
556 }
557
558 bool TaskWidgetConfig::parseVersionString(const std::string &version,
559         long &majorVersion, long &minorVersion, long &microVersion) const
560 {
561     std::istringstream inputString(version);
562     inputString >> majorVersion;
563     if (inputString.bad() || inputString.fail()) {
564         LogWarning("Invalid minVersion format.");
565         return false;
566     }
567     inputString.get(); // skip period
568     inputString >> minorVersion;
569     if (inputString.bad() || inputString.fail()) {
570         LogWarning("Invalid minVersion format");
571         return false;
572     } else {
573         inputString.get(); // skip period
574         if (inputString.bad() || inputString.fail()) {
575             inputString >> microVersion;
576         }
577     }
578     return true;
579 }
580
581 bool TaskWidgetConfig::isMinVersionCompatible(WrtDB::AppType appType,
582         const DPL::OptionalString &widgetVersion) const
583 {
584     if (widgetVersion.IsNull() || (*widgetVersion).empty())
585     {
586         LogWarning("minVersion attribute is empty. WRT assumes platform "
587                 "supports this widget.");
588         return true;
589     }
590
591     //Parse widget version
592     long majorWidget = 0, minorWidget = 0, microWidget = 0;
593     if (!parseVersionString(DPL::ToUTF8String(*widgetVersion), majorWidget,
594             minorWidget, microWidget)) {
595         LogWarning("Invalid format of widget version string.");
596         return true;
597     }
598
599     //Parse supported version
600     long majorSupported = 0, minorSupported = 0, microSupported = 0;
601     std::string version;
602     if (appType == WrtDB::AppType::APP_TYPE_TIZENWEBAPP) {
603         version = WrtDB::GlobalConfig::GetTizenVersion();
604     } else if (appType == WrtDB::AppType::APP_TYPE_WAC20) {
605         version = WrtDB::GlobalConfig::GetWACVersion();
606     } else {
607         LogWarning("Invaild AppType");
608         return false;
609     }
610
611     if (!parseVersionString(version,
612                 majorSupported, minorSupported, microSupported)) {
613         LogWarning("Invalid format of WAC version string.");
614         return true;
615     }
616
617     if (majorWidget > majorSupported ||
618             minorWidget > minorSupported ||
619             microWidget > microSupported) {
620         LogInfo("Platform doesn't support this widget.");
621         return false;
622     }
623     return true;
624 }
625
626 bool TaskWidgetConfig::isTizenWebApp() const
627 {
628     bool ret = FALSE;
629     if (m_installContext.widgetConfig.type.appType
630             == WrtDB::AppType::APP_TYPE_TIZENWEBAPP)
631         ret = TRUE;
632
633     return ret;
634 }
635
636 } //namespace WidgetInstall
637 } //namespace Jobs