[Release] wrt-installer_0.1.9
[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
23 #include <sstream>
24 #include <string>
25 #include <sys/stat.h>
26 #include <dirent.h>
27
28 #include <dpl/errno_string.h>
29 #include <dpl/foreach.h>
30 #include <dpl/localization/w3c_file_localization.h>
31 #include <dpl/singleton_impl.h>
32 #include <dpl/utils/mime_type_utils.h>
33 #include <dpl/utils/wrt_global_settings.h>
34 #include <dpl/utils/wrt_utility.h>
35 #include <dpl/wrt-dao-ro/global_config.h>
36 #include <dpl/wrt-dao-rw/feature_dao.h>
37
38 #include <libiriwrapper.h>
39 #include <parser_runner.h>
40 #include <root_parser.h>
41
42 #include <widget_install/job_widget_install.h>
43 #include <widget_install/task_widget_config.h>
44 #include <widget_install/widget_install_context.h>
45 #include <widget_install/widget_install_errors.h>
46 #include <widget_parser.h>
47
48 namespace { // anonymous
49 const DPL::String BR = DPL::FromUTF8String("<br>");
50 const std::string WIDGET_NOT_COMPATIBLE = "This widget is "
51                                           "not compatible with WRT.<br><br>";
52 const std::string QUESTION = "Do you want to install it anyway?";
53
54 const char *const DEFAULT_LANGUAGE = "default";
55
56 const char *const WRT_WIDGET_CONFIG_FILE_NAME = "config.xml";
57
58 const std::string WINDGET_INSTALL_NETWORK_ACCESS = "network access";
59 }
60
61 namespace Jobs {
62 namespace WidgetInstall {
63 void InstallerTaskWidgetPopupData::PopupData::addWidgetInfo(
64     const DPL::String &info)
65 {
66     widgetInfo = info;
67 }
68
69 TaskWidgetConfig::TaskWidgetConfig(InstallerContext& installContext) :
70     DPL::TaskDecl<TaskWidgetConfig>(this),
71     WidgetInstallPopup(installContext),
72     m_installContext(installContext)
73 {
74     AddStep(&TaskWidgetConfig::StepProcessConfigurationFile);
75     AddStep(&TaskWidgetConfig::ReadLocaleFolders);
76     AddStep(&TaskWidgetConfig::ProcessLocalizedStartFiles);
77     AddStep(&TaskWidgetConfig::ProcessBackgroundPageFile);
78     AddStep(&TaskWidgetConfig::ProcessLocalizedIcons);
79     AddStep(&TaskWidgetConfig::ProcessWidgetInstalledPath);
80     AddStep(&TaskWidgetConfig::StepVerifyFeatures);
81     AddStep(&TaskWidgetConfig::StepCheckMinVersionInfo);
82
83     if (!GlobalSettings::TestModeEnabled() && !m_installContext.m_quiet) {
84         AddStep(
85             &TaskWidgetConfig::
86                 StepCancelWidgetInstallationAfterVerifyFeatures);
87         AddStep(&TaskWidgetConfig::StepShowWidgetInfo);
88         AddStep(&TaskWidgetConfig::StepCancelWidgetInstallation);
89         AddStep(&TaskWidgetConfig::StepCancelWidgetInstallationAfterMinVersion);
90         AddStep(&TaskWidgetConfig::StepDeletePopupWin);
91     }
92 }
93
94 void TaskWidgetConfig::StepProcessConfigurationFile()
95 {
96     Try
97     {
98         std::string path = m_installContext.locations->getConfigurationDir();
99         LogInfo("path: " << path);
100
101         processFile(path, m_installContext.widgetConfig);
102     }
103     Catch(Exception::ConfigParseFailed)
104     {
105         LogError("Parsing failed.");
106         ReThrow(Exceptions::WidgetConfigFileInvalid);
107     }
108
109     m_installContext.job->UpdateProgress(
110         InstallerContext::INSTALL_WIDGET_CONFIG1,
111         "Parse elements of configuration file and save them");
112 }
113
114 void TaskWidgetConfig::ReadLocaleFolders()
115 {
116     LogDebug("Reading locale");
117     //Adding default locale
118     m_localeFolders.insert(L"");
119
120     std::string localePath =
121         m_installContext.locations->getConfigurationDir() + "/locales";
122     DIR* localeDir = opendir(localePath.c_str());
123     if (!localeDir) {
124         LogDebug("No /locales directory in the widget package.");
125         return;
126     }
127
128
129
130     struct stat statStruct;
131     struct dirent dirent;
132     struct dirent *result;
133     int return_code;
134     errno = 0;
135     for (return_code = readdir_r(localeDir, &dirent, &result);
136             result != NULL && return_code == 0;
137             return_code = readdir_r(localeDir, &dirent, &result))
138     {
139         DPL::String dirName = DPL::FromUTF8String(dirent.d_name);
140         std::string absoluteDirName = localePath + "/";
141         absoluteDirName += dirent.d_name;
142
143         if (stat(absoluteDirName.c_str(), &statStruct) != 0) {
144             LogError("stat() failed with " << DPL::GetErrnoString());
145             continue;
146         }
147
148         if (S_ISDIR(statStruct.st_mode)) {
149             //Yes, we ignore current, parent & hidden directories
150             if (dirName[0] != L'.') {
151                 LogDebug("Adding locale directory \"" << dirName << "\"");
152                 m_localeFolders.insert(dirName);
153             }
154         }
155     }
156
157     if (return_code != 0 || errno != 0) {
158         LogError("readdir_r() failed with " << DPL::GetErrnoString());
159     }
160
161     if (-1 == TEMP_FAILURE_RETRY(closedir(localeDir))) {
162         LogError("Failed to close dir: " << localePath << " with error: "
163                                          << DPL::GetErrnoString());
164     }
165 }
166
167 void TaskWidgetConfig::ProcessLocalizedStartFiles()
168 {
169     typedef DPL::String S;
170     ProcessStartFile(
171         m_installContext.widgetConfig.configInfo.startFile,
172         m_installContext.widgetConfig.configInfo.
173             startFileContentType,
174         m_installContext.widgetConfig.configInfo.startFileEncoding,
175         true);
176     ProcessStartFile(S(L"index.htm"), S(L"text/html"));
177     ProcessStartFile(S(L"index.html"), S(L"text/html"));
178     ProcessStartFile(S(L"index.svg"), S(L"image/svg+xml"));
179     ProcessStartFile(S(L"index.xhtml"), S(L"application/xhtml+xml"));
180     ProcessStartFile(S(L"index.xht"), S(L"application/xhtml+xml"));
181     // TODO: (l.wrzosek) we need better check if in current locales widget is
182     // valid.
183     FOREACH(it, m_installContext.widgetConfig.localizationData.startFiles) {
184         if (it->propertiesForLocales.size() > 0) {
185             return;
186         }
187     }
188     ThrowMsg(Exceptions::WidgetConfigFileInvalid,
189              L"The Widget has no valid start file");
190 }
191
192 void TaskWidgetConfig::ProcessStartFile(const DPL::OptionalString& path,
193                                         const DPL::OptionalString& type,
194                                         const DPL::OptionalString& encoding,
195                                         bool typeForcedInConfig)
196 {
197     using namespace WrtDB;
198
199     if (!!path) {
200         WidgetRegisterInfo::LocalizedStartFile startFileData;
201         startFileData.path = *path;
202
203         FOREACH(i, m_localeFolders) {
204             DPL::String pathPrefix = *i;
205             if (!pathPrefix.empty()) {
206                 pathPrefix = L"locales/" + pathPrefix + L"/";
207             }
208
209             DPL::String relativePath = pathPrefix + *path;
210             DPL::String absolutePath = DPL::FromUTF8String(
211                     m_installContext.locations->getConfigurationDir()) + L"/" +
212                 relativePath;
213
214             // get property data from packaged app
215             if (WrtUtilFileExists(DPL::ToUTF8String(absolutePath))) {
216                 WidgetRegisterInfo::StartFileProperties startFileProperties;
217                 if (!!type) {
218                     startFileProperties.type = *type;
219                 } else {
220                     startFileProperties.type =
221                         MimeTypeUtils::identifyFileMimeType(absolutePath);
222                 }
223
224                 //proceed only if MIME type is supported
225                 if (MimeTypeUtils::isMimeTypeSupportedForStartFile(
226                         startFileProperties.type))
227                 {
228                     if (!!encoding) {
229                         startFileProperties.encoding = *encoding;
230                     } else {
231                         MimeTypeUtils::MimeAttributes attributes =
232                             MimeTypeUtils::getMimeAttributes(
233                                 startFileProperties.type);
234                         if (attributes.count(L"charset") > 0) {
235                             startFileProperties.encoding =
236                                 attributes[L"charset"];
237                         } else {
238                             startFileProperties.encoding = L"UTF-8";
239                         }
240                     }
241
242                     startFileData.propertiesForLocales[*i] =
243                         startFileProperties;
244                 } else {
245                     //9.1.16.5.content.8
246                     //(there seems to be no similar requirement in .6,
247                     //so let's throw only when mime type is
248                     // provided explcitly in config.xml)
249                     if (typeForcedInConfig) {
250                         ThrowMsg(Exceptions::WidgetConfigFileInvalid,
251                                  "Unsupported MIME type for start file.");
252                     }
253                 }
254             } else {
255                 // set property data for hosted start url
256                 // Hosted start url only support TIZEN WebApp
257                 if (m_installContext.widgetConfig.webAppType ==
258                     APP_TYPE_TIZENWEBAPP)
259                 {
260                     std::string startPath = DPL::ToUTF8String(
261                             startFileData.path);
262
263                     if (strstr(startPath.c_str(),
264                                "http") == startPath.c_str())
265                     {
266                         WidgetRegisterInfo::StartFileProperties
267                             startFileProperties;
268                         if (!!type) {
269                             startFileProperties.type = *type;
270                         }
271                         if (!!encoding) {
272                             startFileProperties.encoding = *encoding;
273                         }
274                         startFileData.propertiesForLocales[*i] =
275                             startFileProperties;
276                     }
277                 }
278             }
279         }
280
281         m_installContext.widgetConfig.localizationData.startFiles.push_back(
282             startFileData);
283     }
284 }
285
286 void TaskWidgetConfig::ProcessBackgroundPageFile()
287 {
288     if (!!m_installContext.widgetConfig.configInfo.backgroundPage) {
289         // check whether file exists
290         DPL::String backgroundPagePath = DPL::FromUTF8String(
291                 m_installContext.locations->getConfigurationDir()) + L"/" +
292             *m_installContext.widgetConfig.configInfo.backgroundPage;
293         //if no then cancel installation
294         if (!WrtUtilFileExists(DPL::ToUTF8String(backgroundPagePath))) {
295             ThrowMsg(Exceptions::WidgetConfigFileInvalid,
296                      L"Given background page file not found in archive");
297         }
298     }
299 }
300
301 void TaskWidgetConfig::ProcessLocalizedIcons()
302 {
303     using namespace WrtDB;
304     ProcessIcon(ConfigParserData::Icon(L"icon.svg"));
305     ProcessIcon(ConfigParserData::Icon(L"icon.ico"));
306     ProcessIcon(ConfigParserData::Icon(L"icon.png"));
307     ProcessIcon(ConfigParserData::Icon(L"icon.gif"));
308     ProcessIcon(ConfigParserData::Icon(L"icon.jpg"));
309
310     FOREACH(i, m_installContext.widgetConfig.configInfo.iconsList)
311     {
312         ProcessIcon(*i);
313     }
314 }
315
316 void TaskWidgetConfig::ProcessIcon(const WrtDB::ConfigParserData::Icon& icon)
317 {
318     LogInfo("enter");
319     bool isAnyIconValid = false;
320     //In case a default filename is passed as custom filename in config.xml, we
321     //need to keep a set of already processed filenames to avoid icon
322     // duplication
323     //in database.
324
325     using namespace WrtDB;
326
327     if (m_processedIconSet.count(icon.src) > 0) {
328         return;
329     }
330     m_processedIconSet.insert(icon.src);
331
332     LocaleSet localesAvailableForIcon;
333
334     FOREACH(i, m_localeFolders)
335     {
336         DPL::String pathPrefix = *i;
337         if (!pathPrefix.empty()) {
338             pathPrefix = L"locales/" + pathPrefix + L"/";
339         }
340
341         DPL::String relativePath = pathPrefix + icon.src;
342         DPL::String absolutePath = DPL::FromUTF8String(
343                 m_installContext.locations->getConfigurationDir()) + L"/" +
344             relativePath;
345
346         if (WrtUtilFileExists(DPL::ToUTF8String(absolutePath))) {
347             DPL::String type = MimeTypeUtils::identifyFileMimeType(absolutePath);
348
349             if (MimeTypeUtils::isMimeTypeSupportedForIcon(type)) {
350                 isAnyIconValid = true;
351                 localesAvailableForIcon.insert(*i);
352                 LogInfo("Icon absolutePath :" << absolutePath <<
353                         ", assigned locale :" << *i << ", type: " << type);
354             }
355         }
356     }
357
358     if (isAnyIconValid) {
359         WidgetRegisterInfo::LocalizedIcon localizedIcon(icon,
360                                                         localesAvailableForIcon);
361         m_installContext.widgetConfig.localizationData.icons.push_back(
362             localizedIcon);
363     }
364 }
365
366 void TaskWidgetConfig::ProcessWidgetInstalledPath()
367 {
368     LogDebug("ProcessWidgetInstalledPath");
369     m_installContext.widgetConfig.widgetInstalledPath =
370         DPL::FromUTF8String(
371             m_installContext.locations->getPackageInstallationDir());
372 }
373
374 void TaskWidgetConfig::StepCancelWidgetInstallationAfterVerifyFeatures()
375 {
376     LogDebug("StepCancelWidgetInstallationAfterVerifyFeatures");
377     if (InfoPopupButton::WRT_POPUP_BUTTON_CANCEL == m_installCancel) {
378         m_installCancel = WRT_POPUP_BUTTON;
379         destroyPopup();
380         ThrowMsg(Exceptions::WidgetConfigFileInvalid, "Widget not allowed");
381     }
382 }
383
384 void TaskWidgetConfig::StepCancelWidgetInstallation()
385 {
386     if (InfoPopupButton::WRT_POPUP_BUTTON_CANCEL == m_installCancel) {
387         m_installCancel = WRT_POPUP_BUTTON;
388         destroyPopup();
389         ThrowMsg(Exceptions::NotAllowed, "Widget not allowed");
390     }
391 }
392
393 void TaskWidgetConfig::StepCancelWidgetInstallationAfterMinVersion()
394 {
395     if (InfoPopupButton::WRT_POPUP_BUTTON_CANCEL == m_installCancel) {
396         m_installCancel = WRT_POPUP_BUTTON;
397         destroyPopup();
398         ThrowMsg(Exceptions::NotAllowed, "WRT version incompatible.");
399     }
400 }
401
402 void TaskWidgetConfig::createInstallPopup(PopupType type,
403                                           const std::string &label)
404 {
405     m_installContext.job->Pause();
406     if (m_popup) {
407         destroyPopup();
408     }
409
410     bool ret = createPopup();
411     if (ret) {
412         loadPopup(type, label);
413         showPopup();
414     }
415 }
416
417 void TaskWidgetConfig::StepDeletePopupWin()
418 {
419     destroyPopup();
420 }
421
422 void TaskWidgetConfig::StepShowWidgetInfo()
423 {
424     if (!m_popupData.widgetInfo.empty()) {
425         std::string label = DPL::ToUTF8String(m_popupData.widgetInfo);
426         createInstallPopup(PopupType::WIDGET_FEATURE_INFO, label);
427         m_installContext.job->UpdateProgress(
428             InstallerContext::INSTALL_WIDGET_CONFIG2,
429             "Show Widget Info Finished");
430     }
431 }
432
433 void TaskWidgetConfig::StepCheckMinVersionInfo()
434 {
435     if (!isMinVersionCompatible(
436             m_installContext.widgetConfig.webAppType.appType,
437             m_installContext.widgetConfig.minVersion))
438     {
439         if (!GlobalSettings::TestModeEnabled() && !m_installContext.m_quiet) {
440             LogDebug("Platform version to low - launching");
441             std::string label = WIDGET_NOT_COMPATIBLE + QUESTION;
442             createInstallPopup(PopupType::WIDGET_MIN_VERSION, label);
443         } else {
444             LogError(
445                 "Platform version lower than required -> cancelling installation");
446             ThrowMsg(Exceptions::NotAllowed,
447                      "Platform version does not meet requirements");
448         }
449     }
450
451     m_installContext.job->UpdateProgress(
452         InstallerContext::INSTALL_WIDGET_CONFIG2,
453         "Check MinVersion Finished");
454 }
455
456 void TaskWidgetConfig::StepVerifyFeatures()
457 {
458     using namespace WrtDB;
459     ConfigParserData &data = m_installContext.widgetConfig.configInfo;
460     ConfigParserData::FeaturesList list = data.featuresList;
461     ConfigParserData::FeaturesList newList;
462
463     //in case of tests, this variable is unused
464     std::string featureInfo;
465     FOREACH(it, list)
466     {
467         // check feature vender for permission
468         // WAC, TIZEN WebApp cannot use other feature
469
470         if (!isFeatureAllowed(m_installContext.widgetConfig.webAppType.appType,
471                               it->name))
472         {
473             LogInfo("This application type not allowed to use this feature");
474             ThrowMsg(
475                 Exceptions::WidgetConfigFileInvalid,
476                 "This app type [" <<
477                 m_installContext.widgetConfig.webAppType.getApptypeToString()
478                                   <<
479                 "] cannot be allowed to use [" <<
480                 DPL::ToUTF8String(it->name) + "] feature");
481         }
482         if (!WrtDB::FeatureDAOReadOnly::isFeatureInstalled(
483                 DPL::ToUTF8String(it->name)))
484         {
485             LogWarning("Feature not found. Checking if required :[" <<
486                        DPL::ToUTF8String(it->name) << "]");
487
488             if (it->required) {
489                 /**
490                  * WL-3210 The WRT MUST inform the user if a widget cannot be
491                  * installed because one or more required features are not
492                  * supported.
493                  */
494                 std::ostringstream os;
495                 os <<
496                 "Widget cannot be installed, required feature is missing:["
497                    << DPL::ToUTF8String(it->name) << "]";
498                 if (!GlobalSettings::TestModeEnabled() && !isTizenWebApp()) {
499                     std::string label = os.str();
500                     createInstallPopup(PopupType::WIDGET_WRONG_FEATURE_INFO,
501                                        label);
502                 }
503                 ThrowMsg(Exceptions::WidgetConfigFileInvalid, os.str());
504             }
505         } else {
506             newList.insert(*it);
507             featureInfo += DPL::ToUTF8String(it->name);
508             featureInfo += DPL::ToUTF8String(BR);
509         }
510     }
511     if (!data.accessInfoSet.empty()) {
512         featureInfo += WINDGET_INSTALL_NETWORK_ACCESS;
513         featureInfo += DPL::ToUTF8String(BR);
514     }
515     data.featuresList = newList;
516     if (!featureInfo.empty()) {
517         m_popupData.addWidgetInfo(DPL::FromUTF8String(featureInfo));
518     }
519
520     m_installContext.job->UpdateProgress(
521         InstallerContext::INSTALL_WIDGET_CONFIG2,
522         "Widget Config step2 Finished");
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     std::string featureStr = DPL::ToUTF8String(featureName);
535     const char* feature = featureStr.c_str();
536
537     // check prefix of  feature name
538     if (strstr(feature, PluginsPrefix::TIZENPluginsPrefix) == feature) {
539         // Tizen WebApp feature
540         featureType = APP_TYPE_TIZENWEBAPP;
541     } else if (strstr(feature, PluginsPrefix::WACPluginsPrefix) == feature) {
542         // WAC 2.0 feature
543         featureType = APP_TYPE_WAC20;
544     } else if (strstr(feature, PluginsPrefix::W3CPluginsPrefix) == feature) {
545         // W3C standard feature
546         // Both WAC and TIZEN WebApp are possible to use W3C plugins
547         return true;
548     } else {
549         // unknown feature
550         // unknown feature will be checked next step
551         return true;
552     }
553
554     if (appType == featureType) {
555         return true;
556     }
557     return false;
558 }
559
560 bool TaskWidgetConfig::parseVersionString(const std::string &version,
561                                           long &majorVersion,
562                                           long &minorVersion,
563                                           long &microVersion) const
564 {
565     std::istringstream inputString(version);
566     inputString >> majorVersion;
567     if (inputString.bad() || inputString.fail()) {
568         LogWarning("Invalid minVersion format.");
569         return false;
570     }
571     inputString.get(); // skip period
572     inputString >> minorVersion;
573     if (inputString.bad() || inputString.fail()) {
574         LogWarning("Invalid minVersion format");
575         return false;
576     } else {
577         inputString.get(); // skip period
578         if (inputString.bad() || inputString.fail()) {
579             inputString >> microVersion;
580         }
581     }
582     return true;
583 }
584
585 bool TaskWidgetConfig::isMinVersionCompatible(
586     WrtDB::AppType appType,
587     const DPL::OptionalString &
588     widgetVersion) const
589 {
590     if (widgetVersion.IsNull() || (*widgetVersion).empty()) {
591         LogWarning("minVersion attribute is empty. WRT assumes platform "
592                    "supports this widget.");
593         return false;
594     }
595
596     //Parse widget version
597     long majorWidget = 0, minorWidget = 0, microWidget = 0;
598     if (!parseVersionString(DPL::ToUTF8String(*widgetVersion), majorWidget,
599                             minorWidget, microWidget))
600     {
601         LogWarning("Invalid format of widget version string.");
602         return false;
603     }
604
605     //Parse supported version
606     long majorSupported = 0, minorSupported = 0, microSupported = 0;
607     std::string version;
608     if (appType == WrtDB::AppType::APP_TYPE_TIZENWEBAPP) {
609         version = WrtDB::GlobalConfig::GetTizenVersion();
610     } else if (appType == WrtDB::AppType::APP_TYPE_WAC20) {
611         version = WrtDB::GlobalConfig::GetWACVersion();
612     } else {
613         LogWarning("Invaild AppType");
614         return false;
615     }
616
617     if (!parseVersionString(version,
618                             majorSupported, minorSupported, microSupported))
619     {
620         LogWarning("Invalid format of platform version string.");
621         return true;
622     }
623
624     if (majorWidget > majorSupported ||
625         (majorWidget == majorSupported && minorWidget > minorSupported) ||
626         (majorWidget == majorSupported && minorWidget == minorSupported
627          && microWidget > microSupported))
628     {
629         LogInfo("Platform doesn't support this widget.");
630         return false;
631     }
632     return true;
633 }
634
635 bool TaskWidgetConfig::isTizenWebApp() const
636 {
637     bool ret = FALSE;
638     if (m_installContext.widgetConfig.webAppType.appType
639         == WrtDB::AppType::APP_TYPE_TIZENWEBAPP)
640     {
641         ret = TRUE;
642     }
643
644     return ret;
645 }
646
647 bool TaskWidgetConfig::parseConfigurationFileBrowser(
648     WrtDB::ConfigParserData& configInfo,
649     const std::string& _currentPath)
650 {
651     ParserRunner parser;
652     Try
653     {
654         parser.Parse(_currentPath, ElementParserPtr(new
655                                                     RootParser<
656                                                         WidgetParser>(
657                                                         configInfo,
658                                                         DPL::FromUTF32String(
659                                                             L"widget"))));
660     }
661     Catch(ElementParser::Exception::Base)
662     {
663         LogError("Invalid widget configuration file!");
664         return false;
665     }
666     return true;
667 }
668
669 bool TaskWidgetConfig::parseConfigurationFileWidget(
670     WrtDB::ConfigParserData& configInfo,
671     const std::string& _currentPath)
672 {
673     ParserRunner parser;
674
675     //TODO: rewrite this madness
676     std::string cfgAbsPath;
677     DIR* dir = NULL;
678
679     dir = opendir(_currentPath.c_str());
680     if (dir == NULL) {
681         return false;
682     }
683     bool has_config_xml = false;
684     struct dirent ptr;
685     struct dirent *result;
686     int return_code;
687     errno = 0;
688
689     //Find configuration file, based on its name
690     for (return_code = readdir_r(dir, &ptr, &result);
691                 result != NULL && return_code == 0;
692                 return_code = readdir_r(dir, &ptr, &result))
693     {
694         if (ptr.d_type == DT_REG) {
695             if (!strcmp(ptr.d_name, WRT_WIDGET_CONFIG_FILE_NAME)) {
696                 std::string dName(ptr.d_name);
697                 WrtUtilJoinPaths(cfgAbsPath, _currentPath, dName);
698
699                 //Parse widget configuration file
700                 LogDebug("Found config: " << cfgAbsPath);
701
702                 Try
703                 {
704                     parser.Parse(cfgAbsPath, ElementParserPtr(new
705                                                               RootParser<
706                                                                   WidgetParser>(
707                                                                   configInfo,
708                                                                   DPL
709                                                                       ::
710                                                                       FromUTF32String(
711                                                                       L"widget"))));
712                 }
713                 Catch(ElementParser::Exception::Base)
714                 {
715                     LogError("Invalid widget configuration file!");
716                     if (-1 == TEMP_FAILURE_RETRY(closedir(dir))) {
717                         LogError(
718                             "Failed to close dir: " << _currentPath <<
719                             " with error: "
720                                                     << DPL::GetErrnoString());
721                     }
722                     return false;
723                 }
724
725                 has_config_xml = true;
726                 break;
727             }
728         }
729     }
730     if (errno != 0) {
731         LogError("readdir_r() failed with " << DPL::GetErrnoString());
732     }
733     errno = 0;
734     if (-1 == TEMP_FAILURE_RETRY(closedir(dir))) {
735         LogError("Failed to close dir: " << _currentPath << " with error: "
736                                          << DPL::GetErrnoString());
737     }
738
739     //We must have config.xml so leaveing if we doesn't
740     if (!has_config_xml) {
741         LogError("Invalid archive");
742         return false;
743     }
744     return true;
745 }
746
747 bool TaskWidgetConfig::locateAndParseConfigurationFile(
748     const std::string& _currentPath,
749     WrtDB::WidgetRegisterInfo& pWidgetConfigInfo,
750     const std::string& baseFolder)
751 {
752     using namespace WrtDB;
753
754     ConfigParserData& configInfo = pWidgetConfigInfo.configInfo;
755
756     // check if this installation from browser, or not.
757     size_t pos = _currentPath.rfind("/");
758     std::ostringstream infoPath;
759     infoPath << _currentPath.substr(pos + 1);
760
761     if (infoPath.str() != WRT_WIDGET_CONFIG_FILE_NAME) {
762         if (_currentPath.empty() || baseFolder.empty()) {
763             return false;
764         }
765         // in case of general installation using wgt archive
766         if (!parseConfigurationFileWidget(configInfo, _currentPath))
767         {
768             return false;
769         }
770     } else {
771         // in case of browser installation
772         if (!parseConfigurationFileBrowser(configInfo, _currentPath))
773         {
774             return false;
775         }
776     }
777
778     if (!fillWidgetConfig(pWidgetConfigInfo, configInfo)) {
779         return false;
780     }
781     return true;
782 }
783
784 bool TaskWidgetConfig::fillWidgetConfig(
785     WrtDB::WidgetRegisterInfo& pWidgetConfigInfo,
786     WrtDB::ConfigParserData& configInfo)
787 {
788     if (!!configInfo.widget_id) {
789         if (!pWidgetConfigInfo.guid) {
790             pWidgetConfigInfo.guid = configInfo.widget_id;
791         } else {
792             if (pWidgetConfigInfo.guid != configInfo.widget_id) {
793                 LogError("Invalid archive");
794                 return false;
795             }
796         }
797     }
798     if (!!configInfo.tizenAppId) {
799         if (DPL::ToUTF8String(pWidgetConfigInfo.tzAppid).compare(
800                 DPL::ToUTF8String(*configInfo.tizenAppId)) < 0)
801         {
802             LogError("Invalid archive - Tizen App ID not same error");
803             return false;
804         }
805     }
806     if (!!configInfo.tizenPkgId) {
807         if (pWidgetConfigInfo.tzPkgid != *configInfo.tizenPkgId) {
808             LogError("Invalid archive - Tizen Pkg ID not same error");
809             return false;
810         }
811     }
812     if (!!configInfo.version) {
813         if (!pWidgetConfigInfo.version) {
814             pWidgetConfigInfo.version = configInfo.version;
815         } else {
816             if (pWidgetConfigInfo.version != configInfo.version) {
817                 LogError("Invalid archive");
818                 return false;
819             }
820         }
821     }
822     if (!!configInfo.minVersionRequired) {
823         pWidgetConfigInfo.minVersion = configInfo.minVersionRequired;
824     } else if (!!configInfo.tizenMinVersionRequired) {
825         pWidgetConfigInfo.minVersion = configInfo.tizenMinVersionRequired;
826     }
827     return true;
828 }
829
830 void TaskWidgetConfig::processFile(
831     const std::string& path,
832     WrtDB::WidgetRegisterInfo &
833     widgetConfiguration)
834 {
835     if (!locateAndParseConfigurationFile(path, widgetConfiguration,
836                                          DEFAULT_LANGUAGE))
837     {
838         LogWarning("Widget archive: Failed while parsing config file");
839         ThrowMsg(Exception::ConfigParseFailed, path);
840     }
841 }
842 } //namespace WidgetInstall
843 } //namespace Jobs