From e4155db2165c1f5eb1fff29ce67e98ead4f5c077 Mon Sep 17 00:00:00 2001 From: Lukasz Foniok Date: Sun, 13 Dec 2015 18:39:33 +0100 Subject: [PATCH] [Common] Small filesystem refactoring [Verification] account 100% alarm 100% appcontrol 100% application 100% archive 100% badge 100% bookmark 100% calendar 100% callhistory 100% contact 100% content 100% datacontrol 100% download 100% exif 100% filesystem 100% humanactivitymonitor 100% inputdevice 100% mediacontroller 100% mediakey 100% messageport 100% messaging-sms 100% messaging-mms 100% namespace 100% networkbearerselection 100% nfc 100% notification 100% package 100% power 100% privilege 100% push 100% secureelement 100% sensor 100% sound 100% systeminfo 100% systemsetting 100% tizen 100% websetting 100% messaging-email 100% Change-Id: Ibb36f536270c82f8e98e4ade207aa354ffab2ec5 Signed-off-by: Lukasz Foniok --- src/archive/archive_instance.cc | 4 +- src/common/common.gyp | 10 +- src/common/current_application.cc | 68 +++- src/common/current_application.h | 3 + .../filesystem/filesystem_provider_storage.cc | 223 ++++++++++++ .../filesystem/filesystem_provider_storage.h | 58 +++ .../filesystem/filesystem_provider_types.h | 20 ++ src/common/filesystem/filesystem_storage.cc | 114 ++++++ src/common/filesystem/filesystem_storage.h | 92 +++++ src/common/virtual_fs.cc | 330 ------------------ src/common/virtual_fs.h | 91 ----- src/content/content_instance.cc | 4 +- src/content/content_manager.cc | 6 +- src/download/download_instance.cc | 7 +- src/filesystem/filesystem_instance.cc | 8 +- src/filesystem/filesystem_instance.h | 5 +- src/filesystem/filesystem_manager.cc | 171 ++++----- src/filesystem/filesystem_manager.h | 26 +- src/filesystem/js/common.js | 51 ++- src/messaging/message.cc | 6 +- src/messaging/message_attachment.cc | 4 +- src/notification/status_notification.cc | 23 +- src/systemsetting/systemsetting_instance.cc | 4 +- 23 files changed, 724 insertions(+), 604 deletions(-) create mode 100644 src/common/filesystem/filesystem_provider_storage.cc create mode 100644 src/common/filesystem/filesystem_provider_storage.h create mode 100644 src/common/filesystem/filesystem_provider_types.h create mode 100644 src/common/filesystem/filesystem_storage.cc create mode 100644 src/common/filesystem/filesystem_storage.h delete mode 100755 src/common/virtual_fs.cc delete mode 100755 src/common/virtual_fs.h diff --git a/src/archive/archive_instance.cc b/src/archive/archive_instance.cc index c9e621d3..30ec005e 100755 --- a/src/archive/archive_instance.cc +++ b/src/archive/archive_instance.cc @@ -24,7 +24,7 @@ #include "common/current_application.h" #include "common/picojson.h" #include "common/logger.h" -#include "common/virtual_fs.h" +#include "common/filesystem/filesystem_provider_storage.h" #include "common/tools.h" #include "archive_callback_data.h" #include "archive_manager.h" @@ -620,7 +620,7 @@ void ArchiveInstance::FetchVirtualRoots(const picojson::value& args, picojson::o LoggerD("Entered"); picojson::array roots; - for (const auto& root : common::VirtualFs::GetInstance().GetVirtualRoots()) { + for (const auto& root : common::FilesystemProviderStorage::Create().GetVirtualPaths() ) { roots.push_back(root.ToJson()); } ReportSuccess(picojson::value(roots), out); diff --git a/src/common/common.gyp b/src/common/common.gyp index 1dad003a..bba10751 100644 --- a/src/common/common.gyp +++ b/src/common/common.gyp @@ -38,8 +38,6 @@ 'platform_result.cc', 'platform_result.h', 'assert.h', - 'virtual_fs.cc', - 'virtual_fs.h', 'GDBus/connection.cpp', 'GDBus/connection.h', 'GDBus/proxy.cpp', @@ -47,8 +45,12 @@ 'GDBus/gdbus_powerwrapper.cc', 'GDBus/gdbus_powerwrapper.h', 'GDBus/auto_gen_interface.c', - 'GDBus/auto_gen_interface.h' - + 'GDBus/auto_gen_interface.h', + 'filesystem/filesystem_storage_types.h', + 'filesystem/filesystem_storage.h', + 'filesystem/filesystem_storage.cc', + 'filesystem/filesystem_provider_storage.h', + 'filesystem/filesystem_provider_storage.cc', ], 'cflags': [ '-fvisibility=default', diff --git a/src/common/current_application.cc b/src/common/current_application.cc index 85910ccf..4f76330e 100755 --- a/src/common/current_application.cc +++ b/src/common/current_application.cc @@ -21,6 +21,7 @@ #include #include "common/logger.h" +#include "common/scope_exit.h" namespace common { @@ -45,10 +46,16 @@ std::string CurrentApplication::GetPackageId() const { return package_id_; } +std::string CurrentApplication::GetRoot() const { + LoggerD("Enter"); + return root_; +} + CurrentApplication::CurrentApplication() : pid_(getpid()), app_id_(FetchApplicationId()), - package_id_(FetchPackageId()) { + package_id_(FetchPackageId()), + root_(FetchRoot()) { LoggerD("Enter"); } @@ -73,20 +80,61 @@ std::string CurrentApplication::FetchApplicationId() const { std::string CurrentApplication::FetchPackageId() const { LoggerD("Enter"); std::string package_id; - char* tmp_str = nullptr; - - const int ret = package_manager_get_package_id_by_app_id(app_id_.c_str(), - &tmp_str); - - if ((PACKAGE_MANAGER_ERROR_NONE == ret) && (nullptr != tmp_str)) { - package_id = tmp_str; + app_info_h app_info; + int err = app_info_create(app_id_.c_str(), &app_info); + if (APP_MANAGER_ERROR_NONE != err) { + LoggerE("Can't create app info handle from appId %s: %d (%s)", + app_id_.c_str(), err, get_error_message(err)); + return std::string(); + } + SCOPE_EXIT { + app_info_destroy(app_info); + }; + + char* package = nullptr; + err = app_info_get_package(app_info, &package); + if (APP_MANAGER_ERROR_NONE != err) { + LoggerE("Can't get package name from app info: %d (%s)", err, + get_error_message(err)); } else { - LoggerE("Can't get package name from app info: %d (%s)", ret, get_error_message(ret)); + package_id = package; } - free(tmp_str); + free(package); return package_id; } +std::string CurrentApplication::FetchRoot() const { + LoggerD("Enter"); + + if(package_id_.empty()) { + LoggerE("Can't get package id, no root path can be obtained"); + return std::string(); + } + + package_info_h pkg_info; + int err = package_info_create(package_id_.c_str(), &pkg_info); + if (PACKAGE_MANAGER_ERROR_NONE != err) { + LoggerE("Can't create package info handle from pkg (%s)", get_error_message(err)); + return std::string(); + } + SCOPE_EXIT { + package_info_destroy(pkg_info); + }; + + char* root = nullptr; + err = package_info_get_root_path(pkg_info, &root); + if (PACKAGE_MANAGER_ERROR_NONE != err || nullptr == root) { + LoggerE("Can't get root_ path from package info (%s)", get_error_message(err)); + return std::string(); + } + + std::string ret(root); + free(root); + + LoggerD("Exit"); + return ret; +} + } // namespace common diff --git a/src/common/current_application.h b/src/common/current_application.h index 68135e60..96658814 100755 --- a/src/common/current_application.h +++ b/src/common/current_application.h @@ -30,16 +30,19 @@ class CurrentApplication { pid_t GetProcessId() const; std::string GetApplicationId() const; std::string GetPackageId() const; + std::string GetRoot() const; private: CurrentApplication(); std::string FetchApplicationId() const; std::string FetchPackageId() const; + std::string FetchRoot() const; private: pid_t pid_; std::string app_id_; std::string package_id_; + std::string root_; }; } // namespace common diff --git a/src/common/filesystem/filesystem_provider_storage.cc b/src/common/filesystem/filesystem_provider_storage.cc new file mode 100644 index 00000000..74108863 --- /dev/null +++ b/src/common/filesystem/filesystem_provider_storage.cc @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "common/filesystem/filesystem_provider_storage.h" +#include +#include +#include +#include "common/logger.h" +#include "common/current_application.h" + +namespace { + +const std::string kVirtualRootCamera = "camera"; +const std::string kVirtualRootDocuments = "documents"; +const std::string kVirtualRootDownloads = "downloads"; +const std::string kVirtualRootImages = "images"; +const std::string kVirtualRootMusic = "music"; +const std::string kVirtualRootRingtones = "ringtones"; +const std::string kVirtualRootVideos = "videos"; +const std::string kVirtualRootWgtPackage = "wgt-package"; +const std::string kVirtualRootWgtPrivate = "wgt-private"; +const std::string kVirtualRootWgtPrivateTmp = "wgt-private-tmp"; + +const std::map kStorageDirectories = { + { STORAGE_DIRECTORY_CAMERA, &kVirtualRootCamera }, { + STORAGE_DIRECTORY_DOCUMENTS, &kVirtualRootDocuments }, { + STORAGE_DIRECTORY_DOWNLOADS, &kVirtualRootDownloads }, { + STORAGE_DIRECTORY_IMAGES, &kVirtualRootImages }, { + STORAGE_DIRECTORY_MUSIC, &kVirtualRootMusic }, { + STORAGE_DIRECTORY_SYSTEM_RINGTONES, &kVirtualRootRingtones }, { + STORAGE_DIRECTORY_VIDEOS, &kVirtualRootVideos } }; + +const std::string kFileUriPrefix = "file://"; + +} // namespace + +namespace common { + +StorageState TranslateCoreStorageState( + storage_state_e coreStorageState) { + StorageState state = StorageState::kUnknown; + if (coreStorageState == STORAGE_STATE_REMOVED) { + state = StorageState::kUnmounted; + } else if (coreStorageState == STORAGE_STATE_MOUNTED + || coreStorageState == STORAGE_STATE_MOUNTED_READ_ONLY) { + state = StorageState::kMounted; + } else { + state = StorageState::kUnmountable; + } + + return state; +} + +void OnStorageChange(int storage_id, storage_state_e state, void* user_data) { + LoggerD("Entered, id: %d", storage_id); + + FilesystemProviderStorage* provider = + static_cast(user_data); + for (auto &storage : provider->GetStorages()) { + if (storage.id_ == storage_id) { + StorageState previous_state = storage.state_; + storage.state_ = TranslateCoreStorageState(state); + if (provider->GetListener()) { + provider->GetListener()(storage, previous_state, storage.state_); + } + break; + } + } +} + +bool OnForeachStorage(int storage_id, storage_type_e type, + storage_state_e state, const char* path, + void* user_data) { + LoggerD("Entered, id: %d", storage_id); + FilesystemProviderStorage* provider = + static_cast(user_data); + + int err = storage_set_state_changed_cb(storage_id, OnStorageChange, provider); + if (STORAGE_ERROR_NONE != err) { + LoggerW("Failed to add listener"); + } + + StorageType type_ = + type == STORAGE_TYPE_INTERNAL ? + StorageType::kInternal : StorageType::kExternal; + + provider->GetStorages().push_back( + Storage(storage_id, type_, TranslateCoreStorageState(state), path)); + if (type_ == StorageType::kInternal) { + // if internal storage is supported, we can add also virtual paths: + // downloads, documents etc + provider->FillVirtualPaths(storage_id); + } + return true; +} + +DeviceChangeStateFun FilesystemProviderStorage::GetListener() { + return listener_; +} + +FilesystemProviderStorage::FilesystemProviderStorage() { + LoggerD("Entered"); + int err = storage_foreach_device_supported(OnForeachStorage, this); + if (err != STORAGE_ERROR_NONE) { + LoggerE("Unknown Error on getting storage paths"); + } +} + +FilesystemProviderStorage& FilesystemProviderStorage::Create() { + static FilesystemProviderStorage fs; + return fs; +} + +FilesystemProviderStorage::~FilesystemProviderStorage() { +} + +void FilesystemProviderStorage::FillVirtualPaths(int storage_id) { + LoggerD("Creating virtual paths for storage: %d", storage_id); + for (auto& item : kStorageDirectories) { + char* dir_path = nullptr; + storage_directory_e dir_enum = item.first; + int err = storage_get_directory(storage_id, dir_enum, &dir_path); + if (STORAGE_ERROR_NONE == err && nullptr != dir_path) { + virtual_paths_.push_back(VirtualRoot(*(item.second), dir_path)); + free(dir_path); + } + } + + // fill also virtual paths based on current application install dir + std::string root = common::CurrentApplication::GetInstance().GetRoot(); + if (!root.empty()) { + virtual_paths_.push_back( + VirtualRoot(kVirtualRootWgtPackage, root + "/res/wgt")); + virtual_paths_.push_back( + VirtualRoot(kVirtualRootWgtPrivate, root + "/data")); + virtual_paths_.push_back( + VirtualRoot(kVirtualRootWgtPrivateTmp, root + "/tmp")); + } +} + +void FilesystemProviderStorage::RegisterDeviceChangeState( + DeviceChangeStateFun callback) { + LoggerD("Entered"); + listener_ = callback; +} + +void FilesystemProviderStorage::UnregisterDeviceChangeState() { + LoggerD("Entered"); + listener_ = nullptr; +} + +Storages FilesystemProviderStorage::GetStorages() { + return storages_; +} + +VirtualRoots FilesystemProviderStorage::GetVirtualPaths() { + return virtual_paths_; +} + +std::string FilesystemProviderStorage::GetRealPath( + const std::string& path_or_uri) { + LoggerD("Enter"); + std::string realpath; + std::size_t pos = path_or_uri.find(kFileUriPrefix); + if (pos != std::string::npos) { + realpath = path_or_uri.substr(pos + kFileUriPrefix.size()); + } else { + realpath = path_or_uri; + } + pos = realpath.find('/'); + if (pos != 0) { + const std::string prefix = realpath.substr(0, pos); + const auto it = std::find_if(virtual_paths_.begin(), virtual_paths_.end(), + [prefix](const common::VirtualRoot & vr) { + return vr.name_ == prefix; + }); + if (it != virtual_paths_.end()) { + realpath.replace(0, prefix.size(), it->path_); + } else { + LoggerE("Unknown virtual root"); + } + } + return realpath; +} + +std::string FilesystemProviderStorage::GetVirtualPath( + const std::string& real_path) const { + LoggerD("Enter"); + for (const auto& kv : virtual_paths_) { + if (0 == real_path.compare(0, kv.path_.size(), kv.path_)) { + return std::string(real_path).replace(0, kv.path_.size(), kv.name_); + } + } + return real_path; +} + +VirtualStorages FilesystemProviderStorage::GetAllStorages() { + VirtualStorages vs; + for (auto storage : storages_) { + vs.push_back(std::make_shared < Storage > (storage)); + } + + for (auto virtualRoot : virtual_paths_) { + vs.push_back(std::make_shared < VirtualRoot > (virtualRoot)); + } + + return vs; +} + +} // namespace common diff --git a/src/common/filesystem/filesystem_provider_storage.h b/src/common/filesystem/filesystem_provider_storage.h new file mode 100644 index 00000000..a486a5d1 --- /dev/null +++ b/src/common/filesystem/filesystem_provider_storage.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef COMMON_FILESYSTEM_FILESYSTEM_PROVIDER_STORAGE_H_ +#define COMMON_FILESYSTEM_FILESYSTEM_PROVIDER_STORAGE_H_ + +#include +#include +#include "common/filesystem/filesystem_provider_types.h" + +namespace common { + +class FilesystemProviderStorage { + public: + static FilesystemProviderStorage& Create(); + virtual ~FilesystemProviderStorage(); + + virtual void RegisterDeviceChangeState(DeviceChangeStateFun callback); + virtual void UnregisterDeviceChangeState(); + + virtual Storages GetStorages(); + virtual VirtualRoots GetVirtualPaths(); + virtual VirtualStorages GetAllStorages(); + + std::string GetRealPath(const std::string& path_or_uri); + std::string GetVirtualPath(const std::string& real_path) const; + + DeviceChangeStateFun GetListener(); + void FillVirtualPaths(int storage_id); + + private: + FilesystemProviderStorage(); + /** + * For given storage_id try to get paths for virtual paths. + * For example for storage_id (which has type INTERNAL) it will + * add to storages virtual paths: downloads with real path /opt/usr/media/Downloads + */ + DeviceChangeStateFun listener_; + Storages storages_; + VirtualRoots virtual_paths_; +}; + +} // namespace common + +#endif // COMMON_FILESYSTEM_FILESYSTEM_PROVIDER_STORAGE_H_ diff --git a/src/common/filesystem/filesystem_provider_types.h b/src/common/filesystem/filesystem_provider_types.h new file mode 100644 index 00000000..cb0695be --- /dev/null +++ b/src/common/filesystem/filesystem_provider_types.h @@ -0,0 +1,20 @@ +#ifndef COMMON_FILESYSTEM_FILESYSTEM_PROVIDER_TYPES_H_ +#define COMMON_FILESYSTEM_FILESYSTEM_PROVIDER_TYPES_H_ + +#include +#include +#include +#include "common/filesystem/filesystem_storage.h" + +namespace common { + +typedef std::function< + void(common::Storage, common::StorageState, + common::StorageState)> DeviceChangeStateFun; +typedef std::vector Storages; +typedef std::vector VirtualRoots; +typedef std::vector > VirtualStorages; + +} // namespace common + +#endif // COMMON_FILESYSTEM_FILESYSTEM_PROVIDER_TYPES_H_ \ No newline at end of file diff --git a/src/common/filesystem/filesystem_storage.cc b/src/common/filesystem/filesystem_storage.cc new file mode 100644 index 00000000..3d737a1d --- /dev/null +++ b/src/common/filesystem/filesystem_storage.cc @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "common/filesystem/filesystem_storage.h" +#include +#include "common/logger.h" + +namespace common { + +VirtualRoot::VirtualRoot(std::string const& name, std::string const& path, + StorageType type, StorageState state) + : name_(name), + path_(path), + type_(type), + state_(state) { +} + +Storage::Storage(int id, StorageType type, StorageState state, + std::string const& path, std::string const& name) + : VirtualRoot(name, path, type, state), + id_(id) { + LoggerD("Enter"); + if (name_ == "") { + switch (type) { + case StorageType::kInternal: + name_ = "internal"; + break; + + case StorageType::kExternal: + name_ = "removable"; + break; + + default: + name_ = "unknown"; + LoggerE("Unknown storage type: %d", type); + break; + } + name_ += std::to_string(id); + } +} + +picojson::value VirtualRoot::ToJson() const { + picojson::value v { picojson::object { } }; + picojson::object& obj = v.get(); + + obj["type"] = picojson::value(ToString(type_)); + obj["state"] = picojson::value(ToString(state_)); + obj["path"] = picojson::value(path_); + obj["name"] = picojson::value(name_); + + return v; +} + +picojson::value Storage::ToJson() const { + picojson::value value = VirtualRoot::ToJson(); + picojson::object& obj = value.get(); + obj["storage_id"] = picojson::value(static_cast(id_)); + return value; +} + +Storage::Storage(Storage const& other) + : VirtualRoot(other) { + this->id_ = other.id_; +} + +VirtualRoot::VirtualRoot(VirtualRoot const& other) { + this->path_ = other.path_; + this->name_ = other.name_; + this->state_ = other.state_; + this->type_ = other.type_; +} + +std::string VirtualRoot::ToString(StorageType type) { + switch (type) { + case StorageType::kInternal: + return "INTERNAL"; + + case StorageType::kExternal: + return "EXTERNAL"; + + default: + LoggerE("Unknown storage type: %d", type); + return "UNKNOWN"; + } +} + +std::string VirtualRoot::ToString(StorageState state) { + switch (state) { + case StorageState::kUnmounted: + return "REMOVED"; + case StorageState::kUnmountable: + return "UNMOUNTABLE"; + case StorageState::kMounted: + return "MOUNTED"; + default: + LoggerE("Unknown storage state: %d", state); + return "UNKNOWN"; + } +} + +} // namespace common diff --git a/src/common/filesystem/filesystem_storage.h b/src/common/filesystem/filesystem_storage.h new file mode 100644 index 00000000..6f67388a --- /dev/null +++ b/src/common/filesystem/filesystem_storage.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef COMMON_FILESYSTEM_STORAGE_H_ +#define COMMON_FILESYSTEM_STORAGE_H_ + +#include +#include "common/picojson.h" + +namespace common { + +enum class StorageState { + kMounted, + kUnmounted, + kUnmountable, + kUnknown +}; + +enum class StorageType { + kInternal, + kExternal +}; + +class VirtualStorage { + public: + virtual picojson::value ToJson() const = 0; + virtual ~VirtualStorage() { + } + + virtual std::string path() const = 0; + virtual std::string name() const = 0; + virtual StorageType type() const = 0; + virtual StorageState state() const = 0; +}; + +class VirtualRoot : public VirtualStorage { + public: + VirtualRoot(std::string const& name, std::string const & path, + StorageType type = StorageType::kInternal, StorageState state = StorageState::kMounted); + VirtualRoot(VirtualRoot const& other); + + std::string name_; + std::string path_; + StorageType type_; + StorageState state_; + virtual picojson::value ToJson() const; + virtual std::string path() const{ + return path_; + } + virtual std::string name() const { + return name_; + } + virtual StorageType type() const{ + return type_; + } + virtual StorageState state() const{ + return state_; + } + + static std::string ToString(StorageType type); + static std::string ToString(StorageState state); +}; + +class Storage : public VirtualRoot { + public: + virtual ~Storage() { + } + + Storage(int id, StorageType type, StorageState state, + std::string const& path = "", std::string const& name = ""); + Storage(Storage const& other); + + int id_; + virtual picojson::value ToJson() const; +}; + +} // namespace common + +#endif // COMMON_FILESYSTEM_STORAGE_H_ diff --git a/src/common/virtual_fs.cc b/src/common/virtual_fs.cc deleted file mode 100755 index 01991b1f..00000000 --- a/src/common/virtual_fs.cc +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright (c) 2014 Intel Corporation. All rights reserved. -// Copyright 2015 Samsung Electronics Co, Ltd. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "common/virtual_fs.h" - -#include - -#include -#include - -#include "common/extension.h" -#include "common/logger.h" -#include "common/optional.h" -#include "common/scope_exit.h" -#include "common/current_application.h" - -namespace { - -const std::string kVirtualRootCamera = "camera"; -const std::string kVirtualRootDocuments = "documents"; -const std::string kVirtualRootDownloads = "downloads"; -const std::string kVirtualRootImages = "images"; -const std::string kVirtualRootMusic = "music"; -const std::string kVirtualRootRingtones = "ringtones"; -const std::string kVirtualRootVideos = "videos"; -const std::string kVirtualRootWgtPackage = "wgt-package"; -const std::string kVirtualRootWgtPrivate = "wgt-private"; -const std::string kVirtualRootWgtPrivateTmp = "wgt-private-tmp"; - -const std::string kFileUriPrefix = "file://"; - -const std::map kStorageDirectories = { - {STORAGE_DIRECTORY_CAMERA, &kVirtualRootCamera}, - {STORAGE_DIRECTORY_DOCUMENTS, &kVirtualRootDocuments}, - {STORAGE_DIRECTORY_DOWNLOADS, &kVirtualRootDownloads}, - {STORAGE_DIRECTORY_IMAGES, &kVirtualRootImages}, - {STORAGE_DIRECTORY_MUSIC, &kVirtualRootMusic}, - {STORAGE_DIRECTORY_SYSTEM_RINGTONES, &kVirtualRootRingtones}, - {STORAGE_DIRECTORY_VIDEOS, &kVirtualRootVideos} -}; - -std::map g_storages; - -std::map g_virtual_roots; - -void AddVirtualRoot(const std::string& name, const std::string& path) { - LoggerD("Enter"); - g_virtual_roots.insert(std::make_pair(name, common::VirtualRoot(name, path))); -} - -void OnStorageStateChanged(int storage_id, storage_state_e state, void *user_data) { - LoggerD("Enter"); - const auto it = g_storages.find(storage_id); - - if (it != g_storages.end()) { - it->second.state_ = state; - } else { - LoggerE("Unknown storage: %d", storage_id); - } -} - -bool OnStorageDeviceSupported(int storage_id, storage_type_e type, - storage_state_e state, const char *path, - void *user_data) { - LoggerD("Enter"); - g_storages.insert(std::make_pair(storage_id, common::VirtualStorage(storage_id, type, state, path))); - - storage_set_state_changed_cb(storage_id, OnStorageStateChanged, nullptr); - - if (STORAGE_TYPE_INTERNAL == type) { - // virtual roots are only on internal storage - for (const auto& kv : kStorageDirectories) { - char* directory = nullptr; - storage_directory_e dir = kv.first; - - int err = storage_get_directory(storage_id, dir, &directory); - - if (STORAGE_ERROR_NONE == err && nullptr != directory) { - AddVirtualRoot(*kv.second, directory); - free(directory); - } - } - } - - return true; -} - -common::optional GetRootDir() { - LoggerD("Enter"); - std::string app_id = common::CurrentApplication::GetInstance().GetApplicationId(); - - app_info_h app_info; - int err = app_info_create(app_id.c_str(), &app_info); - if (APP_MANAGER_ERROR_NONE != err) { - LoggerE("Can't create app info handle from appId (%s): %d (%s)", app_id.c_str(), err, - get_error_message(err)); - return nullptr; - } - SCOPE_EXIT { - app_info_destroy(app_info); - }; - - char* package = nullptr; - err = app_info_get_package(app_info, &package); - if (APP_MANAGER_ERROR_NONE != err) { - LoggerE("Can't get package name from app info (%s)", get_error_message(err)); - return nullptr; - } - SCOPE_EXIT { - free(package); - }; - - package_info_h pkg_info; - err = package_info_create(package, &pkg_info); - if (PACKAGE_MANAGER_ERROR_NONE != err) { - LoggerE("Can't create package info handle from pkg (%s)", get_error_message(err)); - return nullptr; - } - SCOPE_EXIT { - package_info_destroy(pkg_info); - }; - - char* root = nullptr; - err = package_info_get_root_path(pkg_info, &root); - if (PACKAGE_MANAGER_ERROR_NONE != err || nullptr == root) { - LoggerE("Can't get root path from package info (%s)", get_error_message(err)); - return nullptr; - } - - std::string ret{root}; - free(root); - - return ret; -} - -} // namespace - -namespace common { - -std::string to_string(storage_type_e type) { - switch (type) { - case STORAGE_TYPE_INTERNAL: - return "INTERNAL"; - - case STORAGE_TYPE_EXTERNAL: - return "EXTERNAL"; - - default: - LoggerE("Unknown storage type: %d", type); - return "UNKNOWN"; - } -} - -std::string to_string(storage_state_e state) { - switch (state) { - case STORAGE_STATE_UNMOUNTABLE: - return "UNMOUNTABLE"; - - case STORAGE_STATE_REMOVED: - return "REMOVED"; - - case STORAGE_STATE_MOUNTED: - case STORAGE_STATE_MOUNTED_READ_ONLY: - return "MOUNTED"; - - default: - LoggerE("Unknown storage state: %d", state); - return "UNKNOWN"; - } -} - -VirtualRoot::VirtualRoot(const std::string& name, const std::string& path) - : name_(name), - path_(path) { -} - -picojson::value VirtualRoot::ToJson() const { - picojson::value v{picojson::object{}}; - picojson::object& obj = v.get(); - - obj["name"] = picojson::value(name_); - obj["path"] = picojson::value(path_); - - return v; -} - -VirtualStorage::VirtualStorage(int id, storage_type_e type, - storage_state_e state, const std::string& path) - : id_(id), - type_(type), - state_(state), - path_(path) { - LoggerD("Enter"); - switch (type_) { - case STORAGE_TYPE_INTERNAL: - name_ = "internal"; - break; - - case STORAGE_TYPE_EXTERNAL: - name_ = "removable"; - break; - - default: - name_ = "unknown"; - LoggerE("Unknown storage type: %d", type); - break; - } - name_ += std::to_string(id_); -} - -picojson::value VirtualStorage::ToJson() const { - picojson::value v{picojson::object{}}; - picojson::object& obj = v.get(); - - obj["storage_id"] = picojson::value(static_cast(id_)); - obj["type"] = picojson::value(to_string(type_)); - obj["state"] = picojson::value(to_string(state_)); - obj["path"] = picojson::value(path_); - obj["name"] = picojson::value(name_); - - return v; -} - -VirtualFs::VirtualFs() : app_root_(GetRootDir()) { - LoggerD("Enter"); - if (app_root_) { - AddVirtualRoot(kVirtualRootWgtPackage, *app_root_ + "/res/wgt"); - AddVirtualRoot(kVirtualRootWgtPrivate, *app_root_ + "/data"); - AddVirtualRoot(kVirtualRootWgtPrivateTmp, *app_root_ + "/tmp"); - } - - int err = storage_foreach_device_supported(OnStorageDeviceSupported, nullptr); - - if (STORAGE_ERROR_NONE != err) { - LoggerE("Unknown Error on getting storage paths %d (%s)", err, get_error_message(err)); - } - - int id = -1; - // add virtual roots to storages - for (const auto kw : g_virtual_roots) { - const int storage_id = id--; - VirtualStorage vs{storage_id, STORAGE_TYPE_INTERNAL, STORAGE_STATE_MOUNTED, kw.second.path_}; - vs.name_ = kw.second.name_; - g_storages.insert(std::make_pair(storage_id, vs)); - } -} - -VirtualFs::~VirtualFs() { - LoggerD("Enter"); - for (const auto kv : g_storages) { - storage_unset_state_changed_cb(kv.second.id_, OnStorageStateChanged); - } -} - -VirtualFs& VirtualFs::GetInstance() { - static VirtualFs vfs; - return vfs; -} - -optional VirtualFs::GetVirtualRootDirectory(const std::string& name) const { - LoggerD("Enter"); - const auto it = g_virtual_roots.find(name); - if (it != g_virtual_roots.end()) { - return it->second.path_; - } - return nullptr; -} -optional VirtualFs::GetApplicationDirectory() const { - return app_root_; -} - -std::string VirtualFs::GetRealPath(const std::string& path_or_uri) const { - LoggerD("Enter"); - SLoggerD("Input: [%s]", path_or_uri.c_str()); - std::string realpath; - std::size_t pos = path_or_uri.find(kFileUriPrefix); - if (pos != std::string::npos) { - realpath = path_or_uri.substr(pos + kFileUriPrefix.size()); - } else { - realpath = path_or_uri; - } - pos = realpath.find('/'); - if (pos != 0) { - const std::string prefix = realpath.substr(0, pos); - const auto it = g_virtual_roots.find(prefix); - if (it != g_virtual_roots.end()) { - realpath.replace(0, prefix.size(), it->second.path_); - } else { - LoggerE("Unknown virtual root"); - } - } - SLoggerD("Exit: [%s]", realpath.c_str()); - return realpath; -} - -std::string VirtualFs::GetVirtualPath(const std::string& real_path) const { - LoggerD("Enter"); - for (const auto& kv : g_virtual_roots) { - if (0 == real_path.compare(0, kv.second.path_.size(), kv.second.path_)) { - return std::string(real_path).replace(0, kv.second.path_.size(), kv.first); - } - } - return real_path; -} - -std::vector VirtualFs::GetVirtualRoots() const { - LoggerD("Enter"); - std::vector r; - - for (const auto kv : g_virtual_roots) { - r.push_back(kv.second); - } - - return r; -} - -std::vector VirtualFs::GetStorages() const { - LoggerD("Enter"); - std::vector r; - - for (const auto kv : g_storages) { - r.push_back(kv.second); - } - - return r; -} - -} // namespace common diff --git a/src/common/virtual_fs.h b/src/common/virtual_fs.h deleted file mode 100755 index e4b25514..00000000 --- a/src/common/virtual_fs.h +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) 2014 Intel Corporation. All rights reserved. -// Copyright 2015 Samsung Electronics Co, Ltd. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMMON_VIRTUAL_FS_H_ -#define COMMON_VIRTUAL_FS_H_ - -#include -#include - -#include - -#include "common/optional.h" -#include "common/picojson.h" - -namespace common { - -std::string to_string(storage_type_e type); -std::string to_string(storage_state_e state); - -struct VirtualRoot { - VirtualRoot(const std::string& name, const std::string& path); - picojson::value ToJson() const; - std::string name_; - std::string path_; -}; - -struct VirtualStorage { - VirtualStorage(int id, storage_type_e type, storage_state_e state, - const std::string& path = ""); - picojson::value ToJson() const; - int id_; - storage_type_e type_; - storage_state_e state_; - std::string path_; - std::string name_; -}; - -class VirtualFs { - public: - /** - * Get absolute path of Virtual Roots - * - * @return absolute path on success - */ - optional GetVirtualRootDirectory(const std::string& name) const; - - /** - * Get root directory of current application. - * - * @return absolute path on success - */ - optional GetApplicationDirectory() const; - - /** - * Get real path (absolute path) from virtual path - * - * @remark - * this function never fail. - * if you want virtual path is not exist, check with getVirtualRoot() - * - * @return real path - */ - std::string GetRealPath(const std::string& path_or_uri) const; - - /** - * Get virtual path from real path - * - * @return virtual path - */ - std::string GetVirtualPath(const std::string& real_path) const; - - std::vector GetVirtualRoots() const; - - std::vector GetStorages() const; - - static VirtualFs& GetInstance(); - - private: - VirtualFs(); - VirtualFs(const VirtualFs&) = delete; - VirtualFs& operator =(const VirtualFs&) = delete; - ~VirtualFs(); - - optional app_root_; -}; - -} // namespace common - -#endif // COMMON_VIRTUAL_FS_H_ diff --git a/src/content/content_instance.cc b/src/content/content_instance.cc index 5275d4a1..4dffe567 100755 --- a/src/content/content_instance.cc +++ b/src/content/content_instance.cc @@ -27,9 +27,9 @@ #include "common/platform_result.h" #include "common/task-queue.h" #include "common/tools.h" -#include "common/virtual_fs.h" #include "content/content_manager.h" +#include "common/filesystem/filesystem_provider_storage.h" namespace extension { namespace content { @@ -137,7 +137,7 @@ static void* WorkThread(const std::shared_ptr& user_data) { } case ContentManagerScanfileCallback: { std::string contentURI = user_data->args.get("contentURI").get(); - std::string real_path = common::VirtualFs::GetInstance().GetRealPath(contentURI); + std::string real_path = common::FilesystemProviderStorage::Create().GetRealPath(contentURI); ret = ContentManager::getInstance()->scanFile(real_path); if (ret != MEDIA_CONTENT_ERROR_NONE) { PlatformResult err = LogAndCreateResult( diff --git a/src/content/content_manager.cc b/src/content/content_manager.cc index 05cc0dbb..1099b868 100644 --- a/src/content/content_manager.cc +++ b/src/content/content_manager.cc @@ -29,7 +29,7 @@ #include "common/logger.h" #include "common/scope_exit.h" #include "common/tools.h" -#include "common/virtual_fs.h" +#include "common/filesystem/filesystem_provider_storage.h" #include "content/content_filter.h" @@ -820,7 +820,7 @@ int ContentManager::scanFile(std::string& uri) { PlatformResult ContentManager::scanDirectory(media_scan_completed_cb callback, ReplyCallbackData* cbData) { LoggerD("Enter"); const std::string& contentDirURI = cbData->args.get("contentDirURI").get(); - std::string real_path = common::VirtualFs::GetInstance().GetRealPath(contentDirURI); + std::string real_path = common::FilesystemProviderStorage::Create().GetRealPath(contentDirURI); const bool recursive = cbData->args.get("recursive").get(); int ret = media_content_scan_folder(real_path.c_str(), recursive, callback, (void*) cbData); @@ -1568,7 +1568,7 @@ int ContentManager::setThumbnailUri(int id, const std::string& thb_uri) media_playlist_h playlist_handle = getPlaylistHandle(id); PlaylistUniquePtr playlist_ptr(playlist_handle, destroyMediaPlaylistHandle); - std::string real_path = VirtualFs::GetInstance().GetRealPath(thb_uri); + std::string real_path = common::FilesystemProviderStorage::Create().GetRealPath(thb_uri); const int ret_code = media_playlist_set_thumbnail_path(playlist_handle, real_path.c_str()); if(MEDIA_CONTENT_ERROR_NONE != ret_code) { diff --git a/src/download/download_instance.cc b/src/download/download_instance.cc index 24602d65..a10618e6 100755 --- a/src/download/download_instance.cc +++ b/src/download/download_instance.cc @@ -24,7 +24,7 @@ #include "common/picojson.h" #include "common/logger.h" #include "common/typeutil.h" -#include "common/virtual_fs.h" +#include "common/filesystem/filesystem_provider_storage.h" namespace extension { namespace download { @@ -318,7 +318,8 @@ gboolean DownloadInstance::OnFinished(void* user_data) { } out["callbackId"] = picojson::value(static_cast(callback_id)); - out["fullPath"] = picojson::value(common::VirtualFs::GetInstance().GetVirtualPath(fullPath)); + + out["fullPath"] = picojson::value(common::FilesystemProviderStorage::Create().GetVirtualPath(fullPath)); Instance::PostMessage(downCbPtr->instance, picojson::value(out).serialize().c_str()); downCbPtr->instance->download_callbacks.erase(callback_id); @@ -445,7 +446,7 @@ void DownloadInstance::DownloadManagerStart if (!args.get("destination").is()) { if (args.get("destination").get() != "") { diPtr->destination = args.get("destination").get(); - diPtr->destination = common::VirtualFs::GetInstance().GetRealPath(diPtr->destination); + diPtr->destination = common::FilesystemProviderStorage::Create().GetRealPath(diPtr->destination); } } diff --git a/src/filesystem/filesystem_instance.cc b/src/filesystem/filesystem_instance.cc index 5da9cc39..1f5718ee 100644 --- a/src/filesystem/filesystem_instance.cc +++ b/src/filesystem/filesystem_instance.cc @@ -344,7 +344,7 @@ void FilesystemInstance::FileSystemManagerFetchStorages( picojson::object& out) { LoggerD("enter"); - auto onSuccess = [&](const std::vector& result) { + auto onSuccess = [&](const std::vector& result) { LoggerD("enter"); picojson::array storages; storages.reserve(result.size()); @@ -377,14 +377,14 @@ void FilesystemInstance::StopListening( ReportSuccess(out); } -void FilesystemInstance::onFilesystemStateChangeSuccessCallback(const common::VirtualStorage& storage) { +void FilesystemInstance::onFilesystemStateChangeSuccessCallback(const common::Storage& storage) { LoggerD("entered"); picojson::value event = picojson::value(picojson::object()); picojson::object& obj = event.get(); obj["label"] = picojson::value(storage.name_); - obj["type"] = picojson::value(common::to_string(storage.type_)); - obj["state"] = picojson::value(common::to_string(storage.state_)); + obj["type"] = picojson::value(common::Storage::ToString(storage.type())); + obj["state"] = picojson::value(common::Storage::ToString(storage.state())); obj["listenerId"] = picojson::value("StorageStateChangeListener"); Instance::PostMessage(this, event.serialize().c_str()); } diff --git a/src/filesystem/filesystem_instance.h b/src/filesystem/filesystem_instance.h index 6c30d3ab..b46ef7da 100644 --- a/src/filesystem/filesystem_instance.h +++ b/src/filesystem/filesystem_instance.h @@ -19,7 +19,8 @@ #include "common/extension.h" #include "filesystem_utils.h" -#include "filesystem_manager.h" +#include "filesystem/filesystem_manager.h" +#include "common/filesystem/filesystem_storage.h" namespace extension { namespace filesystem { @@ -54,7 +55,7 @@ class FilesystemInstance : public common::ParsedInstance, void StopListening(const picojson::value& args, picojson::object& out); void CopyTo(const picojson::value& args, picojson::object& out); void onFilesystemStateChangeErrorCallback(); - void onFilesystemStateChangeSuccessCallback(const common::VirtualStorage& storage); + void onFilesystemStateChangeSuccessCallback(const common::Storage& storage); void PrepareError(const FilesystemError& error, picojson::object& out); }; diff --git a/src/filesystem/filesystem_manager.cc b/src/filesystem/filesystem_manager.cc index 4e6a6e37..b0d282ff 100644 --- a/src/filesystem/filesystem_manager.cc +++ b/src/filesystem/filesystem_manager.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "filesystem_manager.h" +#include "filesystem/filesystem_manager.h" #include #include @@ -36,7 +36,7 @@ #include "common/tools.h" #include "common/scope_exit.h" #include "common/extension.h" -#include "filesystem_file.h" +#include "filesystem/filesystem_file.h" namespace extension { namespace filesystem { @@ -44,20 +44,8 @@ namespace filesystem { using common::tools::GetErrorString; namespace { -void storage_cb(int storage_id, storage_state_e state, void* user_data) { - LoggerD("entered"); - if (user_data) { - FilesystemStateChangeListener* listener = - static_cast(user_data); - storage_type_e type; - storage_get_type(storage_id, &type); - listener->onFilesystemStateChangeSuccessCallback(common::VirtualStorage(storage_id, type, state)); - } -} -int unlink_cb(const char* fpath, - const struct stat* sb, - int typeflag, +int unlink_cb(const char* fpath, const struct stat* sb, int typeflag, struct FTW* ftwbuf) { if (ftwbuf->level == 0) return 0; @@ -68,10 +56,8 @@ int unlink_cb(const char* fpath, return result; } -int unlink_with_base_dir_cb(const char* fpath, - const struct stat* sb, - int typeflag, - struct FTW* ftwbuf) { +int unlink_with_base_dir_cb(const char* fpath, const struct stat* sb, + int typeflag, struct FTW* ftwbuf) { int result = remove(fpath); if (result) LoggerE("error occured"); @@ -125,10 +111,10 @@ FilesystemError copyDirectory(const std::string& originPath, if (strcmp(result->d_name, ".") == 0 || strcmp(result->d_name, "..") == 0) continue; - std::string oldLocation = - originPath + std::string("/") + std::string(result->d_name); - std::string newLocation = - destPath + std::string("/") + std::string(result->d_name); + std::string oldLocation = originPath + std::string("/") + + std::string(result->d_name); + std::string newLocation = destPath + std::string("/") + + std::string(result->d_name); FilesystemError fstatus = FilesystemError::None; if (result->d_type == DT_DIR) { fstatus = copyDirectory(oldLocation, newLocation); @@ -148,8 +134,7 @@ FilesystemError copyDirectory(const std::string& originPath, } FilesystemError perform_deep_copy(const std::string& originPath, - const std::string& destPath, - bool overwrite) { + const std::string& destPath, bool overwrite) { LoggerD("enter src %s dst %s", originPath.c_str(), destPath.c_str()); FilesystemStat originStat = FilesystemStat::getStat(originPath); FilesystemStat destStat = FilesystemStat::getStat(destPath); @@ -172,22 +157,22 @@ FilesystemError perform_deep_copy(const std::string& originPath, if (destStat.isDirectory) { path.append("/"); if (originStat.isFile) { - std::string dstPathWithFilename = originPath.substr(originPath.find_last_of("/") +1 ); + std::string dstPathWithFilename = originPath.substr( + originPath.find_last_of("/") + 1); path.append(dstPathWithFilename); FilesystemStat destStatWithFilename = FilesystemStat::getStat(path); if (destStatWithFilename.valid) { status = remove(path.c_str()); if (status) { - LoggerE("Cannot remove old file: %s", GetErrorString(errno).c_str()); + LoggerE("Cannot remove old file: %s", + GetErrorString(errno).c_str()); return FilesystemError::Other; } } } else { const int maxDirOpened = 64; - if (nftw(path.c_str(), - unlink_cb, - maxDirOpened, - FTW_DEPTH | FTW_PHYS) != 0) { + if (nftw(path.c_str(), unlink_cb, maxDirOpened, FTW_DEPTH | FTW_PHYS) + != 0) { LoggerE("Error occured"); return FilesystemError::Other; } @@ -195,7 +180,8 @@ FilesystemError perform_deep_copy(const std::string& originPath, } else { status = remove(path.c_str()); if (status) { - LoggerE("Cannot remove old directory: %s", GetErrorString(errno).c_str()); + LoggerE("Cannot remove old directory: %s", + GetErrorString(errno).c_str()); return FilesystemError::Other; } } @@ -239,36 +225,21 @@ FilesystemError make_directory_worker(const std::string& path) { } } // namespace -std::vector FilesystemManager::FillStorages() { - LoggerD("entered"); - auto virtualStorages = common::VirtualFs::GetInstance().GetStorages(); - if (ids_.empty()) { - for (auto storage : virtualStorages) { - if (storage.id_ >= 0) { - ids_.insert(storage.id_); - } - } - } - return virtualStorages; -} - void FilesystemManager::FetchStorages( - const std::function&)>& success_cb, + const std::function& success_cb, const std::function& error_cb) { - LoggerD("enter"); - auto result = FillStorages(); - success_cb(result); + LoggerD("Entered"); + + success_cb(fs_provider_.GetStorages()); } FilesystemManager::FilesystemManager() - : listener_(nullptr), is_listener_registered_(false) {} + : listener_(nullptr), + fs_provider_(common::FilesystemProviderStorage::Create()) { +} + FilesystemManager::~FilesystemManager() { LoggerD("enter"); - if (is_listener_registered_) { - for (auto id : ids_) { - storage_unset_state_changed_cb(id, storage_cb); - } - } } FilesystemManager& FilesystemManager::GetInstance() { @@ -293,10 +264,10 @@ void FilesystemManager::StatPath( } void FilesystemManager::GetVirtualRoots( - const std::function&)>& success_cb, + const std::function& success_cb, const std::function& error_cb) { LoggerD("enter"); - success_cb(common::VirtualFs::GetInstance().GetVirtualRoots()); + success_cb(fs_provider_.GetVirtualPaths()); } void FilesystemManager::CreateFile( @@ -306,16 +277,18 @@ void FilesystemManager::CreateFile( LoggerD("enter"); const mode_t create_mode = S_IRWXU | S_IRWXG | S_IRWXO; int status; - status = - TEMP_FAILURE_RETRY(open(path.c_str(), O_RDWR | O_CREAT, create_mode)); + status = TEMP_FAILURE_RETRY( + open(path.c_str(), O_RDWR | O_CREAT, create_mode)); if (-1 == status) { - LoggerE("Cannot create or open file %s: %s", path.c_str(), GetErrorString(errno).c_str()); + LoggerE("Cannot create or open file %s: %s", path.c_str(), + GetErrorString(errno).c_str()); error_cb(FilesystemError::Other); return; } status = close(status); if (0 != status) { - LoggerE("Cannot close file %s: %s", path.c_str(), GetErrorString(errno).c_str()); + LoggerE("Cannot close file %s: %s", path.c_str(), + GetErrorString(errno).c_str()); error_cb(FilesystemError::Other); return; } @@ -336,8 +309,7 @@ void FilesystemManager::MakeDirectory( } void FilesystemManager::Rename( - const std::string& oldPath, - const std::string& newPath, + const std::string& oldPath, const std::string& newPath, const std::function& success_cb, const std::function& error_cb) { @@ -363,7 +335,7 @@ void FilesystemManager::ReadDir( const std::function& error_cb) { LoggerD("entered"); - std::vector fileList; + std::vector < std::string > fileList; DIR* dp = nullptr; struct dirent entry; struct dirent* result = nullptr; @@ -371,12 +343,11 @@ void FilesystemManager::ReadDir( dp = opendir(path.c_str()); if (dp != NULL) { - while ((status = readdir_r(dp, &entry, &result)) == 0 && - result != nullptr) { + while ((status = readdir_r(dp, &entry, &result)) == 0 && result != nullptr) { if (strcmp(result->d_name, ".") != 0 && strcmp(result->d_name, "..") != 0) fileList.push_back(path + "/" + std::string(result->d_name)); } - (void)closedir(dp); + (void) closedir(dp); if (status == 0) { success_cb(fileList); } else { @@ -391,8 +362,7 @@ void FilesystemManager::ReadDir( } void FilesystemManager::UnlinkFile( - const std::string& path, - const std::function& success_cb, + const std::string& path, const std::function& success_cb, const std::function& error_cb) { LoggerD("enter"); if (unlink(path.c_str()) != 0) { @@ -404,12 +374,12 @@ void FilesystemManager::UnlinkFile( } void FilesystemManager::RemoveDirectory( - const std::string& path, - const std::function& success_cb, + const std::string& path, const std::function& success_cb, const std::function& error_cb) { LoggerD("enter"); const int maxDirOpened = 64; - if (nftw(path.c_str(), unlink_with_base_dir_cb, maxDirOpened, FTW_DEPTH | FTW_PHYS) != 0) { + if (nftw(path.c_str(), unlink_with_base_dir_cb, maxDirOpened, + FTW_DEPTH | FTW_PHYS) != 0) { LoggerE("Error occured"); error_cb(FilesystemError::Other); } @@ -463,50 +433,36 @@ void FilesystemManager::FileWrite( } void FilesystemManager::StartListening() { - LoggerD("enter"); - FillStorages(); - - if (!is_listener_registered_ && !ids_.empty()) { - int result = STORAGE_ERROR_NONE; - std::set registeredSuccessfully; - for (auto id : ids_) { - result = storage_set_state_changed_cb(id, storage_cb, (void*)listener_); - LoggerD("registered id %d", id); - if (result != STORAGE_ERROR_NONE) { - for (auto registeredId : registeredSuccessfully) { - storage_unset_state_changed_cb(registeredId, storage_cb); - LoggerD("unregistering id %d", registeredId); - } - listener_->onFilesystemStateChangeErrorCallback(); - break; - } else { - registeredSuccessfully.insert(id); - } - } - if (ids_.size() == registeredSuccessfully.size()) - is_listener_registered_ = true; - } + LoggerD("Entered"); + auto set = std::bind(&FilesystemManager::OnStorageDeviceChanged, this, + std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3); + + fs_provider_.RegisterDeviceChangeState(set); } void FilesystemManager::StopListening() { - LoggerD("enter"); - if (is_listener_registered_) { - for (auto id : ids_) { - storage_unset_state_changed_cb(id, storage_cb); - } + LoggerD("Entered"); + + fs_provider_.UnregisterDeviceChangeState(); +} + +void FilesystemManager::OnStorageDeviceChanged(common::Storage const& _storage, + common::StorageState _old, + common::StorageState _new) { + LoggerD("Entered"); + if (listener_) { + listener_->onFilesystemStateChangeSuccessCallback(_storage); } - is_listener_registered_ = false; } void FilesystemManager::CopyTo( - const std::string& originFilePath, - const std::string& destinationFilePath, - const bool overwrite, - const std::function& success_cb, + const std::string& originFilePath, const std::string& destinationFilePath, + const bool overwrite, const std::function& success_cb, const std::function& error_cb) { LoggerD("enter"); - FilesystemError retval = - perform_deep_copy(originFilePath, destinationFilePath, overwrite); + FilesystemError retval = perform_deep_copy(originFilePath, + destinationFilePath, overwrite); if (FilesystemError::None == retval) { success_cb(); } else { @@ -515,7 +471,6 @@ void FilesystemManager::CopyTo( } } - void FilesystemManager::AddListener(FilesystemStateChangeListener* listener) { LoggerD("enter"); listener_ = listener; diff --git a/src/filesystem/filesystem_manager.h b/src/filesystem/filesystem_manager.h index 0492d345..514e0a02 100644 --- a/src/filesystem/filesystem_manager.h +++ b/src/filesystem/filesystem_manager.h @@ -21,11 +21,15 @@ #include #include #include +#include -#include "common/virtual_fs.h" +#include "common/filesystem/filesystem_provider_storage.h" -#include "filesystem_stat.h" -#include "filesystem_utils.h" +#include "filesystem/filesystem_stat.h" +#include "filesystem/filesystem_utils.h" + +#include "common/filesystem/filesystem_storage.h" +#include "common/filesystem/filesystem_provider_storage.h" namespace extension { namespace filesystem { @@ -34,20 +38,21 @@ class FilesystemStateChangeListener { public: virtual ~FilesystemStateChangeListener() {} virtual void onFilesystemStateChangeSuccessCallback( - const common::VirtualStorage& storage) = 0; + const common::Storage& storage) = 0; virtual void onFilesystemStateChangeErrorCallback() = 0; }; class FilesystemManager { private: FilesystemManager(); - ~FilesystemManager(); FilesystemStateChangeListener* listener_; - bool is_listener_registered_; - std::set ids_; + common::FilesystemProviderStorage& fs_provider_; public: + + virtual ~FilesystemManager(); + static FilesystemManager& GetInstance(); void UnlinkFile( @@ -59,13 +64,12 @@ class FilesystemManager { const std::function& success_cb, const std::function& error_cb); - std::vector FillStorages(); void FetchStorages( - const std::function&)>& success_cb, + const std::function& success_cb, const std::function& error_cb); void GetVirtualRoots( - const std::function&)>& success_cb, + const std::function& success_cb, const std::function& error_cb); void CreateFile(const std::string& path, @@ -110,6 +114,8 @@ void CopyTo(const std::string& originFilePath, void StartListening(); void StopListening(); + void OnStorageDeviceChanged(common::Storage const& _virtualStorage, + common::StorageState _old, common::StorageState _new); void AddListener(FilesystemStateChangeListener* listener); void RemoveListener(); }; diff --git a/src/filesystem/js/common.js b/src/filesystem/js/common.js index b4891db7..e5b45f77 100644 --- a/src/filesystem/js/common.js +++ b/src/filesystem/js/common.js @@ -23,7 +23,10 @@ var types_ = validator_.Types; var native_ = new xwalk.utils.NativeManager(extension); function SetReadOnlyProperty(obj, n, v) { - Object.defineProperty(obj, n, {value: v, writable: false}); + Object.defineProperty(obj, n, { + value: v, + writable: false + }); } var FileSystemStorageType = { @@ -71,6 +74,7 @@ var commonFS_ = (function() { for (var i = 0; i < virtualRoots.length; ++i) { cacheVirtualToReal[virtualRoots[i].name] = { path: virtualRoots[i].path, + label: virtualRoots[i].name, type: FileSystemStorageType.INTERNAL, state: FileSystemStorageState.MOUNTED }; @@ -99,8 +103,8 @@ var commonFS_ = (function() { }); listenerRegistered = true; } catch (e) { - console.log('Failed to register storage change listener, ' + - 'storage information may be corrupted: ' + e.message); + console.log('Failed to register storage change listener, ' + + 'storage information may be corrupted: ' + e.message); } } @@ -113,7 +117,7 @@ var commonFS_ = (function() { if (aPath.indexOf(uriPrefix) === 0) { _fileRealPath = aPath.substr(uriPrefix.length); } else if (aPath[0] !== '/') { - //virtual path + // virtual path initCache(); var _pathTokens = aPath.split('/'); @@ -124,7 +128,7 @@ var commonFS_ = (function() { _fileRealPath += '/' + _pathTokens[i]; } } else { - //If path token is not present in cache then it is invalid + // If path token is not present in cache then it is invalid _fileRealPath = undefined; // check storages for (var j = 0; j < cacheStorages.length; ++j) { @@ -163,10 +167,7 @@ var commonFS_ = (function() { } function getFileInfo(aStatObj, secondIter, aMode) { - var _result = {}, - _pathTokens, - _fileParentPath = '', - i; + var _result = {}, _pathTokens, _fileParentPath = '', i; var aPath = toVirtualPath(aStatObj.path); _result.readOnly = aStatObj.readOnly; @@ -224,14 +225,14 @@ var commonFS_ = (function() { }; function f_isCorrectRelativePath(relativePath) { - return ((0 !== relativePath.indexOf('/')) && - (0 !== relativePath.indexOf('\\')) && - (-1 === relativePath.indexOf('?')) && - (-1 === relativePath.indexOf('*')) && - (-1 === relativePath.indexOf(':')) && - (-1 === relativePath.indexOf('"')) && - (-1 === relativePath.indexOf('<')) && - (-1 === relativePath.indexOf('>'))); + return ((0 !== relativePath.indexOf('/')) + && (0 !== relativePath.indexOf('\\')) + && (-1 === relativePath.indexOf('?')) + && (-1 === relativePath.indexOf('*')) + && (-1 === relativePath.indexOf(':')) + && (-1 === relativePath.indexOf('"')) + && (-1 === relativePath.indexOf('<')) && (-1 === relativePath + .indexOf('>'))); }; function cloneStorage(storage) { @@ -249,6 +250,15 @@ var commonFS_ = (function() { return cloneStorage(cacheStorages[i]); } } + + for (var key in cacheVirtualToReal) { + if (cacheVirtualToReal.hasOwnProperty(key)) { + if (cacheVirtualToReal[key].label === label) { + return cloneStorage(cacheVirtualToReal[key]); + } + } + } + return null; } @@ -258,6 +268,13 @@ var commonFS_ = (function() { for (var i = 0; i < cacheStorages.length; ++i) { ret.push(cloneStorage(cacheStorages[i])); } + + for (var key in cacheVirtualToReal) { + if (cacheVirtualToReal.hasOwnProperty(key)) { + ret.push(cloneStorage(cacheVirtualToReal[key])); + } + } + return ret; } diff --git a/src/messaging/message.cc b/src/messaging/message.cc index d3d086db..991a745e 100755 --- a/src/messaging/message.cc +++ b/src/messaging/message.cc @@ -23,7 +23,6 @@ #include "common/logger.h" #include "common/platform_exception.h" #include "common/scope_exit.h" -#include "common/virtual_fs.h" #include "Ecore_File.h" #include "message_email.h" @@ -31,6 +30,7 @@ #include "message_mms.h" #include "short_message_manager.h" #include "messaging_util.h" +#include "common/filesystem/filesystem_provider_storage.h" using common::ErrorCode; using common::PlatformResult; @@ -423,7 +423,7 @@ PlatformResult copyFileToTemp(const std::string& sourcePath, std::string* result std::string dirPath = "/tmp/" + std::string(buf); if ( sourcePath[0] != '/' ) { - attPath = common::VirtualFs::GetInstance().GetRealPath(sourcePath); + attPath = common::FilesystemProviderStorage::Create().GetRealPath(sourcePath); } else { // Assuming that the path is a real path attPath = sourcePath; } @@ -786,7 +786,7 @@ PlatformResult Message::addMMSBodyAndAttachmentsToStruct(const AttachmentPtrVect if (attach.at(i)->isFilePathSet()) { std::string filepath = attach.at(i)->getFilePath(); LoggerD("att[%d]: org filepath: %s", i, filepath.c_str()); - filepath = common::VirtualFs::GetInstance().GetRealPath(filepath); + filepath = common::FilesystemProviderStorage::Create().GetRealPath(filepath); LoggerD("att[%d]: org virtual filepath: %s", i, filepath.c_str()); msg_set_str_value(tmpAtt, MSG_MMS_ATTACH_FILEPATH_STR, diff --git a/src/messaging/message_attachment.cc b/src/messaging/message_attachment.cc index d778962b..67db1178 100755 --- a/src/messaging/message_attachment.cc +++ b/src/messaging/message_attachment.cc @@ -20,7 +20,7 @@ #include "message_attachment.h" #include "common/logger.h" -#include "common/virtual_fs.h" +#include "common/filesystem/filesystem_provider_storage.h" namespace extension { namespace messaging { @@ -143,7 +143,7 @@ void MessageAttachment::setFilePath(const std::string &value) { LoggerD("Entered"); - m_filePath = common::VirtualFs::GetInstance().GetRealPath(value); + m_filePath = common::FilesystemProviderStorage::Create().GetRealPath(value); m_isFilePathSet = true; } diff --git a/src/notification/status_notification.cc b/src/notification/status_notification.cc index ffcd3c7f..f0944683 100644 --- a/src/notification/status_notification.cc +++ b/src/notification/status_notification.cc @@ -23,7 +23,7 @@ #include "common/converter.h" #include "common/logger.h" #include "common/scope_exit.h" -#include "common/virtual_fs.h" +#include "common/filesystem/filesystem_provider_storage.h" namespace extension { namespace notification { @@ -528,7 +528,8 @@ PlatformResult StatusNotification::GetThumbnails(notification_h noti_handle, if (!text.length()) break; - out->push_back(picojson::value(VirtualFs::GetInstance().GetVirtualPath(text))); + //CHECK GetVirtualPath ?? + out->push_back(picojson::value(common::FilesystemProviderStorage::Create().GetVirtualPath(text))); } return PlatformResult(ErrorCode::NO_ERROR); @@ -542,7 +543,7 @@ PlatformResult StatusNotification::SetThumbnails(notification_h noti_handle, size_t thumbnails_map_size = thumbnails_map_.size(); for (auto& item : value) { const std::string& text = JsonCast(item); - std::string real_path = VirtualFs::GetInstance().GetRealPath(text); + std::string real_path = common::FilesystemProviderStorage::Create().GetRealPath(text); PlatformResult status = SetImage(noti_handle, thumbnails_map_.at(idx), real_path); @@ -1014,14 +1015,14 @@ PlatformResult StatusNotification::ToJson(int id, if (status.IsError()) return status; if (value_str.length()) { - out["iconPath"] = picojson::value(VirtualFs::GetInstance().GetVirtualPath(value_str)); + out["iconPath"] = picojson::value(common::FilesystemProviderStorage::Create().GetVirtualPath(value_str)); } status = GetImage(noti_handle, NOTIFICATION_IMAGE_TYPE_ICON_SUB, &value_str); if (status.IsError()) return status; if (value_str.length()) { - out["subIconPath"] = picojson::value(VirtualFs::GetInstance().GetVirtualPath(value_str)); + out["subIconPath"] = picojson::value(common::FilesystemProviderStorage::Create().GetVirtualPath(value_str)); } long number; @@ -1060,7 +1061,7 @@ PlatformResult StatusNotification::ToJson(int id, if (status.IsError()) return status; if (value_str.length()) { - out["backgroundImagePath"] = picojson::value(VirtualFs::GetInstance().GetVirtualPath(value_str)); + out["backgroundImagePath"] = picojson::value(common::FilesystemProviderStorage::Create().GetVirtualPath(value_str)); } picojson::array thumbnails = picojson::array(); @@ -1075,7 +1076,7 @@ PlatformResult StatusNotification::ToJson(int id, if (status.IsError()) return status; if (value_str.length()) { - out["soundPath"] = picojson::value(VirtualFs::GetInstance().GetVirtualPath(value_str)); + out["soundPath"] = picojson::value(common::FilesystemProviderStorage::Create().GetVirtualPath(value_str)); } bool vibration; @@ -1183,7 +1184,7 @@ PlatformResult StatusNotification::FromJson(const picojson::object& args, picojson::value val(noti_obj); if (val.contains("iconPath") && !IsNull(noti_obj, "iconPath")) { const std::string& value_str = common::FromJson(noti_obj, "iconPath"); - std::string real_path = VirtualFs::GetInstance().GetRealPath(value_str); + std::string real_path = common::FilesystemProviderStorage::Create().GetRealPath(value_str); status = SetImage(noti_handle, NOTIFICATION_IMAGE_TYPE_ICON, real_path); if (status.IsError()) { @@ -1194,7 +1195,7 @@ PlatformResult StatusNotification::FromJson(const picojson::object& args, if (val.contains("subIconPath") && !IsNull(noti_obj, "subIconPath")) { const std::string& value_str = common::FromJson(noti_obj, "subIconPath"); - std::string real_path = VirtualFs::GetInstance().GetRealPath(value_str); + std::string real_path = common::FilesystemProviderStorage::Create().GetRealPath(value_str); status = SetImage(noti_handle, NOTIFICATION_IMAGE_TYPE_ICON_SUB, real_path); if (status.IsError()) { @@ -1245,7 +1246,7 @@ PlatformResult StatusNotification::FromJson(const picojson::object& args, if (val.contains("backgroundImagePath") && !IsNull(noti_obj, "backgroundImagePath")) { const std::string& value_str = common::FromJson(noti_obj, "backgroundImagePath"); - std::string real_path = VirtualFs::GetInstance().GetRealPath(value_str); + std::string real_path = common::FilesystemProviderStorage::Create().GetRealPath(value_str); status = SetImage(noti_handle, NOTIFICATION_IMAGE_TYPE_BACKGROUND, real_path); if (status.IsError()) { @@ -1263,7 +1264,7 @@ PlatformResult StatusNotification::FromJson(const picojson::object& args, if (val.contains("soundPath") && !IsNull(noti_obj, "soundPath")) { const std::string& value_str = common::FromJson(noti_obj, "soundPath"); - std::string real_path = VirtualFs::GetInstance().GetRealPath(value_str); + std::string real_path = common::FilesystemProviderStorage::Create().GetRealPath(value_str); status = SetSoundPath(noti_handle, real_path); if (status.IsError()) { diff --git a/src/systemsetting/systemsetting_instance.cc b/src/systemsetting/systemsetting_instance.cc index c9e702a3..dcc63294 100644 --- a/src/systemsetting/systemsetting_instance.cc +++ b/src/systemsetting/systemsetting_instance.cc @@ -21,7 +21,7 @@ #include "common/logger.h" #include "common/picojson.h" #include "common/task-queue.h" -#include "common/virtual_fs.h" +#include "common/filesystem/filesystem_provider_storage.h" #include "common/tools.h" #include @@ -152,7 +152,7 @@ void SystemSettingInstance::setProperty(const picojson::value& args, picojson::o auto get = [this, type, value, callback_id](const std::shared_ptr& response) -> void { LoggerD("Setting platform value"); - std::string real_path = VirtualFs::GetInstance().GetRealPath(value); + std::string real_path = common::FilesystemProviderStorage::Create().GetRealPath(value); PlatformResult status = setPlatformPropertyValue(type, real_path); picojson::object& obj = response->get(); if (status.IsSuccess()) { -- 2.34.1