7dff757c10daaa8d720caf931601bfbd3476bb44
[framework/web/wrt-plugins-tizen.git] / src / Filesystem / Manager.cpp
1 //
2 // Tizen Web Device API
3 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
4 //
5 // Licensed under the Apache License, Version 2.0 (the License);
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17
18
19 #include "Manager.h"
20
21 #include <unistd.h>
22 #include <sys/stat.h>
23 #include <errno.h>
24 #include <pcrecpp.h>
25 #include <ctime>
26 #include <sstream>
27 #include <dirent.h>
28 #include <dpl/scoped_ptr.h>
29
30 #include <Commons/Exception.h>
31 #include <Commons/Regex.h>
32 #include "PathUtils.h"
33 #include "StorageProperties.h"
34 #include "Node.h"
35 #include "Utils.h"
36 #include <app.h>
37 #include <Logger.h>
38
39 namespace {
40 const char* PATH_DOWNLOADS = "/opt/usr/media/Downloads";
41 const char* PATH_DOCUMENTS = "/opt/usr/media/Documents";
42 const char* PATH_SOUNDS = "/opt/usr/media/Sounds";
43 const char* PATH_IMAGES = "/opt/usr/media/Images";
44 const char* PATH_VIDEOS = "/opt/usr/media/Videos";
45 const char* PATH_RINGTONE = "/opt/share/settings/Ringtones/";
46 }
47
48 using namespace WrtDeviceApis;
49 using namespace WrtDeviceApis::Commons;
50
51 namespace DeviceAPI {
52 namespace Filesystem {
53 Manager::Locations Manager::m_locations;
54 Manager::RootList Manager::m_rootlist;
55 Manager::SubRootList Manager::m_subrootlist;
56 const std::size_t Manager::m_maxPathLength = 256;
57 NodeList Manager::m_openedNodes;
58 std::vector<Manager::WatcherPtr> Manager::m_watchers;
59
60 bool Manager::fileExists(const std::string &file)
61 {
62     errno = 0;
63     struct stat info;
64     memset(&info, 0, sizeof(struct stat));
65     int status = lstat(file.c_str(), &info);
66     if (status == 0) {
67         return true;
68     } else if (errno == ENOENT) {
69         return false;
70     }
71     ThrowMsg(Commons::PlatformException, "Cannot stat file.");
72 }
73
74 bool Manager::getSupportedDeviceCB(int storage, storage_type_e type, storage_state_e state, const char *path, void *user_data)
75 {
76         std::vector<StoragePropertiesPtr>* storageVector = (std::vector<StoragePropertiesPtr>*)user_data;
77         StoragePropertiesPtr storageItem(new StorageProperties());
78
79         int size = 12;
80         char buf[size];
81         std::string lable;
82         std::string fullpath(path);
83         if (type == STORAGE_TYPE_INTERNAL) {
84                 snprintf(buf, size, "internal%d", storage);
85                 lable.append(buf);
86         } else if (type == STORAGE_TYPE_EXTERNAL) {
87                 snprintf(buf, size, "removable%d", storage);
88                 lable.append(buf);
89         }
90         LoggerD(lable << "state" << state);
91
92         storageItem->setId(storage);
93         storageItem->setLabel(lable);
94         storageItem->setType((short)type);
95         storageItem->setState((short)state);
96         storageItem->setFullPath(fullpath);
97
98         storageVector->insert(storageVector->end(), storageItem);
99
100         return true;
101 }
102
103 void Manager::storageStateChangedCB(int storage, storage_state_e state, void *user_data)
104 {
105         if (user_data != NULL) {
106                 watcherList* m_watcherList = (watcherList *)user_data;
107                 watcherList::iterator it = m_watcherList->begin();
108                 for(; it!= m_watcherList->end(); ++it) {
109                         (*it)->StorageStateHasChanged(storage, state);
110                 }
111         }
112 }
113
114 void Manager::addOpenedNode(const INodePtr& node)
115 {
116     NodeListIterator it = m_openedNodes.begin();
117     for (; it != m_openedNodes.end(); ++it) {
118         if (node.Get() == (*it).Get()) {
119             //node is added already
120             return;
121         }
122     }
123     m_openedNodes.push_back(node);
124 }
125
126 void Manager::removeOpenedNode(const INodePtr& node)
127 {
128     NodeListIterator it = m_openedNodes.begin();
129     for (; it != m_openedNodes.end(); ++it) {
130         if ((*it).Get() == node.Get()) {
131             m_openedNodes.erase(it);
132             break;
133         }
134     }
135 }
136
137 bool Manager::checkIfOpened(const IPathPtr& path) const
138 {
139     NodeListIterator it = m_openedNodes.begin();
140     for (; it != m_openedNodes.end(); ++it) {
141         if (*path == *(*it)->getPath()) {
142             return true;
143         }
144     }
145     return false;
146 }
147
148 Manager::Manager()
149 {
150     static bool initialized = init();
151     (void) initialized;
152 }
153
154 Manager::~Manager()
155 {
156 }
157
158 StorageList Manager::getStorageList() const
159 {
160     return m_locations;
161 }
162
163 IPathPtr Manager::getBasePath() const
164 {
165     Locations::const_iterator it = m_locations.find(m_subrootlist.find(LT_ROOT)->second);
166     if (it == m_locations.end()) {
167         ThrowMsg(Commons::PlatformException, "Base path not available.");
168     }
169     return it->second;
170 }
171
172 IPathPtr Manager::getLocationPath(LocationType type) const
173 {
174     Locations::const_iterator it = m_locations.find(m_subrootlist.find(type)->second);
175     if (it != m_locations.end()) {
176         return it->second->clone();
177     }
178     return IPathPtr();
179 }
180
181 LocationPaths Manager::getLocationPaths() const
182 {
183     LocationPaths result;
184     Locations::const_iterator it = m_locations.begin();
185     for (; it != m_locations.end(); ++it) {
186         result.push_back(it->second->clone());
187     }
188     return result;
189 }
190
191 LocationTypes Manager::getLocations() const
192 {
193     LocationTypes result;
194     SubRootList::const_iterator it = m_subrootlist.begin();
195     for (; it != m_subrootlist.end(); ++it) {
196         result.push_back(it->first);
197     }
198     return result;
199 }
200
201 void Manager::getNode(const EventResolvePtr& event)
202 {
203     EventRequestReceiver<EventResolve>::PostRequest(event);
204 }
205
206 void Manager::getStorage(const EventGetStoragePtr& event)
207 {
208         EventRequestReceiver<EventGetStorage>::PostRequest(event);
209 }
210
211 void Manager::listStorages(const EventListStoragesPtr& event)
212 {
213         EventRequestReceiver<EventListStorages>::PostRequest(event);
214 }
215
216 std::size_t Manager::getMaxPathLength() const
217 {
218     return m_maxPathLength;
219 }
220
221 void Manager::copy(const EventCopyPtr& event)
222 {
223     EventRequestReceiver<EventCopy>::PostRequest(event);
224 }
225
226 void Manager::move(const EventMovePtr& event)
227 {
228     EventRequestReceiver<EventMove>::PostRequest(event);
229 }
230
231 void Manager::create(const EventCreatePtr& event)
232 {
233     EventRequestReceiver<EventCreate>::PostRequest(event);
234 }
235
236 void Manager::remove(const EventRemovePtr& event)
237 {
238     EventRequestReceiver<EventRemove>::PostRequest(event);
239 }
240
241 void Manager::find(const EventFindPtr& event)
242 {
243     EventRequestReceiver<EventFind>::PostRequest(event);
244 }
245
246 void Manager::find(const IPathPtr& path,
247         const FiltersMap& filters,
248         NodeList& result,
249         const EventFindPtr& event)
250 {
251     Try {
252         DIR* dir = opendir(path->getFullPath().c_str());
253         if (!dir) {
254             return;
255         }
256
257         errno = 0;
258         struct dirent* entry = NULL;
259         while ((entry = readdir(dir))) {
260             if (event && event->checkCancelled()) {
261                 break;
262             }
263             if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) {
264                 continue;
265             }
266             IPathPtr childPath = *path + entry->d_name;
267             struct stat info;
268             memset(&info, 0, sizeof(struct stat));
269             if (lstat(childPath->getFullPath().c_str(), &info) == 0) {
270                 if (matchFilters(entry->d_name, info, filters)) {
271                     result.push_back(Node::resolve(childPath));
272                 }
273                 if (S_ISDIR(info.st_mode)) {
274                     find(childPath, filters, result, event);
275                 }
276             }
277         }
278
279         if (errno != 0) {
280             ThrowMsg(Commons::PlatformException,
281                      "Error while reading directory.");
282         }
283
284         if (closedir(dir) != 0) {
285             ThrowMsg(Commons::PlatformException,
286                      "Could not close platform node.");
287         }
288     }
289     Catch(WrtDeviceApis::Commons::Exception) {
290     }
291 }
292
293 void Manager::copyElement(
294         const std::string &src, const std::string &dest, bool recursive) const
295 {
296     LoggerD("Copying src: " << src << " to: " << dest);
297
298     //element is a file:
299     if (EINA_TRUE != ecore_file_is_dir(src.c_str())) {
300         if (EINA_TRUE != ecore_file_cp(src.c_str(), dest.c_str())) {
301             ThrowMsg(Commons::PlatformException, "Failed to copy file");
302         }
303         return;
304     }
305     //element is a directory -> create it:
306     if (EINA_TRUE != ecore_file_mkdir(dest.c_str())) {
307         LoggerD("Failed to create destination directory");
308         ThrowMsg(Commons::PlatformException, "Failed to copy directory");
309     }
310     //copy all elements of directory:
311     if (recursive) {
312         Eina_List* list = ecore_file_ls(src.c_str());
313         void* data;
314         EINA_LIST_FREE(list, data)
315         {
316             Try
317             {
318                 copyElement((src + '/' + static_cast<char*>(data)).c_str(),
319                             (dest + '/' + static_cast<char*>(data)).c_str());
320             }
321                         
322             Catch (Commons::Exception) 
323             {
324                  //remove rest of the list
325                 EINA_LIST_FREE(list, data)
326                 {
327                     free(data);
328                 }
329                 LoggerE("Exception: " << _rethrown_exception.GetMessage());
330                 ReThrowMsg(Commons::PlatformException, "Failed to copy element");
331             }
332             free(data);
333         }
334     }
335
336 }
337
338 /*bool Manager::access(const IPathPtr& path,
339         int accessType) const
340 {
341     int amode = 0;
342     if (accessType & AT_EXISTS) { amode |= F_OK; }
343     if (accessType & AT_READ) { amode |= R_OK; }
344     if (accessType & AT_WRITE) { amode |= W_OK; }
345     if (accessType & AT_EXEC) { amode |= X_OK; }
346     return (::access(path->getFullPath().c_str(), amode) == 0);
347 }*/
348
349 long Manager::addStorageStateChangeListener(
350         const EventStorageStateChangedEmitterPtr& emitter)
351 {
352         RootList::const_iterator it = m_rootlist.begin();
353         WatcherPtr watcher(new Watcher(emitter));
354         Manager::m_watchers.push_back(watcher);
355
356         for (; it != m_rootlist.end(); ++it) {
357                 storage_set_state_changed_cb(it->second, Manager::storageStateChangedCB, (void *)(&m_watchers));
358         }
359
360         watcher->getCurrentStoargeStateForWatch();
361         return static_cast<long>(emitter->getId());
362 }
363
364 void Manager::removeStorageStateChangeListener(EventStorageStateChangedEmitter::IdType id)
365 {
366         watcherList::iterator itWatcher = Manager::m_watchers.begin();
367         bool found = false;
368         for (;itWatcher != Manager::m_watchers.end();) {
369                 if (id == (*itWatcher)->getEmitter()->getId()) {
370                         itWatcher = Manager::m_watchers.erase(itWatcher);
371                         found = true;
372                         continue;
373                 }
374                 ++itWatcher;
375         }
376
377         if (Manager::m_watchers.size() == 0) {
378                 RootList::const_iterator itRoot;
379                 for (itRoot = m_rootlist.begin(); itRoot != m_rootlist.end(); ++itRoot) {
380                         storage_unset_state_changed_cb(itRoot->second);
381                 }
382         }
383
384         if (found == false) {
385 //              LoggerD("no exist" << id);
386                 ThrowMsg(Commons::NotFoundException, "The " << id << "is not exist");
387         }
388 }
389
390 bool Manager::matchFilters(const std::string& name,
391         const struct stat& info,
392         const FiltersMap& filters)
393 {
394     FiltersMap::const_iterator it = filters.begin();
395     for (; it != filters.end(); ++it) {
396         if (it->first == FF_NAME) {
397             if (!pcrecpp::RE(it->second).PartialMatch(name)) { return false; }
398         } else if (it->first == FF_SIZE) {
399             std::size_t size;
400             std::stringstream ss(it->second);
401             ss >> size;
402             if (!ss ||
403                 (size != static_cast<size_t>(info.st_size))) { return false; }
404         } else if (it->first == FF_CREATED) {
405             std::time_t created;
406             std::stringstream ss(it->second);
407             ss >> created;
408             if (!ss || (created != info.st_ctime)) { return false; }
409         } else if (it->first == FF_MODIFIED) {
410             std::time_t modified;
411             std::stringstream ss(it->second);
412             ss >> modified;
413             if (!ss || (modified != info.st_mtime)) { return false; }
414         }
415     }
416     return true;
417 }
418
419 void Manager::OnRequestReceived(const EventResolvePtr& event)
420 {
421     try {
422         event->setResult(Node::resolve(event->getPath()));
423     }
424     catch (const Commons::Exception& ex) 
425     {
426         LoggerE("Exception: " << ex.GetMessage());
427         event->setExceptionCode(ex.getCode());
428     }
429 }
430
431 void Manager::OnRequestReceived(const EventGetStoragePtr& event)
432 {
433         try {
434
435                 StoragePropertiesPtr storage(new StorageProperties());
436
437                 RootList::const_iterator it = m_rootlist.find(event->getLabel());
438                 if (it == m_rootlist.end()) {
439                         Locations::const_iterator itL = m_locations.find(event->getLabel());
440                         if (itL == m_locations.end()) {
441                                 ThrowMsg(Commons::NotFoundException, "Base path not available.");
442                         } else {
443                                 storage->setId(0xff);
444                                 storage->setLabel(event->getLabel());
445                                 storage->setType(StorageProperties::TYPE_INTERNAL);
446                                 storage->setState(StorageProperties::STATE_MOUNTED);
447                         }
448                 } else {
449                         int id = it->second;
450
451                         storage_type_e currentType;
452                         storage_state_e currentState;
453
454                         storage_get_type(id, &currentType);
455                         storage_get_state(id, &currentState);
456
457                         storage->setId(id);
458                         storage->setLabel(event->getLabel());
459                         storage->setType((short)currentType);
460                         storage->setState((short)currentState);
461                 }
462
463                 event->setResult(storage);
464     } catch (const Commons::Exception& ex) 
465     {
466         event->setExceptionCode(ex.getCode());
467     }
468 }
469
470 void Manager::OnRequestReceived(const EventListStoragesPtr& event)
471 {
472         try {
473                 std::vector<StoragePropertiesPtr> storageList;
474                         
475                 storage_foreach_device_supported(Manager::getSupportedDeviceCB, &storageList);
476
477                 SubRootList::const_iterator it = m_subrootlist.begin();
478                 for (; it != m_subrootlist.end(); ++it) {
479                         if (it->first == LT_ROOT) 
480                                 continue;
481                         if (it->first == LT_SDCARD) 
482                                 continue;
483                         if (it->first == LT_USBHOST) 
484                                 continue;                       
485
486                         addLocalStorage(it->second, storageList);
487                 }
488                 
489
490                 event->setResult(storageList);
491     }   catch (const Commons::Exception& ex) 
492     {
493         event->setExceptionCode(ex.getCode());
494     }
495 }
496
497 void Manager::OnRequestReceived(const EventCopyPtr& event)
498 {
499     Try {
500         INodePtr srcNode = Node::resolve(event->getSource());
501                 LoggerD(std::hex << srcNode->getMode() << " " << std::hex << PM_USER_READ);
502         if ((srcNode->getMode() & PM_USER_READ/*PERM_READ*/) == 0) {
503             ThrowMsg(Commons::SecurityException,
504                      "Not enough permissions to read source node.");
505         }
506
507         IPathPtr src = event->getSource();
508         IPathPtr dest = event->getDestination();
509         if (!dest->isAbsolute()) {
510             dest = src->getPath() + *dest;
511         }
512   
513         INodePtr parent;
514         Try {
515             parent = Node::resolve(IPath::create(dest->getPath()));
516         }
517         Catch(Commons::NotFoundException) 
518         {
519             event->setExceptionCode(_rethrown_exception.getCode());
520             ReThrowMsg(Commons::NotFoundException, "could not find a destination path.");
521         }
522         Catch (Commons::Exception) 
523         {
524             event->setExceptionCode(_rethrown_exception.getCode());
525             ReThrowMsg(Commons::PlatformException,
526                        "Could not get destination's parent node.");
527         }
528
529         if (parent->getType() != NT_DIRECTORY) {
530             ThrowMsg(Commons::PlatformException,
531                      "Destination's parent node is not directory.");
532         }
533
534                 std::string realSrc = src->getFullPath();
535                 std::string realDest = dest->getFullPath();
536
537                 if (realSrc == realDest) {
538                         ThrowMsg(Commons::PlatformException,
539                         "Destination is same as source.");
540                 }
541                 
542
543         errno = 0;
544         struct stat info;
545         memset(&info, 0, sizeof(struct stat));
546         int status = lstat(realDest.c_str(), &info);
547         if ((status != 0) && (errno != ENOENT)) {
548             ThrowMsg(Commons::PlatformException,
549                      "No access to platform destination node.");
550         }
551                 
552         if (S_ISDIR(info.st_mode) && srcNode->getType() == NT_FILE) {
553             dest->append("/" + src->getName());
554             realDest = dest->getFullPath();
555             memset(&info, 0, sizeof(struct stat));
556             status = lstat(realDest.c_str(), &info);
557             if ((status != 0) && (errno != ENOENT)) {
558                 ThrowMsg(Commons::PlatformException,
559                              "No access to platform destination node.");
560             }
561         }
562
563         if (0 == status) {
564             //no owerwrite flag setted -> exception
565             if ((event->getOptions() & OPT_OVERWRITE) == 0) {
566                 ThrowMsg(Commons::PlatformException, "Overwrite is not set.");
567             }
568
569             if (event->checkCancelled()) {
570                 //file is not copied yet, so we can cancel it now.
571                 event->setCancelAllowed(true);
572                 return;
573             }
574
575             //destination exist. Need to be removed
576             Try {
577                 INodePtr node = Node::resolve(dest);
578                 node->remove(event->getOptions());
579             }
580             catch (const Commons::Exception& ex) 
581             {
582                 LoggerE("Exception: " << ex.GetMessage());
583                 event->setExceptionCode(ex.getCode());
584              }
585         }
586         //Destination is not exist. Start copy now.
587                 LoggerD(dest->getFullPath().c_str());
588         copyElement(realSrc, realDest);
589
590         event->setResult(Node::resolve(dest));
591     }
592     catch (const Commons::Exception& ex) 
593     {
594         LoggerE("Exception: " << ex.GetMessage());
595         event->setExceptionCode(ex.getCode());
596     }
597     //file is copied already so we don't allow cancelling anymore.
598     event->setCancelAllowed(false);
599 }
600
601 void Manager::OnRequestReceived(const EventMovePtr& event)
602 {
603     try {
604         IPathPtr src = event->getSource();
605         IPathPtr dest = event->getDestination();
606
607         INodePtr srcNode = Node::resolve(src);
608                 LoggerD(std::hex << srcNode->getMode() << " " << std::hex << PM_USER_WRITE);
609         if ((srcNode->getMode() & PM_USER_WRITE/*PERM_WRITE*/) == 0)
610         {
611             ThrowMsg(Commons::SecurityException,
612                      "Not enough permissions to move source node.");
613         }
614
615         if (!dest->isAbsolute()) {
616             dest = src->getPath() + *dest;
617         }
618
619         if (src == dest) {
620             ThrowMsg(Commons::PlatformException,
621                      "Destination is same as source.");
622         }
623
624         INodePtr parent;
625         Try {
626             parent = Node::resolve(IPath::create(dest->getPath()));
627         }
628                 
629         Catch(Commons::NotFoundException) 
630         {
631             event->setExceptionCode(_rethrown_exception.getCode());
632             ReThrowMsg(Commons::NotFoundException, "could not find a destination path.");
633         }
634         Catch(Commons::Exception) 
635         {
636             LoggerE("Exception: " << _rethrown_exception.GetMessage());
637             ReThrowMsg(Commons::PlatformException,
638                        "Could not get destination's parent node.");
639         }
640
641         if (parent->getType() != NT_DIRECTORY) {
642             ThrowMsg(Commons::PlatformException,
643                      "Destination's parent node is not directory.");
644         }
645
646         errno = 0;
647         struct stat info;
648         memset(&info, 0, sizeof(info));
649         int status = lstat(dest->getFullPath().c_str(), &info);
650         if ((status != 0) && (errno != ENOENT)) {
651             ThrowMsg(Commons::PlatformException,
652                      "No access to platform destination node.");
653         }
654
655         LoggerD(dest->getFullPath().c_str());
656                 
657         if (S_ISDIR(info.st_mode) && srcNode->getType() == NT_FILE) {
658                         dest->append("/" + src->getName());
659                         memset(&info, 0, sizeof(info));
660                         status = lstat(dest->getFullPath().c_str(), &info);
661                         if ((status != 0) && (errno != ENOENT)) {
662                     ThrowMsg(Commons::PlatformException,
663                             "No access to platform destination node.");
664                         }
665         } 
666
667                 if (status == 0 && 0 == (event->getOptions() & OPT_OVERWRITE)) {
668             ThrowMsg(Commons::PlatformException, "Overwrite is not set.");
669         }
670
671         if (event->checkCancelled()) {
672             //file is not moved yet, so we can cancel it now.
673             event->setCancelAllowed(true);
674             return;
675         }
676
677         errno = 0;
678         
679         LoggerD(dest->getFullPath().c_str());
680                 
681         if (0 != ::rename(src->getFullPath().c_str(), dest->getFullPath().c_str()))
682         {
683             int error = errno;
684             switch (error)
685             {
686             case EXDEV:
687                 {
688                                         LoggerD(std::hex << srcNode->getMode() << " " << std::hex << PM_USER_READ);
689                     if ((srcNode->getMode() & PM_USER_READ /*PERM_READ*/) == 0)
690                     {
691                         ThrowMsg(Commons::SecurityException,
692                                  "Not enough permissions to move source node.");
693                     }
694                     if (0 == status) {
695                         //destination exist. Need to be removed
696                         Try {
697                             INodePtr node = Node::resolve(dest);
698                             node->remove(event->getOptions());
699                         }
700                         catch (const Commons::Exception& ex) 
701                         {
702                             LoggerE("Exception: " << ex.GetMessage());
703                             event->setExceptionCode(ex.getCode());
704                             LoggerE("Exception while removing dest directory");
705                         }
706                     }
707
708                     copyElement(src->getFullPath(),
709                                 dest->getFullPath());
710                     //remove source files
711                     Try {
712                         INodePtr node = Node::resolve(event->getSource());
713                         node->remove(event->getOptions());
714                     }
715                     Catch(Commons::Exception) {
716                         LoggerE("Exception: "
717                                  << _rethrown_exception.GetMessage());
718                     }
719                     break;
720                 }
721             default:
722                                 // needtofix
723                 ThrowMsg(Commons::PlatformException,
724                          "Error on rename: " /*<< DPL::GetErrnoString(error)*/);
725                 break;
726             }
727         }
728
729         event->setResult(Node::resolve(dest));
730     }
731     catch (const Commons::Exception& ex) 
732     {
733         LoggerE("Exception: " << ex.GetMessage());
734         event->setExceptionCode(ex.getCode());
735     }
736
737     event->setCancelAllowed(false);
738 }
739
740 void Manager::OnRequestReceived(const EventCreatePtr& event)
741 {
742     Try {
743     }
744     catch (const Commons::Exception& ex) 
745     {
746         LoggerE("Exception: " << ex.GetMessage());
747         event->setExceptionCode(ex.getCode());
748     }
749 }
750
751 void Manager::OnRequestReceived(const EventRemovePtr& event)
752 {
753     if (!event->checkCancelled()) {
754         Try {
755             INodePtr node = Node::resolve(event->getPath());
756             node->remove(event->getOptions());
757         }
758         catch (const Commons::Exception& ex) 
759         {
760             LoggerE("Exception: " << ex.GetMessage());
761             event->setExceptionCode(ex.getCode());
762         }
763         event->setCancelAllowed(false);
764     } else {
765         event->setCancelAllowed(true);
766     }
767 }
768
769 void Manager::OnRequestReceived(const EventFindPtr& event)
770 {
771     try {
772         NodeList result;
773         find(event->getPath(), event->getFilters(), result, event);
774         event->setResult(result);
775     }
776     catch (const Commons::Exception& ex) {
777         LoggerE("Exception: " << ex.GetMessage());
778         event->setExceptionCode(Commons::ExceptionCodes::PlatformException);
779     }
780     event->setCancelAllowed(true);
781 }
782
783 void Manager::addLocalStorage(std::string label, std::vector<StoragePropertiesPtr> &storageList)
784 {
785         StoragePropertiesPtr storage(new StorageProperties());
786         storage->setId(0xff);
787         storage->setLabel(label);
788         storage->setType(StorageProperties::TYPE_INTERNAL);
789
790         storage_state_e currentState;
791         storage_get_state(0, &currentState);
792         storage->setState((short)currentState);
793
794         storageList.insert(storageList.end(), storage);
795 }
796
797 void Manager::addWidgetStorage(const std::string &key, const std::string &value)
798 {
799         setupLocation(key, value.c_str());
800
801         if (key == "wgt-package")
802         {
803                 m_subrootlist[LT_WGTPKG] = key;
804         }
805         else if (key == "wgt-private")
806         {
807                 m_subrootlist[LT_WGTPRV] = key;
808         }
809         else if (key == "wgt-private-tmp")
810         {
811                 m_subrootlist[LT_WGTPRVTMP] = key;
812         }
813 }
814
815 bool Manager::init()
816 {
817         std::vector<StoragePropertiesPtr> storageList;
818         storage_foreach_device_supported(Manager::getSupportedDeviceCB, &storageList);
819
820         for (size_t i = 0; i < storageList.size(); i++) {
821                 m_locations[storageList[i]->getLabel()] = IPath::create(storageList[i]->getFullPath());
822                 m_rootlist[storageList[i]->getLabel()] = storageList[i]->getId();
823         }
824
825         /* for Tizen */
826         setupLocation("downloads", PATH_DOWNLOADS);
827         setupLocation("documents", PATH_DOCUMENTS);
828         setupLocation("music", PATH_SOUNDS);
829         setupLocation("images", PATH_IMAGES);
830         setupLocation("videos", PATH_VIDEOS);
831         setupLocation("ringtones", PATH_RINGTONE);
832
833         m_subrootlist[LT_ROOT] = "internal0";
834         m_subrootlist[LT_SDCARD] = "removable1";
835         m_subrootlist[LT_USBHOST] = "removable2";
836         m_subrootlist[LT_DOWNLOADS] = "downloads";
837         m_subrootlist[LT_DOCUMENTS] = "documents";
838         m_subrootlist[LT_SOUNDS] = "music";
839         m_subrootlist[LT_IMAGES] = "images";
840         m_subrootlist[LT_VIDEOS] = "videos";
841         m_subrootlist[LT_RINGTONES] = "ringtones";
842         return true;
843
844 }
845
846 void Manager::setupLocation(std::string location, const char* path)
847 {
848     if (!nodeExists(path)) {
849         try {
850             makePath(path, 0755);
851         }
852         catch (const Commons::Exception& ex) 
853         {
854             LoggerE("Exception: " << ex.GetMessage());
855             return;
856         }
857     }
858     m_locations[location] = IPath::create(path);
859 }
860
861 void Manager::Watcher::getCurrentStoargeStateForWatch()
862 {
863         std::string label("");
864         storage_type_e type;
865         storage_state_e state;
866         RootList::const_iterator it = m_rootlist.begin();
867         for (; it != m_rootlist.end(); ++it) {
868                 label = it->first;
869                 if (label.compare("") != 0) {
870                         StoragePropertiesPtr storageItem(new StorageProperties());
871
872                         if (storage_get_type(it->second, &type) != STORAGE_ERROR_NONE) {
873                                 Throw(Commons::PlatformException);
874                         }
875                         if (storage_get_state(it->second, &state) != STORAGE_ERROR_NONE) {
876                                 Throw(Commons::PlatformException);
877                         }
878
879                         storageItem->setId(it->second);
880                         storageItem->setLabel(it->first);
881                         storageItem->setType(static_cast<short>(type));
882                         storageItem->setState(static_cast<short>(state));
883
884                         EventStorageStateChangedPtr event(new EventStorageStateChanged());
885
886                         event->setResult(storageItem);
887                         emit(event);
888                 }
889         }
890 }
891
892 void Manager::Watcher::StorageStateHasChanged(int storage, storage_state_e state)
893 {
894         StoragePropertiesPtr storageItem(new StorageProperties());
895
896         std::string label;
897         storage_type_e type;
898
899         RootList::const_iterator it = m_rootlist.begin();
900         for (; it != m_rootlist.end(); ++it) {
901                 if (it->second == storage) {
902                         label = it->first;
903                         break;
904                 }
905         }
906
907         if (storage_get_type(storage, &type) != STORAGE_ERROR_NONE) {
908                 Throw(Commons::PlatformException);
909         }
910
911         if (label.compare("") != 0) {
912                 storageItem->setId(storage);
913                 storageItem->setLabel(label);
914                 storageItem->setType(static_cast<short>(type));
915                 storageItem->setState(static_cast<short>(state));
916
917                 EventStorageStateChangedPtr event(new EventStorageStateChanged());
918
919                 event->setResult(storageItem);
920                 emit(event);
921         }
922 }
923
924 }
925 }