From: Krzysztof Lachacz Date: Fri, 19 Dec 2014 12:47:37 +0000 (+0100) Subject: [Archive] Implementation of filesystem classes required by module X-Git-Tag: submit/tizen_tv/20150603.064601~1^2~723^2 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=2d2df3333643c2bd4e57dedc24dcdfb11220ee18;p=platform%2Fcore%2Fapi%2Fwebapi-plugins.git [Archive] Implementation of filesystem classes required by module [Verification] Code compiles without errors. Archive object is visible in tizen namespace. Change-Id: Ia1613bf84ebed2f2cce244b3887e7537443e39a6 Signed-off-by: Krzysztof Lachacz --- diff --git a/src/archive/archive.gyp b/src/archive/archive.gyp index 999e79d1..751d0ac9 100644 --- a/src/archive/archive.gyp +++ b/src/archive/archive.gyp @@ -8,8 +8,6 @@ 'type': 'loadable_module', 'sources': [ 'archive_api.js', - #'archive_callback_data.cc', - 'archive_callback_data.h', 'archive_extension.cc', 'archive_extension.h', 'archive_file.cc', @@ -22,8 +20,14 @@ 'archive_manager.h', 'archive_utils.cc', 'archive_utils.h', - 'filesystem_file.cc' + 'archive_callback_data.cc', + 'archive_callback_data.h', + 'filesystem_file.cc', 'filesystem_file.h', + 'filesystem_path.cc', + 'filesystem_path.h', + 'filesystem_node.cc', + 'filesystem_node.h', 'defs.h', 'un_zip.cc', 'un_zip.h', diff --git a/src/archive/archive_api.js b/src/archive/archive_api.js index 32187ce1..630edca6 100644 --- a/src/archive/archive_api.js +++ b/src/archive/archive_api.js @@ -382,11 +382,11 @@ ArchiveManager.prototype.open = function () { } }).then({ success: function (data) { - args.successCallback.call(null, new ArchiveFile(data)); + args.onsuccess.call(null, new ArchiveFile(data)); }, error: function (e) { - if (args.errorCallback) { - args.errorCallback.call( + if (args.onerror) { + args.onerror.call( null, new tizen.WebAPIException(e.code, e.name, e.message) ); diff --git a/src/archive/archive_callback_data.cc b/src/archive/archive_callback_data.cc index 075ab6df..207135b7 100755 --- a/src/archive/archive_callback_data.cc +++ b/src/archive/archive_callback_data.cc @@ -23,215 +23,181 @@ #include "common/logger.h" -//#include +//#include #include "archive_file.h" #include "archive_utils.h" #include "un_zip.h" #include "zip.h" +#include "archive_manager.h" + +namespace extension { +namespace archive { using namespace common; -namespace DeviceAPI { -namespace Archive { +//---------------------------------------------------------------------------------------- +//OperationCallbackData +//---------------------------------------------------------------------------------------- -//namespace { -//const char* CALLBACK_SUCCESS = "success"; -//const char* CALLBACK_ERROR = "error"; -//const char* CALLBACK_PROGRESS = "progress"; -//} //anonymous namespace -// -////---------------------------------------------------------------------------------------- -////OperationCallbackData -////---------------------------------------------------------------------------------------- -// -//OperationCallbackData::OperationCallbackData(ArchiveCallbackType callback_type) : -// m_callback_type(callback_type), -// m_op_id(0), -// m_is_error(false), -// m_is_canceled(false) -//{ -// LOGD("Entered"); -//} -// -//OperationCallbackData::~OperationCallbackData() -//{ -// LOGD("Entered"); -// if(m_op_id > 0){ -// ArchiveManager::getInstance().eraseElementFromArchiveFileMap(m_op_id); -// } -//} -// -//void OperationCallbackData::setError(const std::string &err_name, -// const std::string &err_message) -//{ -// LOGD("Entered"); -// //store only first error -// if (!m_is_error) { -// m_err_name = err_name; -// m_err_message = err_message; -// m_is_error = true; -// } -//} -// -//bool OperationCallbackData::isError() const -//{ -// LOGD("Entered"); -// return m_is_error; -//} -// -//bool OperationCallbackData::isCanceled() const -//{ -// return m_is_canceled; -//} -// -//void OperationCallbackData::setOperationId(long op_id) -//{ -// LOGD("Entered"); -// m_op_id = op_id; -//} -// -//long OperationCallbackData::getOperationId() const -//{ -// LOGD("Entered"); -// return m_op_id; -//} -// -//void OperationCallbackData::setIsCanceled(bool canceled) -//{ -// m_is_canceled = canceled; -//} -// -//const std::string& OperationCallbackData::getErrorName() const -//{ -// LOGD("Entered"); -// return m_err_name; -//} -// -//const std::string& OperationCallbackData::getErrorMessage() const -//{ -// LOGD("Entered"); -// return m_err_message; -//} -// -//ArchiveCallbackType OperationCallbackData::getCallbackType() const -//{ -// LOGD("Entered"); -// return m_callback_type; -//} -// -//ArchiveFilePtr OperationCallbackData::getArchiveFile() const -//{ -// return m_caller_instance; -//} -// -//void OperationCallbackData::setArchiveFile(ArchiveFilePtr caller) -//{ -// m_caller_instance = caller; -//} -// -// -////void OperationCallbackData::setSuccessCallback(JSValueRef on_success) -////{ -//// LOGD("Entered"); -//// auto ctx = getContext(); -//// if(on_success && JSValueIsObject(ctx, on_success)) { -//// JSObjectRef success = JSValueToObject(ctx, on_success, NULL); -//// this->setCallback(CALLBACK_SUCCESS, success); -//// } -////} -// -////void OperationCallbackData::setErrorCallback(JSValueRef on_error) -////{ -//// LOGD("Entered"); -//// auto ctx = getContext(); -//// if(on_error && JSValueIsObject(ctx, on_error)) { -//// JSObjectRef error = JSValueToObject(ctx, on_error, NULL); -//// this->setCallback(CALLBACK_ERROR, error); -//// } -////} -// -//void OperationCallbackData::callSuccessCallback() -//{ -// LOGD("Entered"); -// LOGW("STUB Not calling success callback"); -// //this->invokeCallback(CALLBACK_SUCCESS, 0, NULL); -//} -// -////void OperationCallbackData::callSuccessCallback(JSValueRef success) -////{ -//// LOGD("Entered"); -//// this->invokeCallback(CALLBACK_SUCCESS, success); -////} -// -////void OperationCallbackData::callErrorCallback(JSValueRef err) -////{ -//// LOGD("Entered"); -//// this->invokeCallback(CALLBACK_ERROR, err); -////} -// -////---------------------------------------------------------------------------------------- -////OpenCallbackData -////---------------------------------------------------------------------------------------- -// -//OpenCallbackData::OpenCallbackData(ArchiveCallbackType callback_type): -// OperationCallbackData(callback_type) -//{ -// LOGD("Entered"); -//} -// -//OpenCallbackData::~OpenCallbackData() -//{ -// LOGD("Entered"); -//} -// -//void OpenCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) -//{ -// LOGE("Entered"); -// -// Filesystem::FilePtr file = archive_file_ptr->getFile(); -// if (!file) { -// LOGE("File is null"); -// throw UnknownException("File is null"); -// } -// Filesystem::NodePtr node = file->getNode(); -// if(!node) { -// LOGE("Node is null"); -// throw UnknownException("Node is null"); -// } -// const FileMode fm = archive_file_ptr->m_file_mode; -// if (0 == node->getSize()) { -// if(FileMode::READ_WRITE == fm || -// FileMode::WRITE == fm || -// FileMode::ADD == fm) { -// LOGD("Empty file obtained for writing/appending"); -// -// // Do not create empty archive with minizip library - it will not be loaded -// // by unzip. -// // -// // For explanation please see: -// // ArchiveFile.h m_created_as_new_empty_archive description -// // -// archive_file_ptr->setCreatedAsNewEmptyArchive(true); -// archive_file_ptr->setEntryMap(ArchiveFileEntryPtrMapPtr( -// new ArchiveFileEntryPtrMap())); -// archive_file_ptr->setIsOpen(true); -// } -// else { -// LOGE("The file is empty throwing: InvalidValuesException - Invalid ZIP archive"); -// throw InvalidValuesException("Invalid ZIP archive"); -// } -// } -// else { -// archive_file_ptr->setIsOpen(true); -// archive_file_ptr->updateListOfEntries(); -// } -// -// guint id = g_idle_add(ArchiveFile::openTaskCompleteCB, this); -// if (!id) { -// LOGE("g_idle_add fails"); -// throw UnknownException("g_idle_add fails"); -// } -//} +OperationCallbackData::OperationCallbackData(ArchiveCallbackType callback_type) : + m_callback_type(callback_type), + m_op_id(0), + m_cid(-1), + m_is_error(false), + m_is_canceled(false) +{ + LoggerD("Entered"); +} + +OperationCallbackData::~OperationCallbackData() +{ + LoggerD("Entered"); + if(m_op_id > 0){ + //ArchiveManager::getInstance().eraseElementFromArchiveFileMap(m_op_id); + } +} + +void OperationCallbackData::setError(const std::string &err_name, + const std::string &err_message) +{ + LoggerD("Entered"); + //store only first error + if (!m_is_error) { + m_err_name = err_name; + m_err_message = err_message; + m_is_error = true; + } +} + +bool OperationCallbackData::isError() const +{ + LoggerD("Entered"); + return m_is_error; +} + +bool OperationCallbackData::isCanceled() const +{ + return m_is_canceled; +} + +void OperationCallbackData::setOperationId(long op_id) +{ + LoggerD("Entered"); + m_op_id = op_id; +} + +long OperationCallbackData::getOperationId() const +{ + LoggerD("Entered"); + return m_op_id; +} + +void OperationCallbackData::setCallbackId(double cid) +{ + m_cid = cid; +} + +double OperationCallbackData::getCallbackId() const +{ + return m_cid; +} + +void OperationCallbackData::setIsCanceled(bool canceled) +{ + m_is_canceled = canceled; +} + +const std::string& OperationCallbackData::getErrorName() const +{ + LoggerD("Entered"); + return m_err_name; +} + +const std::string& OperationCallbackData::getErrorMessage() const +{ + LoggerD("Entered"); + return m_err_message; +} + +ArchiveCallbackType OperationCallbackData::getCallbackType() const +{ + LoggerD("Entered"); + return m_callback_type; +} + +ArchiveFilePtr OperationCallbackData::getArchiveFile() const +{ + return m_caller_instance; +} + +void OperationCallbackData::setArchiveFile(ArchiveFilePtr caller) +{ + m_caller_instance = caller; +} + +//---------------------------------------------------------------------------------------- +//OpenCallbackData +//---------------------------------------------------------------------------------------- + +OpenCallbackData::OpenCallbackData(ArchiveCallbackType callback_type): + OperationCallbackData(callback_type) +{ + LoggerD("Entered"); +} + +OpenCallbackData::~OpenCallbackData() +{ + LoggerD("Entered"); +} + +void OpenCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) +{ + LoggerE("Entered"); + + filesystem::FilePtr file = archive_file_ptr->getFile(); + if (!file) { + LoggerE("File is null"); + throw UnknownException("File is null"); + } + filesystem::NodePtr node = file->getNode(); + if(!node) { + LoggerE("Node is null"); + throw UnknownException("Node is null"); + } + const FileMode fm = archive_file_ptr->m_file_mode; + if (0 == node->getSize()) { + if(FileMode::READ_WRITE == fm || + FileMode::WRITE == fm || + FileMode::ADD == fm) { + LoggerD("Empty file obtained for writing/appending"); + + // Do not create empty archive with minizip library - it will not be loaded + // by unzip. + // + // For explanation please see: + // ArchiveFile.h m_created_as_new_empty_archive description + // + archive_file_ptr->setCreatedAsNewEmptyArchive(true); + archive_file_ptr->setEntryMap(ArchiveFileEntryPtrMapPtr( + new ArchiveFileEntryPtrMap())); + archive_file_ptr->setIsOpen(true); + } + else { + LoggerE("The file is empty throwing: InvalidValuesException - Invalid ZIP archive"); + throw InvalidValuesException("Invalid ZIP archive"); + } + } + else { + archive_file_ptr->setIsOpen(true); + archive_file_ptr->updateListOfEntries(); + } + + guint id = g_idle_add(ArchiveFile::openTaskCompleteCB, this); + if (!id) { + LoggerE("g_idle_add fails"); + throw UnknownException("g_idle_add fails"); + } +} // ////---------------------------------------------------------------------------------------- ////GetEntriesCallbackData @@ -240,11 +206,11 @@ namespace Archive { //GetEntriesCallbackData::GetEntriesCallbackData(ArchiveCallbackType callback_type): // OperationCallbackData(callback_type) //{ -// LOGD("Entered"); +// LoggerD("Entered"); //} //GetEntriesCallbackData::~GetEntriesCallbackData() //{ -// LOGD("Entered"); +// LoggerD("Entered"); //} // //ArchiveFileEntryPtrMapPtr GetEntriesCallbackData::getEntries() const @@ -259,13 +225,13 @@ namespace Archive { // //void GetEntriesCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) //{ -// LOGD("Entered"); +// LoggerD("Entered"); // // setEntries(archive_file_ptr->getEntryMap()); // // guint id = g_idle_add(ArchiveFile::getEntriesTaskCompleteCB, this); // if (!id) { -// LOGE("g_idle_add fails"); +// LoggerE("g_idle_add fails"); // throw UnknownException("g_idle_add fails"); // } //} @@ -277,23 +243,23 @@ namespace Archive { //GetEntryByNameCallbackData::GetEntryByNameCallbackData(ArchiveCallbackType callback_type): // OperationCallbackData(callback_type) //{ -// LOGD("Entered"); +// LoggerD("Entered"); //} // //GetEntryByNameCallbackData::~GetEntryByNameCallbackData() //{ -// LOGD("Entered"); +// LoggerD("Entered"); //} // //const std::string& GetEntryByNameCallbackData::getName() const //{ -// LOGD("Entered"); +// LoggerD("Entered"); // return m_name; //} // //void GetEntryByNameCallbackData::setName(const std::string& name) //{ -// LOGD("Entered"); +// LoggerD("Entered"); // m_name = name; //} // @@ -309,7 +275,7 @@ namespace Archive { // //void GetEntryByNameCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) //{ -// LOGD("Entered"); +// LoggerD("Entered"); // // ArchiveFileEntryPtrMapPtr entries = archive_file_ptr->getEntryMap(); // auto it = entries->find(getName()); @@ -319,13 +285,13 @@ namespace Archive { // // // if (it == entries->end() && !isDirectoryPath(getName())) { // const std::string try_directory = getName() + "/"; -// LOGD("GetEntryByName Trying directory: [%s]", try_directory.c_str()); +// LoggerD("GetEntryByName Trying directory: [%s]", try_directory.c_str()); // it = entries->find(try_directory); // } // // if (it == entries->end()) { -// LOGE("GetEntryByName Entry with name: [%s] not found", getName().c_str()); -// LOGE("Throwing NotFoundException - Entry not found"); +// LoggerE("GetEntryByName Entry with name: [%s] not found", getName().c_str()); +// LoggerE("Throwing NotFoundException - Entry not found"); // throw NotFoundException("Entry not found"); // } // @@ -333,7 +299,7 @@ namespace Archive { // // guint id = g_idle_add(ArchiveFile::getEntryByNameTaskCompleteCB, this); // if (!id) { -// LOGE("g_idle_add fails"); +// LoggerE("g_idle_add fails"); // throw UnknownException("g_idle_add fails"); // } //} @@ -346,30 +312,31 @@ namespace Archive { // OperationCallbackData(callback_type), // m_overwrite(false) //{ -// LOGD("Entered"); +// LoggerD("Entered"); //} // //BaseProgressCallback::~BaseProgressCallback() //{ -// LOGD("Entered"); +// LoggerD("Entered"); //} // //bool BaseProgressCallback::getOverwrite() const //{ -// LOGD("Entered"); +// LoggerD("Entered"); // return m_overwrite; //} // //void BaseProgressCallback::setOverwrite(bool overwrite) //{ -// LOGD("Entered"); +// LoggerD("Entered"); // m_overwrite = overwrite; //} // //struct ProgressHolder //{ // ProgressHolder() : -// callback(NULL) +// overall_progress(0.0), +// callback(NULL) // { // }; // @@ -383,7 +350,7 @@ namespace Archive { // guint id = g_idle_add(BaseProgressCallback::callSuccessCallbackCB, // static_cast(this)); // if (!id) { -// LOGE("g_idle_add fails - success callback will not be called"); +// LoggerE("g_idle_add fails - success callback will not be called"); // } //} // @@ -391,28 +358,28 @@ namespace Archive { //{ // BaseProgressCallback* callback = static_cast(data); // if (!callback) { -// LOGE("callback pointer is NULL"); +// LoggerE("callback pointer is NULL"); // return false; // } // // std::unique_ptr cb_ptr(callback); // -// LOGW("STUB Not checking if context is still alive"); +// LoggerW("STUB Not checking if context is still alive"); // //JSContextRef context = callback->getContext(); // //if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) { -// // LOGE("context closed - unable to call success callback"); +// // LoggerE("context closed - unable to call success callback"); // // return false; // //} // -// try { -// callback->callSuccessCallback(); -// } -// catch (const PlatformException &err) { -// LOGE("%s (%s)", err.name().c_str(), err.message().c_str()); -// } -// catch (...) { -// LOGE("Unknown error occurs"); -// } +//// try { +//// callback->callSuccessCallback(); +//// } +//// catch (const PlatformException &err) { +//// LoggerE("%s (%s)", err.name().c_str(), err.message().c_str()); +//// } +//// catch (...) { +//// LoggerE("Unknown error occurs"); +//// } // // callback->setArchiveFile(ArchiveFilePtr()); // ArchiveManager::getInstance().eraseElementFromArchiveFileMap(callback->m_op_id); @@ -422,7 +389,7 @@ namespace Archive { // ////void BaseProgressCallback::setProgressCallback(JSValueRef on_progress) ////{ -//// LOGD("Entered"); +//// LoggerD("Entered"); //// auto ctx = getContext(); //// if(on_progress && JSValueIsObject(ctx, on_progress)) { //// JSObjectRef progress = JSValueToObject(ctx, on_progress, NULL); @@ -434,8 +401,8 @@ namespace Archive { // double value, // const std::string& filename) //{ -// LOGD("Entered"); -// LOGW("STUB calling progress callback"); +// LoggerD("Entered"); +// LoggerW("STUB calling progress callback"); // // //auto ctx = getContext(); // //const int SIZE = 3; @@ -461,12 +428,12 @@ namespace Archive { // guint id = g_idle_add(BaseProgressCallback::callProgressCallbackCB, // static_cast(ph)); // if (!id) { -// LOGE("g_idle_add fails"); +// LoggerE("g_idle_add fails"); // delete ph; // ph = NULL; // } // } else { -// LOGE("Couldn't allocate ProgressHolder"); +// LoggerE("Couldn't allocate ProgressHolder"); // } //} // @@ -474,20 +441,20 @@ namespace Archive { //{ // ProgressHolder* ph = static_cast(data); // if (!ph) { -// LOGE("ph is null"); +// LoggerE("ph is null"); // return false; // } // // std::unique_ptr ph_ptr(ph); // if (!ph->callback) { -// LOGE("ph->callback is null"); +// LoggerE("ph->callback is null"); // return false; // } // -// LOGW("STUB Not checking if context is still alive"); +// LoggerW("STUB Not checking if context is still alive"); // //JSContextRef context = ph->callback->getContext(); // //if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) { -// // LOGE("context was closed"); +// // LoggerE("context was closed"); // // return false; // //} // @@ -501,10 +468,10 @@ namespace Archive { // ph->currently_processed_entry->getName()); // } // catch (const PlatformException &err) { -// LOGE("%s (%s)", err.name().c_str(), err.message().c_str()); +// LoggerE("%s (%s)", err.name().c_str(), err.message().c_str()); // } // catch (...) { -// LOGE("Unknown error occurs"); +// LoggerE("Unknown error occurs"); // } // // return false; @@ -517,32 +484,32 @@ namespace Archive { //AddProgressCallback::AddProgressCallback(ArchiveCallbackType callback_type): // BaseProgressCallback(callback_type) //{ -// LOGD("Entered"); +// LoggerD("Entered"); //} // //AddProgressCallback::~AddProgressCallback() //{ -// LOGD("Entered"); +// LoggerD("Entered"); //} // //ArchiveFileEntryPtr AddProgressCallback::getFileEntry() const //{ -// LOGD("Entered"); +// LoggerD("Entered"); // return m_file_entry; //} // //void AddProgressCallback::setFileEntry(ArchiveFileEntryPtr file_entry) //{ -// LOGD("Entered"); +// LoggerD("Entered"); // m_file_entry = file_entry; //} // //void AddProgressCallback::setBasePath(const std::string& path) //{ -// LOGD("Entered"); +// LoggerD("Entered"); // m_base_path = path; -// m_base_virt_path = Filesystem::External::toVirtualPath(m_base_path); -// std::string::size_type pos = m_base_virt_path.find(Filesystem::Path::getSeparator()); +// m_base_virt_path = filesystem::External::toVirtualPath(m_base_path); +// std::string::size_type pos = m_base_virt_path.find(filesystem::Path::getSeparator()); // if (pos != std::string::npos) // { // m_base_virt_path = m_base_virt_path.substr(pos + 1); @@ -555,27 +522,27 @@ namespace Archive { // //const std::string& AddProgressCallback::getBasePath() //{ -// LOGD("Entered"); +// LoggerD("Entered"); // return m_base_path; //} // //const std::string& AddProgressCallback::getBaseVirtualPath() //{ -// LOGD("Entered"); +// LoggerD("Entered"); // return m_base_virt_path; //} // //void AddProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) //{ -// LOGD("Entered"); +// LoggerD("Entered"); // // if(!m_file_entry) { -// LOGE("ArchiveFileEntry is not set in callback"); +// LoggerE("ArchiveFileEntry is not set in callback"); // throw UnknownException("Could not add file to archive"); // } // // if(!archive_file_ptr) { -// LOGE("archive_file_ptr is NULL"); +// LoggerE("archive_file_ptr is NULL"); // throw UnknownException("Could not extract archive file entry"); // } // @@ -592,14 +559,14 @@ namespace Archive { // //we can remove CreatedAsNewEmptyArchive flag // archive_file_ptr->setCreatedAsNewEmptyArchive(false); // -// LOGD("Update decompressed size and entry list"); +// LoggerD("Update decompressed size and entry list"); // // update informations about decompressed size and entry list // // TODO FIXME need to resolve problem with access to file by // // more than one thread // try{ // archive_file_ptr->updateListOfEntries(); // } catch(...){ -// LOGD("Unknown error during updating entries list inside archive"); +// LoggerD("Unknown error during updating entries list inside archive"); // } //} // @@ -610,26 +577,27 @@ namespace Archive { //ExtractAllProgressCallback::ExtractAllProgressCallback(ArchiveCallbackType callback_type): // BaseProgressCallback(callback_type), // m_files_to_extract(0), +// m_expected_decompressed_size(0), // m_files_extracted(0), // m_current_file_size(0), // m_current_file_extracted_bytes(0), // m_progress_overall(0), // m_overall_decompressed(0) //{ -// LOGD("Entered"); +// LoggerD("Entered"); //} // //ExtractAllProgressCallback::~ExtractAllProgressCallback() //{ -// LOGD("Entered"); +// LoggerD("Entered"); //} // -//Filesystem::FilePtr ExtractAllProgressCallback::getDirectory() const +//filesystem::FilePtr ExtractAllProgressCallback::getDirectory() const //{ // return m_directory; //} // -//void ExtractAllProgressCallback::setDirectory(Filesystem::FilePtr directory) +//void ExtractAllProgressCallback::setDirectory(filesystem::FilePtr directory) //{ // m_directory = directory; //} @@ -661,7 +629,7 @@ namespace Archive { // static_cast(m_overall_decompressed + m_files_extracted) / // static_cast(m_expected_decompressed_size + m_files_to_extract); // -// LOGD("%s of %s - %f%% (%d/%d files)", +// LoggerD("%s of %s - %f%% (%d/%d files)", // bytesToReadableString(m_overall_decompressed).c_str(), // bytesToReadableString(m_expected_decompressed_size).c_str(), // m_progress_overall * 100.0, @@ -686,7 +654,7 @@ namespace Archive { // //void ExtractAllProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) //{ -// LOGD("Entered"); +// LoggerD("Entered"); // archive_file_ptr->extractAllTask(this); //} // @@ -718,7 +686,7 @@ namespace Archive { // //OperationCanceledException::OperationCanceledException(const char* message) //{ -// LOGD("Entered"); +// LoggerD("Entered"); //} // ////---------------------------------------------------------------------------------------- @@ -729,13 +697,13 @@ namespace Archive { // ExtractAllProgressCallback(), // m_strip_name(false) //{ -// LOGD("Entered"); +// LoggerD("Entered"); // m_callback_type = EXTRACT_ENTRY_PROGRESS_CALLBACK; //} // //ExtractEntryProgressCallback::~ExtractEntryProgressCallback() //{ -// LOGD("Entered"); +// LoggerD("Entered"); //} // //ArchiveFileEntryPtr ExtractEntryProgressCallback::getArchiveFileEntry() @@ -771,15 +739,15 @@ namespace Archive { // //void ExtractEntryProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) //{ -// LOGD("Entered"); +// LoggerD("Entered"); // // if(!m_archive_file_entry) { -// LOGE("ArchiveFileEntry is not set in callback"); +// LoggerE("ArchiveFileEntry is not set in callback"); // throw UnknownException("Could not extract archive file entry"); // } // // if(!archive_file_ptr) { -// LOGE("archive_file_ptr is NULL"); +// LoggerE("archive_file_ptr is NULL"); // throw UnknownException("Could not extract archive file entry"); // } // @@ -787,5 +755,5 @@ namespace Archive { // unzip->extractTo(this); //} -} //namespace Archive -} //namespace DeviceAPI +} //namespace archive +} //namespace extension diff --git a/src/archive/archive_callback_data.h b/src/archive/archive_callback_data.h index 4dd9fec2..acd12901 100644 --- a/src/archive/archive_callback_data.h +++ b/src/archive/archive_callback_data.h @@ -26,12 +26,16 @@ #include #include +#include "common/platform_exception.h" #include "filesystem_file.h" - #include "archive_file_entry.h" -namespace DeviceAPI { -namespace Archive { + +namespace extension { +namespace archive { + +using namespace common; +using namespace filesystem; class ArchiveFileEntry; typedef std::shared_ptr ArchiveFileEntryPtr; @@ -53,16 +57,9 @@ typedef std::shared_ptr ArchiveFilePtr; class OperationCallbackData { public: - OperationCallbackData(ArchiveCallbackType callback_type = OPERATION_CALLBACK_DATA); + OperationCallbackData(ArchiveCallbackType callback_type); virtual ~OperationCallbackData(); - //void setSuccessCallback(JSValueRef on_success); - //void setErrorCallback(JSValueRef on_error); - - void callSuccessCallback(); - //void callSuccessCallback(JSValueRef err); - //void callErrorCallback(JSValueRef err); - void setError(const std::string &err_name, const std::string &err_message); bool isError() const; @@ -71,20 +68,23 @@ public: void setOperationId(long op_id); long getOperationId() const; + void setCallbackId(double cid); + double getCallbackId() const; ArchiveCallbackType getCallbackType() const; - virtual void executeOperation(ArchiveFilePtr archive_file_ptr); - - bool isCanceled() const; - void setIsCanceled(bool is_cancel); + virtual void executeOperation(ArchiveFilePtr archive_file_ptr) = 0; ArchiveFilePtr getArchiveFile() const; void setArchiveFile(ArchiveFilePtr caller); + bool isCanceled() const; + void setIsCanceled(bool canceled); + protected: ArchiveCallbackType m_callback_type; long m_op_id; + double m_cid; private: bool m_is_error; @@ -101,7 +101,15 @@ public: OpenCallbackData(ArchiveCallbackType callback_type = OPEN_CALLBACK_DATA); virtual ~OpenCallbackData(); + void setFile(std::string file); + const std::string& getFile() const; + //void setMode(FileMode mode); + //FileMode getMode() const; + virtual void executeOperation(ArchiveFilePtr archive_file_ptr); + +private: + std::string m_filename; }; class GetEntriesCallbackData : public OperationCallbackData @@ -195,8 +203,8 @@ public: ExtractAllProgressCallback(ArchiveCallbackType callback_type = EXTRACT_ALL_PROGRESS_CALLBACK); virtual ~ExtractAllProgressCallback(); - Filesystem::FilePtr getDirectory() const; - void setDirectory(Filesystem::FilePtr directory); + filesystem::FilePtr getDirectory() const; + void setDirectory(filesystem::FilePtr directory); void startedExtractingFile(unsigned long current_file_size); void extractedPartOfFile(unsigned long bytes_decompressed); @@ -216,7 +224,7 @@ public: private: void updateOverallProgress(unsigned long bytes_decompressed); - Filesystem::FilePtr m_directory; + filesystem::FilePtr m_directory; // // Constant values set before extracting entries: diff --git a/src/archive/archive_extension.cc b/src/archive/archive_extension.cc index 80635e66..e045825a 100644 --- a/src/archive/archive_extension.cc +++ b/src/archive/archive_extension.cc @@ -2,9 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "archive/archive_extension.h" - -#include "archive/archive_instance.h" +#include "archive_extension.h" +#include "archive_instance.h" // This will be generated from archive_api.js extern const char kSource_archive_api[]; @@ -26,5 +25,5 @@ ArchiveExtension::~ArchiveExtension() common::Instance* ArchiveExtension::CreateInstance() { - return new extension::archive::ArchiveInstance; + return &extension::archive::ArchiveInstance::getInstance(); } diff --git a/src/archive/archive_file.cc b/src/archive/archive_file.cc index 64d28919..ef6b9f52 100644 --- a/src/archive/archive_file.cc +++ b/src/archive/archive_file.cc @@ -16,6 +16,7 @@ // #include "archive_file.h" +#include "common/picojson.h" #include "common/logger.h" #include "common/platform_exception.h" @@ -24,12 +25,12 @@ #include "defs.h" #include "un_zip.h" #include "zip.h" - +#include "archive_instance.h" using namespace common; -namespace DeviceAPI { -namespace Archive { +namespace extension { +namespace archive { Permission::Permission(bool r, bool w, bool rw, bool a){ permission[0] = r; @@ -56,7 +57,7 @@ ArchiveFile::ArchiveFile() : m_overwrite(false), m_created_as_new_empty_archive(false) { - LOGD("Entered"); + LoggerD("Entered"); } ArchiveFile::ArchiveFile(FileMode file_mode) : @@ -70,10 +71,10 @@ ArchiveFile::ArchiveFile(FileMode file_mode) : ArchiveFile::~ArchiveFile() { - LOGD("Entered"); + LoggerD("Entered"); if(m_entry_map) { - LOGD("Unlinking old m_entry_map: %d ArchiveFileEntries", m_entry_map->size()); + LoggerD("Unlinking old m_entry_map: %d ArchiveFileEntries", m_entry_map->size()); for(auto it = m_entry_map->begin(); it != m_entry_map->end(); ++it) { if(it->second) { it->second->setArchiveFileNonProtectPtr(NULL); @@ -84,18 +85,30 @@ ArchiveFile::~ArchiveFile() gboolean ArchiveFile::openTaskCompleteCB(void *data) { - LOGD("Entered"); - LOGW("STUB Not calling success/error callback"); + LoggerD("Entered"); auto callback = static_cast(data); if (!callback) { - LOGE("callback is null"); + LoggerE("callback is null"); return false; } + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); + + obj["action"] = picojson::value("success"); + obj["cid"] = picojson::value(callback->getCallbackId()); + obj["args"] = picojson::value(picojson::object()); + picojson::object& obj1 = obj["args"].get(); + obj1["mode"] = picojson::value("r"); + + LoggerD("%s", val.serialize().c_str()); + + ArchiveInstance::getInstance().PostMessage(val.serialize().c_str()); + // JSContextRef context = callback->getContext(); // if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) { -// LOGE("context was closed"); +// LoggerE("context was closed"); // delete callback; // callback = NULL; // return false; @@ -114,10 +127,10 @@ gboolean ArchiveFile::openTaskCompleteCB(void *data) // } // } // catch (const PlatformException &err) { -// LOGE("%s (%s)", err.name().c_str(), err.message().c_str()); +// LoggerE("%s (%s)", err.name().c_str(), err.message().c_str()); // } // catch (...) { -// LOGE("Unknown error occurs"); +// LoggerE("Unknown error occurs"); // } delete callback; @@ -128,23 +141,23 @@ gboolean ArchiveFile::openTaskCompleteCB(void *data) gboolean ArchiveFile::callErrorCallback(void* data) { - LOGD("Entered"); - LOGW("STUB Not calling success/error callback"); + LoggerD("Entered"); + LoggerW("STUB Not calling success/error callback"); auto callback = static_cast(data); if (!callback) { - LOGE("callback is null"); + LoggerE("callback is null"); return false; } // JSContextRef context = callback->getContext(); // if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) { -// LOGE("context was closed"); +// LoggerE("context was closed"); // delete callback; // callback = NULL; // return false; // } -// +// // try { // if (callback->isError()) { // JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context, @@ -153,14 +166,14 @@ gboolean ArchiveFile::callErrorCallback(void* data) // callback->callErrorCallback(errobj); // } // else { -// LOGW("The success callback should be not be called in this case"); +// LoggerW("The success callback should be not be called in this case"); // } // } // catch (const PlatformException &err) { -// LOGE("%s (%s)", err.name().c_str(), err.message().c_str()); +// LoggerE("%s (%s)", err.name().c_str(), err.message().c_str()); // } // catch (...) { -// LOGE("Unknown error occurs"); +// LoggerE("Unknown error occurs"); // } delete callback; @@ -171,15 +184,15 @@ gboolean ArchiveFile::callErrorCallback(void* data) void* ArchiveFile::taskManagerThread(void *data) { - LOGD("Entered"); + LoggerD("Entered"); ArchiveFileHolder* archive_file_holder = static_cast(data); if (!archive_file_holder) { - LOGE("archive_file_holder is null"); + LoggerE("archive_file_holder is null"); return NULL; } if (!archive_file_holder->ptr){ - LOGE("archive_file is null"); + LoggerE("archive_file is null"); delete archive_file_holder; archive_file_holder = NULL; return NULL; @@ -211,12 +224,12 @@ void* ArchiveFile::taskManagerThread(void *data) delete callback; callback = NULL; } catch (const PlatformException &err) { - LOGE("taskManagerThread fails, %s: %s", err.name().c_str(), + LoggerE("taskManagerThread fails, %s: %s", err.name().c_str(), err.message().c_str()); callback->setError(err.name().c_str(), err.message().c_str()); call_error_callback = true; } catch (...) { - LOGE("taskManagerThread fails"); + LoggerE("taskManagerThread fails"); callback->setError("UnknownError", "UnknownError"); call_error_callback = true; } @@ -226,7 +239,7 @@ void* ArchiveFile::taskManagerThread(void *data) archive_file_holder->ptr->m_task_queue.pop_back(); } if (!g_idle_add(callErrorCallback, static_cast(callback))) { - LOGE("g_idle_add fails"); + LoggerE("g_idle_add fails"); delete callback; callback = NULL; } @@ -241,12 +254,9 @@ void* ArchiveFile::taskManagerThread(void *data) long ArchiveFile::addOperation(OperationCallbackData* callback) { - LOGD("Entered callback type:%d", callback->getCallbackType()); + LoggerD("Entered callback type:%d", callback->getCallbackType()); - const long operation_id = - ArchiveManager::getInstance().getNextOperationId(shared_from_this()); - callback->setOperationId(operation_id); - callback->setArchiveFile(shared_from_this()); + const long operation_id = callback->getOperationId(); std::size_t size = 0; { std::lock_guard lock(m_mutex); @@ -257,20 +267,20 @@ long ArchiveFile::addOperation(OperationCallbackData* callback) pthread_t thread; ArchiveFileHolder* holder = new(std::nothrow) ArchiveFileHolder(); if(!holder) { - LOGE("Memory allocation error"); + LoggerE("Memory allocation error"); throw UnknownException("Memory allocation error"); } holder->ptr = shared_from_this(); if (pthread_create(&thread, NULL, taskManagerThread, static_cast(holder))) { - LOGE("Thread creation failed"); + LoggerE("Thread creation failed"); delete holder; holder = NULL; throw UnknownException("Thread creation failed"); } if (pthread_detach(thread)) { - LOGE("Thread detachment failed"); + LoggerE("Thread detachment failed"); } } return operation_id; @@ -278,24 +288,24 @@ long ArchiveFile::addOperation(OperationCallbackData* callback) void ArchiveFile::extractAllTask(ExtractAllProgressCallback* callback) { - Filesystem::FilePtr directory = callback->getDirectory(); + filesystem::FilePtr directory = callback->getDirectory(); if(!directory) { - LOGE("Directory is null"); + LoggerE("Directory is null"); throw UnknownException("Directory is null"); } else { if(!directory->getNode()){ - LOGE("Node in directory is null"); + LoggerE("Node in directory is null"); throw UnknownException("Node is null"); } } if(!m_file) { - LOGE("File is null"); + LoggerE("File is null"); throw UnknownException("File is null"); } else { if(!m_file->getNode()){ - LOGE("Node in file is null"); + LoggerE("Node in file is null"); throw UnknownException("Node in file is null"); } } @@ -303,9 +313,9 @@ void ArchiveFile::extractAllTask(ExtractAllProgressCallback* callback) // For explanation please see: // ArchiveFile.h m_created_as_new_empty_archive description // - if(m_file->getSize() == 0) { - LOGD("Zip file: %s is empty", - m_file->getFullPath().c_str()); + if(m_file->getNode()->getSize() == 0) { + LoggerD("Zip file: %s is empty", + m_file->getNode()->getPath()->getFullPath().c_str()); if(m_created_as_new_empty_archive) { //We do not call progress callback since we do not have any ArchiveFileEntry @@ -314,21 +324,21 @@ void ArchiveFile::extractAllTask(ExtractAllProgressCallback* callback) return; } else { - LOGW("m_created_as_new_empty_archive is false"); - LOGE("Throwing InvalidStateException: File is not valid ZIP archive"); + LoggerW("m_created_as_new_empty_archive is false"); + LoggerE("Throwing InvalidStateException: File is not valid ZIP archive"); throw InvalidStateException("File is not valid ZIP archive"); } } UnZipPtr unzip = createUnZipObject(); - unzip->extractAllFilesTo(directory->getFullPath(), callback); + unzip->extractAllFilesTo(directory->getNode()->getPath()->getFullPath(), callback); } long ArchiveFile::getEntries(GetEntriesCallbackData* callback) { - LOGD("Entered"); + LoggerD("Entered"); if(!callback) { - LOGE("callback is NULL"); + LoggerE("callback is NULL"); throw UnknownException("Could not get list of files in archive"); } @@ -339,18 +349,18 @@ long ArchiveFile::getEntries(GetEntriesCallbackData* callback) gboolean ArchiveFile::getEntriesTaskCompleteCB(void *data) { - LOGD("Entered"); - LOGW("STUB Not calling success/error callback"); + LoggerD("Entered"); + LoggerW("STUB Not calling success/error callback"); auto callback = static_cast(data); if (!callback) { - LOGE("callback is null"); + LoggerE("callback is null"); return false; } // JSContextRef context = callback->getContext(); // if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) { -// LOGE("context was closed"); +// LoggerE("context was closed"); // delete callback; // callback = NULL; // return false; @@ -377,10 +387,10 @@ gboolean ArchiveFile::getEntriesTaskCompleteCB(void *data) // callback->callSuccessCallback(jsResult); // } // catch (const PlatformException &err) { -// LOGE("%s (%s)", err.name().c_str(), err.message().c_str()); +// LoggerE("%s (%s)", err.name().c_str(), err.message().c_str()); // } // catch (...) { -// LOGE("Unknown error occurs"); +// LoggerE("Unknown error occurs"); // } delete callback; @@ -391,9 +401,9 @@ gboolean ArchiveFile::getEntriesTaskCompleteCB(void *data) long ArchiveFile::extractAll(ExtractAllProgressCallback *callback) { - LOGD("Entered"); + LoggerD("Entered"); if(!callback) { - LOGE("callback is NULL"); + LoggerE("callback is NULL"); throw UnknownException("Could not extract all files from archive"); } @@ -404,9 +414,9 @@ long ArchiveFile::extractAll(ExtractAllProgressCallback *callback) long ArchiveFile::extractEntryTo(ExtractEntryProgressCallback* callback) { - LOGD("Entered"); + LoggerD("Entered"); if(!callback) { - LOGE("callback is NULL"); + LoggerE("callback is NULL"); throw UnknownException("Could not extract archive file entry"); } @@ -417,7 +427,7 @@ long ArchiveFile::extractEntryTo(ExtractEntryProgressCallback* callback) // uncomment in case when this method have permission to throwing InvalidStateError // throwInvalidStateErrorIfArchiveFileisClosed(); if(!m_is_open) { - LOGE("Archive is not opened"); + LoggerE("Archive is not opened"); throw UnknownException("Archive is not opened"); } @@ -427,13 +437,13 @@ long ArchiveFile::extractEntryTo(ExtractEntryProgressCallback* callback) long ArchiveFile::add(AddProgressCallback *callback) { - LOGD("Entered"); + LoggerD("Entered"); if(!callback) { - LOGE("callback is NULL"); + LoggerE("callback is NULL"); throw UnknownException("Could not add file to archive"); } if(FileMode::READ == m_file_mode) { - LOGE("Trying to add file when READ access mode selected"); + LoggerE("Trying to add file when READ access mode selected"); throw InvalidAccessException("Add not allowed for \"r\" access mode"); } @@ -444,10 +454,10 @@ long ArchiveFile::add(AddProgressCallback *callback) void ArchiveFile::close() { - LOGD("Entered"); + LoggerD("Entered"); if(!m_is_open){ - LOGD("Archive already closed"); + LoggerD("Archive already closed"); } m_is_open = false; @@ -456,9 +466,9 @@ void ArchiveFile::close() long ArchiveFile::getEntryByName(GetEntryByNameCallbackData* callback) { - LOGD("Entered"); + LoggerD("Entered"); if(!callback) { - LOGE("callback is NULL"); + LoggerE("callback is NULL"); throw UnknownException("Could not get archive file entries by name"); } @@ -469,18 +479,18 @@ long ArchiveFile::getEntryByName(GetEntryByNameCallbackData* callback) gboolean ArchiveFile::getEntryByNameTaskCompleteCB(void *data) { - LOGD("Entered"); - LOGW("STUB Not calling success/error callback"); + LoggerD("Entered"); + LoggerW("STUB Not calling success/error callback"); auto callback = static_cast(data); if (!callback) { - LOGE("callback is null"); + LoggerE("callback is null"); return false; } // JSContextRef context = callback->getContext(); // if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) { -// LOGE("context was closed"); +// LoggerE("context was closed"); // delete callback; // callback = NULL; // return false; @@ -499,10 +509,10 @@ gboolean ArchiveFile::getEntryByNameTaskCompleteCB(void *data) // } // } // catch (const PlatformException &err) { -// LOGE("%s (%s)", err.name().c_str(), err.message().c_str()); +// LoggerE("%s (%s)", err.name().c_str(), err.message().c_str()); // } // catch (...) { -// LOGE("Unknown error occurs"); +// LoggerE("Unknown error occurs"); // } delete callback; @@ -511,15 +521,15 @@ gboolean ArchiveFile::getEntryByNameTaskCompleteCB(void *data) return false; } -Filesystem::FilePtr ArchiveFile::getFile() const +filesystem::FilePtr ArchiveFile::getFile() const { - LOGD("Entered"); + LoggerD("Entered"); return m_file; } -void ArchiveFile::setFile(Filesystem::FilePtr file) +void ArchiveFile::setFile(filesystem::FilePtr file) { - LOGD("Entered"); + LoggerD("Entered"); m_file = file; } @@ -530,31 +540,31 @@ bool ArchiveFile::isOverwrite() const void ArchiveFile::setOverwrite(bool overwrite) { - LOGD("Entered"); + LoggerD("Entered"); m_overwrite = overwrite; } unsigned long ArchiveFile::getDecompressedSize() const { - LOGD("Entered"); + LoggerD("Entered"); return m_decompressed_size; } void ArchiveFile::setDecompressedSize(unsigned long decompressed_size) { - LOGD("Entered"); + LoggerD("Entered"); m_decompressed_size = decompressed_size; } bool ArchiveFile::isOpen() const { - LOGD("Entered"); + LoggerD("Entered"); return m_is_open; } void ArchiveFile::setIsOpen(bool is_open) { - LOGD("Entered"); + LoggerD("Entered"); m_is_open = is_open; } @@ -565,10 +575,10 @@ ArchiveFileEntryPtrMapPtr ArchiveFile::getEntryMap() const void ArchiveFile::setEntryMap(ArchiveFileEntryPtrMapPtr entries) { - LOGD("Entered"); + LoggerD("Entered"); if(m_entry_map) { - LOGD("Unlinking old m_entry_map: %d ArchiveFileEntries", m_entry_map->size()); + LoggerD("Unlinking old m_entry_map: %d ArchiveFileEntries", m_entry_map->size()); for(auto it = m_entry_map->begin(); it != m_entry_map->end(); ++it) { if(it->second) { it->second->setArchiveFileNonProtectPtr(NULL); @@ -578,7 +588,7 @@ void ArchiveFile::setEntryMap(ArchiveFileEntryPtrMapPtr entries) m_entry_map = entries; - LOGD("Linking new m_entry_map ArchiveFileEntries (%d) with ArchiveFile object", + LoggerD("Linking new m_entry_map ArchiveFileEntries (%d) with ArchiveFile object", m_entry_map->size()); for(auto it = m_entry_map->begin(); it != m_entry_map->end(); ++it) { if(it->second) { @@ -589,54 +599,54 @@ void ArchiveFile::setEntryMap(ArchiveFileEntryPtrMapPtr entries) UnZipPtr ArchiveFile::createUnZipObject() { - LOGD("Entered"); + LoggerD("Entered"); if(!m_is_open) { - LOGE("File is not opened"); + LoggerE("File is not opened"); throw UnknownException("File is not opened"); } if (!m_file) { - LOGE("m_file is null"); + LoggerE("m_file is null"); throw UnknownException("File is null"); } -// Filesystem::NodePtr node = m_file->getNode(); +// filesystem::NodePtr node = m_file->getNode(); // if(!node) { -// LOGE("Node is null"); +// LoggerE("Node is null"); // throw UnknownException("Node is null"); // } - UnZipPtr unzip = UnZip::open(m_file->getFullPath()); + UnZipPtr unzip = UnZip::open(m_file->getNode()->getPath()->getFullPath()); return unzip; } ZipPtr ArchiveFile::createZipObject() { - LOGD("Entered"); + LoggerD("Entered"); if(!m_is_open) { - LOGE("File is not opened"); + LoggerE("File is not opened"); throw UnknownException("File is not opened"); } if (!m_file) { - LOGE("m_file is null"); + LoggerE("m_file is null"); throw UnknownException("File is null"); } -// Filesystem::NodePtr node = m_file->getNode(); +// filesystem::NodePtr node = m_file->getNode(); // if(!node) { -// LOGE("Node is null"); +// LoggerE("Node is null"); // throw UnknownException("Node is null"); // } - ZipPtr zip = Zip::open(m_file->getFullPath()); + ZipPtr zip = Zip::open(m_file->getNode()->getPath()->getFullPath()); return zip; } bool ArchiveFile::isAllowedOperation(const std::string& method_name) { - LOGD("Entered"); + LoggerD("Entered"); PermissionMap::iterator it = s_permission_map.find(method_name); if (it != s_permission_map.end()) { return it->second.permission[m_file_mode]; @@ -646,20 +656,20 @@ bool ArchiveFile::isAllowedOperation(const std::string& method_name) FileMode ArchiveFile::getFileMode() const { - LOGD("Entered"); + LoggerD("Entered"); return m_file_mode; } void ArchiveFile::setFileMode(FileMode file_mode) { - LOGD("Entered"); + LoggerD("Entered"); m_file_mode = file_mode; } void ArchiveFile::throwInvalidStateErrorIfArchiveFileIsClosed() const { if(!m_is_open){ - LOGE("ArchiveFile closed - operation not permitted"); + LoggerE("ArchiveFile closed - operation not permitted"); throw InvalidStateException( "ArchiveFile closed - operation not permitted"); } @@ -680,17 +690,17 @@ void ArchiveFile::updateListOfEntries() // For explanation please see: // ArchiveFile.h m_created_as_new_empty_archive description // - if(m_file->getSize() == 0) { - LOGD("Zip file: %s is empty", - m_file->getFullPath().c_str()); + if(m_file->getNode()->getSize() == 0) { + LoggerD("Zip file: %s is empty", + m_file->getNode()->getPath()->getFullPath().c_str()); if(m_created_as_new_empty_archive) { - LOGD("OK this is empty archive = nothing to do yet"); + LoggerD("OK this is empty archive = nothing to do yet"); return; } else { - LOGW("m_created_as_new_empty_archive is false"); - LOGE("Throwing InvalidStateException: File is not valid ZIP archive"); + LoggerW("m_created_as_new_empty_archive is false"); + LoggerE("Throwing InvalidStateException: File is not valid ZIP archive"); throw InvalidStateException("File is not valid ZIP archive"); } } @@ -707,7 +717,7 @@ bool ArchiveFile::isEntryWithNameInArchive(const std::string& name_in_zip, std::string* out_matching_name) { if(!m_entry_map) { - LOGW("m_entry_map is NULL"); + LoggerW("m_entry_map is NULL"); return false; } @@ -751,5 +761,5 @@ bool ArchiveFile::isEntryWithNameInArchive(const std::string& name_in_zip, return true; } -} // Archive -} // DeviceAPI +} // archive +} // extension diff --git a/src/archive/archive_file.h b/src/archive/archive_file.h index 00d6dd5e..9612fcae 100755 --- a/src/archive/archive_file.h +++ b/src/archive/archive_file.h @@ -21,16 +21,16 @@ #include #include #include +#include #include "archive_callback_data.h" -#include "archive_manager.h" #include "filesystem_file.h" #include "un_zip.h" #include "zip.h" +#include "archive_file_entry.h" - -namespace DeviceAPI { -namespace Archive { +namespace extension { +namespace archive { class ArchiveFile; class ArchiveManager; @@ -85,8 +85,8 @@ public: long add(AddProgressCallback *callback); void close(); - Filesystem::FilePtr getFile() const; - void setFile(Filesystem::FilePtr file); + filesystem::FilePtr getFile() const; + void setFile(filesystem::FilePtr file); bool isOverwrite() const; void setOverwrite(bool overwrite); unsigned long getDecompressedSize() const; @@ -125,7 +125,7 @@ private: std::deque m_task_queue; std::mutex m_mutex; - Filesystem::FilePtr m_file; + filesystem::FilePtr m_file; FileMode m_file_mode; static PermissionMap s_permission_map; @@ -183,7 +183,7 @@ private: friend class BaseProgressCallback; }; -} // Archive -} // DeviceAPI +} // archive +} // extension #endif /* _TIZEN_ARCHIVE_FILE_ENTRY_H_ */ diff --git a/src/archive/archive_file_entry.cc b/src/archive/archive_file_entry.cc index 1615dde4..4a10d25c 100644 --- a/src/archive/archive_file_entry.cc +++ b/src/archive/archive_file_entry.cc @@ -25,12 +25,12 @@ using namespace common; -namespace DeviceAPI { -namespace Archive { +namespace extension { +namespace archive { static const unsigned int s_default_compression_level = 5; -ArchiveFileEntry::ArchiveFileEntry(Filesystem::FilePtr file) : +ArchiveFileEntry::ArchiveFileEntry(filesystem::FilePtr file) : std::enable_shared_from_this(), m_file(file), m_archive(NULL), @@ -58,12 +58,12 @@ void ArchiveFileEntry::setCompressedSize(unsigned long compressed_size) m_compressed_size = compressed_size; } -Filesystem::FilePtr ArchiveFileEntry::getFile() const +filesystem::FilePtr ArchiveFileEntry::getFile() const { return m_file; } -void ArchiveFileEntry::setFile(Filesystem::FilePtr file) +void ArchiveFileEntry::setFile(filesystem::FilePtr file) { m_file = file; } @@ -168,5 +168,5 @@ long ArchiveFileEntry::extractTo(ExtractEntryProgressCallback* callback) return m_archive->extractEntryTo(callback); } -} // Archive -} // DeviceAPI +} // archive +} // extension diff --git a/src/archive/archive_file_entry.h b/src/archive/archive_file_entry.h index 601691f7..d6582f40 100755 --- a/src/archive/archive_file_entry.h +++ b/src/archive/archive_file_entry.h @@ -18,13 +18,12 @@ #ifndef _TIZEN_ARCHIVE_ARCHIVE_FILE_ENTRY_H_ #define _TIZEN_ARCHIVE_ARCHIVE_FILE_ENTRY_H_ -#include #include #include "filesystem_file.h" -namespace DeviceAPI { -namespace Archive { +namespace extension { +namespace archive { class ArchiveFile; @@ -38,13 +37,13 @@ typedef std::shared_ptr ArchiveFileEntryPtrMapPtr; class ArchiveFileEntry : public std::enable_shared_from_this { public: - ArchiveFileEntry(Filesystem::FilePtr file = Filesystem::FilePtr()); + ArchiveFileEntry(filesystem::FilePtr file = filesystem::FilePtr()); ~ArchiveFileEntry(); unsigned long getCompressedSize() const; void setCompressedSize(unsigned long compressedSize); - Filesystem::FilePtr getFile() const; - void setFile(Filesystem::FilePtr file); + filesystem::FilePtr getFile() const; + void setFile(filesystem::FilePtr file); unsigned long getSize() const; void setSize(unsigned long size); const std::string& getName() const; @@ -64,7 +63,7 @@ public: long extractTo(ExtractEntryProgressCallback* callback); private: - Filesystem::FilePtr m_file; + filesystem::FilePtr m_file; ArchiveFile* m_archive; std::string m_name; std::string m_destination; @@ -75,7 +74,7 @@ private: unsigned int m_compression_level; }; -} // Archive -} // DeviceAPI +} // archive +} // extension #endif /* _TIZEN_ARCHIVE_FILE_ENTRY_H_ */ diff --git a/src/archive/archive_instance.cc b/src/archive/archive_instance.cc index ef46d65b..c46c0d26 100644 --- a/src/archive/archive_instance.cc +++ b/src/archive/archive_instance.cc @@ -8,24 +8,30 @@ //#include "archive_manager.h" #include +#include #include "common/picojson.h" #include "common/logger.h" #include "common/platform_exception.h" +#include "archive_callback_data.h" +#include "archive_manager.h" +#include "archive_utils.h" - -//using namespace DeviceAPI; -//using namespace DeviceAPI::Archive; +#include "defs.h" namespace extension { namespace archive { - using namespace common; -using namespace extension::archive; + +ArchiveInstance& ArchiveInstance::getInstance() +{ + static ArchiveInstance instance; + return instance; +} ArchiveInstance::ArchiveInstance() { - LOGD("Entered"); + LoggerD("Entered"); using namespace std::placeholders; #define REGISTER_SYNC(c,x) \ @@ -49,55 +55,93 @@ ArchiveInstance::ArchiveInstance() { } ArchiveInstance::~ArchiveInstance() { - LOGD("Entered"); + LoggerD("Entered"); } void ArchiveInstance::Open(const picojson::value& args, picojson::object& out) { - LOGD("Entered"); - const std::string& file = args.get("file").get(); - - ReportSuccess(out); + LoggerD("Entered"); + LoggerD("%s", args.serialize().c_str()); + + picojson::object data = args.get(JSON_DATA).get(); + picojson::value v_file = data.at("file"); + picojson::value v_mode = data.at("mode"); + //picojson::object options = data.at("options").get(); + //picojson::value v_overwrite = options.at("overwrite"); + const double callbackId = args.get(JSON_CALLBACK_ID).get(); + const long operationId = static_cast(data.at("opId").get()); + + /* + bool overwrite = false; + if (v_overwrite.is()) { + overwrite = v_overwrite.get(); + } + */ + + FileMode fm = stringToFileMode(v_mode.get()); + const std::string& file = v_file.get(); + auto json = std::shared_ptr(new picojson::value(picojson::object())); + picojson::object& obj = json->get(); + obj[JSON_CALLBACK_ID] = picojson::value(callbackId); + + LoggerD("opId: %d", operationId); + LoggerD("filename: %s", file.c_str()); + LoggerD("callbackId: %d", callbackId); + + OpenCallbackData *callback = new OpenCallbackData(); + + NodePtr node = Node::resolve(Path::create(file)); + FilePtr file_ptr = FilePtr(new File(node, File::PermissionList())); + ArchiveFilePtr a_ptr = ArchiveFilePtr(new ArchiveFile(FileMode::READ)); + a_ptr->setFile(file_ptr); + + callback->setArchiveFile(a_ptr); + //callback->setFile(file); + callback->setOperationId(operationId); + callback->setCallbackId(callbackId); + //callback->setMode(FileMode::READ); + //callback->setJson(json); + ArchiveManager::getInstance().open(callback); } void ArchiveInstance::Abort(const picojson::value& args, picojson::object& out) { - LOGD("Entered"); + LoggerD("Entered"); ReportSuccess(out); } void ArchiveInstance::Add(const picojson::value& args, picojson::object& out) { - LOGD("Entered"); + LoggerD("Entered"); ReportSuccess(out); } void ArchiveInstance::ExtractAll(const picojson::value& args, picojson::object& out) { - LOGD("Entered"); + LoggerD("Entered"); ReportSuccess(out); } void ArchiveInstance::GetEntries(const picojson::value& args, picojson::object& out) { - LOGD("Entered"); + LoggerD("Entered"); ReportSuccess(out); } void ArchiveInstance::GetEntryByName(const picojson::value& args, picojson::object& out) { - LOGD("Entered"); + LoggerD("Entered"); ReportSuccess(out); } void ArchiveInstance::Close(const picojson::value& args, picojson::object& out) { - LOGD("Entered"); + LoggerD("Entered"); ReportSuccess(out); } void ArchiveInstance::Extract(const picojson::value& args, picojson::object& out) { - LOGD("Entered"); + LoggerD("Entered"); ReportSuccess(out); } diff --git a/src/archive/archive_instance.h b/src/archive/archive_instance.h index 534d0580..e21ec5f4 100644 --- a/src/archive/archive_instance.h +++ b/src/archive/archive_instance.h @@ -12,10 +12,14 @@ namespace archive { class ArchiveInstance: public common::ParsedInstance { public: + static ArchiveInstance& getInstance(); + +private: ArchiveInstance(); + ArchiveInstance(ArchiveInstance const&); + void operator=(ArchiveInstance const&); virtual ~ArchiveInstance(); -private: /* ArchiveManager methods */ void Open(const picojson::value& args, picojson::object& out); void Abort(const picojson::value& args, picojson::object& out); diff --git a/src/archive/archive_manager.cc b/src/archive/archive_manager.cc index 4f17bbbe..d6d4a75c 100644 --- a/src/archive/archive_manager.cc +++ b/src/archive/archive_manager.cc @@ -19,31 +19,34 @@ #include #include "common/logger.h" +#include "filesystem_file.h" -namespace DeviceAPI { -namespace Archive { +namespace extension { +namespace archive { + +using namespace filesystem; ArchiveManager::ArchiveManager(): m_next_unique_id(0) { - LOGD("Initialize ArchiveManager"); + LoggerD("Initialize ArchiveManager"); } ArchiveManager::~ArchiveManager() { - LOGD("Deinitialize ArchiveManager"); + LoggerD("Deinitialize ArchiveManager"); } ArchiveManager& ArchiveManager::getInstance() { - LOGD("Entered"); + LoggerD("Entered"); static ArchiveManager instance; return instance; } void ArchiveManager::abort(long operation_id) { - LOGD("Entered"); + LoggerD("Entered"); ArchiveFileMap::iterator it = m_archive_file_map.find(operation_id); if (it != m_archive_file_map.end()) { @@ -58,12 +61,19 @@ void ArchiveManager::abort(long operation_id) } } } - LOGD("The Operation Identifier not found"); + LoggerD("The Operation Identifier not found"); } long ArchiveManager::open(OpenCallbackData* callback) { - LOGD("Entered"); + LoggerD("Entered"); + + //ArchiveFilePtr a_ptr = callback->getArchiveFile(); +// std::string filename = callback->getFile(); +// +// NodePtr node = Node::resolve(Path::create(filename)); +// FilePtr file_ptr = FilePtr(new File(node, std::vector(), filename)); +// ArchiveFilePtr a_ptr = ArchiveFilePtr(new ArchiveFile(FileMode::READ)); ArchiveFilePtr a_ptr = callback->getArchiveFile(); return a_ptr->addOperation(callback); @@ -71,7 +81,7 @@ long ArchiveManager::open(OpenCallbackData* callback) long ArchiveManager::getNextOperationId(ArchiveFilePtr archive_file_ptr) { - LOGD("Entered"); + LoggerD("Entered"); long op_id = ++m_next_unique_id; m_archive_file_map.insert(ArchiveFilePair(op_id, archive_file_ptr)); return op_id; @@ -79,12 +89,12 @@ long ArchiveManager::getNextOperationId(ArchiveFilePtr archive_file_ptr) void ArchiveManager::eraseElementFromArchiveFileMap(long operation_id) { - LOGD("Entered"); + LoggerD("Entered"); ArchiveFileMap::iterator it = m_archive_file_map.find(operation_id); if (it != m_archive_file_map.end()) { m_archive_file_map.erase(it); } } -} // Archive -} // DeviceAPI +} // archive +} // extension diff --git a/src/archive/archive_manager.h b/src/archive/archive_manager.h index 204eb34c..00b8ea98 100755 --- a/src/archive/archive_manager.h +++ b/src/archive/archive_manager.h @@ -25,8 +25,8 @@ #include "archive_file.h" #include "archive_callback_data.h" -namespace DeviceAPI { -namespace Archive { +namespace extension { +namespace archive { typedef std::map ArchiveFileMap; typedef std::pair ArchiveFilePair; @@ -52,7 +52,7 @@ private: }; -} // Archive -} // DeviceAPI +} // archive +} // extension #endif /* _TIZEN_ARCHIVE_ARCHIVE_MANAGER_H_ */ diff --git a/src/archive/archive_utils.cc b/src/archive/archive_utils.cc index 0097a8dc..0b773d6c 100644 --- a/src/archive/archive_utils.cc +++ b/src/archive/archive_utils.cc @@ -27,10 +27,10 @@ using namespace common; -namespace DeviceAPI { -namespace Archive { +namespace extension { +namespace archive { -using namespace DeviceAPI::Filesystem; +using namespace filesystem; std::string bytesToReadableString(const size_t num_bytes) { @@ -254,5 +254,5 @@ std::string getArchiveLogMessage(const int errorCode, const std::string &hint) return std::string(ss.str()); } -} //namespace Archive -} //namespace DeviceAPI +} //namespace archive +} //namespace extension diff --git a/src/archive/archive_utils.h b/src/archive/archive_utils.h index 05eaf480..1f618646 100644 --- a/src/archive/archive_utils.h +++ b/src/archive/archive_utils.h @@ -25,8 +25,8 @@ #include "filesystem_file.h" #include "archive_file.h" -namespace DeviceAPI { -namespace Archive { +namespace extension { +namespace archive { std::string bytesToReadableString(const size_t num_bytes); std::string fileModeToString(FileMode fm); @@ -119,7 +119,7 @@ void throwArchiveException(const int errorCode, const std::string &hint) throw T(log.c_str()); } -} //namespace Archive -} //namespace DeviceAPI +} //namespace archive +} //namespace extension #endif // __TIZEN_ARCHIVE_ARCHIVE_UTILS_H__ diff --git a/src/archive/defs.h b/src/archive/defs.h index ed9f2d9b..a9880e81 100755 --- a/src/archive/defs.h +++ b/src/archive/defs.h @@ -31,6 +31,21 @@ #define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ENTRY_EXTRACT "extract" - +#define JSON_CMD "cmd" +#define JSON_ACTION "action" +#define JSON_CALLBACK_ID "cid" +#define JSON_CALLBACK_SUCCCESS "success" +#define JSON_CALLBACK_ERROR "error" +#define JSON_CALLBACK_PROGRESS "progress" +#define JSON_CALLBACK_KEEP "keep" +#define JSON_DATA "args" + +#define ARCHIVE_FILE_ATTR_MODE "mode" +#define ARCHIVE_FILE_ATTR_DECOMPRESSED_SIZE "decompressedSize" + +#define ARCHIVE_FILE_ENTRY_ATTR_NAME "name" +#define ARCHIVE_FILE_ENTRY_ATTR_SIZE "size" +#define ARCHIVE_FILE_ENTRY_ATTR_COMPRESSED_SIZE "compressedSize" +#define ARCHIVE_FILE_ENTRY_ATTR_MODIFIED "modified" #endif // _ARCHIVE_PLUGIN_DEFS_H_ diff --git a/src/archive/filesystem_file.cc b/src/archive/filesystem_file.cc index 3b4269a2..f530eb09 100644 --- a/src/archive/filesystem_file.cc +++ b/src/archive/filesystem_file.cc @@ -21,8 +21,51 @@ using namespace common; -namespace DeviceAPI { -namespace Filesystem { +namespace extension { +namespace filesystem { -} // Filesystem -} // DeviceAPI +File::File(NodePtr node, const File::PermissionList &parentPermissions, + const std::string original_location) : + m_node(node), + m_parentPerms(parentPermissions) +{ + LoggerD("original_location is fullPath: %s", original_location.c_str()); + m_original_fullpath = original_location; +} + +File::~File() +{ +} + +NodePtr File::getNode() const +{ + return m_node; +} + +File::PermissionList File::getParentPermissions() const +{ + return m_parentPerms; +} + +void File::setParentPermissions(const PermissionList &permissions) +{ + m_parentPerms = permissions; +} + +void File::pushParentPermissions(int permissions) +{ + m_parentPerms.push_back(permissions); +} + +const std::string& File::getOriginalURI() const +{ + return m_original_URI; +} + +const std::string& File::getOriginalFullPath() const +{ + return m_original_fullpath; +} + +} // filesystem +} // extension diff --git a/src/archive/filesystem_file.h b/src/archive/filesystem_file.h index 55a3bfd6..b9f0f044 100755 --- a/src/archive/filesystem_file.h +++ b/src/archive/filesystem_file.h @@ -22,97 +22,48 @@ #include #include "common/logger.h" +#include "filesystem_node.h" +#include "filesystem_path.h" -namespace DeviceAPI { -namespace Filesystem { - -enum NodeType -{ - NT_DIRECTORY, - NT_FILE -}; +namespace extension { +namespace filesystem { class File; typedef std::shared_ptr FilePtr; -typedef std::shared_ptr NodePtr; //STUB bad trick -typedef std::vector NodeList; //STUB bad trick class File : public std::enable_shared_from_this { public: - File() - { - } - - File(const std::string& fname) : - m_full_path(fname) - { - } - - FilePtr getNode() - { - LOGW("STUB"); - return shared_from_this(); - } - - size_t getSize() - { - LOGW("STUB"); - return 0; - } - - FilePtr getPath() - { - LOGW("STUB"); - return shared_from_this(); - } - - //! \brief Gets type of current node. - //! @return Node's type. - NodeType getType() const - { - LOGW("STUB"); - return NT_FILE; - } - - const std::string& getFullPath() const - { - return m_full_path; - } - - std::string m_full_path; -}; - -class Path; -typedef std::shared_ptr PathPtr; - -class Path : public std::enable_shared_from_this -{ -public: - typedef char SeparatorType; - static Path::SeparatorType getSeparator() - { - LOGW("STUB"); - return '/'; - } + typedef std::vector PermissionList; + + File(NodePtr node, + const PermissionList &parentPermissions, + const std::string original_location = std::string()); + virtual ~File(); + + NodePtr getNode() const; + PermissionList getParentPermissions() const; + void setParentPermissions(const PermissionList &permissions); + void pushParentPermissions(int permissions); + + const std::string& getOriginalURI() const; + const std::string& getOriginalFullPath() const; +private: + NodePtr m_node; + PermissionList m_parentPerms; + + std::string m_original_URI; + std::string m_original_fullpath; }; class External { public: - static std::string toVirtualPath(const std::string& path) - { - LOGW("STUB Not implemented path -> virtual path. Return not changed path"); - return path; - } - - static void removeDirectoryRecursive(const std::string& fullpath) - { - LOGW("STUB Not implemented. Directory: [%s] will not be removed!", fullpath.c_str()); - } + static std::string toVirtualPath(const std::string& path); + static void removeDirectoryRecursive(const std::string& fullpath); }; -} // Filesystem -} // DeviceAPI +} // filesystem +} // extension #endif /* _TIZEN_FILESYSTEM_FILE_H_ */ diff --git a/src/archive/filesystem_node.cc b/src/archive/filesystem_node.cc new file mode 100755 index 00000000..1784d7ca --- /dev/null +++ b/src/archive/filesystem_node.cc @@ -0,0 +1,592 @@ +// +// Tizen Web Device API +// Copyright (c) 2014 Samsung Electronics Co., Ltd. +// +// 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. +// + +/** + * @file Node.cpp + */ + +#include "filesystem_node.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "filesystem_path.h" +#include "common/logger.h" +#include "common/platform_exception.h" + +namespace extension { +namespace filesystem { + +using namespace common; + +#define MAX_NODE_LENGTH 256 +bool Node::checkPermission(const PathPtr &path, const std::string &mode, NodeType type) +{ + switch (type) + { + case NT_DIRECTORY: + { + DIR* dir = opendir(path->getFullPath().c_str()); + + if (!dir) { + LoggerW("throw InvalidValuesException"); + throw InvalidValuesException("Node has been deleted from platform."); + } + + if (closedir(dir) != 0) { + LoggerW("throw InvalidValuesException"); + throw InvalidValuesException("Could not close platform node."); + } + + if (mode == "r") + return true; + + std::stringstream ss; + time_t now; + time(&now); + ss << now; + PathPtr tempFilePath = Path::create(path->getFullPath()); + tempFilePath->append(ss.str()); + try + { + createAsFileInternal(tempFilePath); + removeAsFile(tempFilePath); + } + catch (const PlatformException& ex) + { + LoggerW("Exception: %s", ex.message().c_str()); + return false; + } + + if (mode == "rw" || mode == "w" || mode == "a") { + return true; + } + LoggerW("throw InvalidValuesException"); + throw InvalidValuesException("invalid mode"); + } + break; + case NT_FILE: + { + std::fstream stream; + std::ios_base::openmode modeBit = std::fstream::binary; + + if (mode == "r") + { + modeBit |= std::fstream::in; + } + else if (mode == "rw" || mode == "w" || mode == "a") + { + modeBit |= std::fstream::app; + } + else + { + LoggerW("throw InvalidValuesException"); + throw InvalidValuesException("invalid mode"); + } + + stream.open(path->getFullPath().c_str(), modeBit); + + if (stream.is_open()) + { + stream.close(); + return true; + } + return false; + } + break; + } + return false; +} + +NodePtr Node::resolve(const PathPtr& path) +{ + LoggerD("Entered path:[%s]", path->getFullPath().c_str()); + + struct stat info; + struct stat syminfo; + + if (lstat(path->getFullPath().c_str(), &info) != 0) { + LoggerE("File:[%s] error no:%d", path->getFullPath().c_str(), errno); + + switch (errno) + { + case EACCES: + LoggerW("throw InvalidValuesException for file:[%s]", path->getFullPath().c_str()); + throw InvalidValuesException("Node access denied"); + break; + case ENOENT: + LoggerW("throw NotFoundException for file:[%s]", path->getFullPath().c_str()); + throw NotFoundException("NotFoundError"); + break; + default: + LoggerW("throw IOException for file:[%s]", path->getFullPath().c_str()); + throw IOException("Platform exception fail"); + } + } + + if (!S_ISDIR(info.st_mode) & !S_ISREG(info.st_mode) && !S_ISLNK(info.st_mode)) { + LoggerW("throw IOException for file:[%s]", path->getFullPath().c_str()); + throw IOException("Platform node is of unsupported type."); + } + + NodeType type = S_ISDIR(info.st_mode) ? NT_DIRECTORY : NT_FILE; + + if (S_ISLNK(info.st_mode)) { + syminfo = stat(path); + + type = S_ISDIR(syminfo.st_mode) ? NT_DIRECTORY : NT_FILE; + LoggerD("%x", type); + } + + auto result = std::shared_ptr(new Node(path, type)); + + LoggerD("Finished execution for file:[%s] type:%s", path->getFullPath().c_str(), + type == NT_DIRECTORY ? "directory" : "file"); + return result; +} + +PathPtr Node::getPath() const +{ + return Path::create(m_path->getFullPath()); +} + +NodePtr Node::getChild(const PathPtr& path) +{ + if (m_type != NT_DIRECTORY) { + LoggerW("throw IOException"); + throw IOException("Not a directory."); + } + return Node::resolve(*m_path + *path); +} + +NodeType Node::getType() const +{ + return m_type; +} + +int Node::getPermissions() const +{ + return m_perms; +} + +void Node::setPermissions(int perms) +{ + m_perms = perms; +} + +Node::NameList Node::getChildNames() const +{ + if (m_type != NT_DIRECTORY) { + LoggerW("throw IOException"); + throw IOException("Node is not directory."); + } + + if ((m_perms & PERM_READ) == 0) { + LoggerW("throw InvalidValuesException"); + throw InvalidValuesException("No permission."); + } + + DIR* dir = opendir(m_path->getFullPath().c_str()); + if (!dir) { + LoggerW("throw IOException"); + throw IOException("Node has been deleted from platform."); + } + + NameList result; + errno = 0; + struct dirent *entry = NULL; + while ((entry = readdir(dir))) { + if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { + continue; + } + result.push_back(entry->d_name); + } + if (errno != 0) { + LoggerW("throw IOException"); + throw IOException("Error while reading directory."); + } + + if (closedir(dir) != 0) { + LoggerW("throw IOException"); + throw IOException("Could not close platform node."); + } + + return result; +} + +NodeList Node::getChildNodes() const +{ + if (m_type != NT_DIRECTORY) { + LoggerW("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); + LoggerW("throw IOException"); + throw IOException("Node is not directory."); + LoggerW("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); + } + + if ((m_perms & PERM_READ) == 0) { + LoggerW("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); + LoggerW("throw InvalidValuesException"); + throw InvalidValuesException("No permission."); + } + + DIR* dir = opendir(m_path->getFullPath().c_str()); + if (!dir) { + LoggerW("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); + LoggerW("throw IOException"); + throw IOException("Node has been deleted from platform."); + } + + errno = 0; + NodeList result; + struct dirent *entry = NULL; + while ((entry = readdir(dir))) { + if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { + continue; + } + try { + NodePtr node = Node::resolve(*m_path + entry->d_name); + node->setPermissions(getPermissions()); // inherit access rights + result.push_back(node); + } + catch (const PlatformException& ex) + { + LoggerW("caught BasePlatformException ignored"); + } + } + + if (errno != 0) { + LoggerW("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); + LoggerW("throw IOException"); + throw IOException("Error while reading directory."); + } + + if (closedir(dir) != 0) { + LoggerW("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); + LoggerW("throw IOException"); + throw IOException("Could not close platform node."); + } + + return result; +} + +NodePtr Node::createChild( + const PathPtr& path, + NodeType type, + int options) +{ + if (m_type != NT_DIRECTORY) { + LoggerW("throw IOException"); + throw IOException("Parent node is not a directory."); + } + + if ((m_perms & PERM_WRITE) == 0) { + LoggerW("throw InvalidValuesException"); + throw InvalidValuesException("Not enough permissions."); + } + + PathPtr childPath = *m_path + *path; + if (exists(childPath)) { + LoggerW("throw IOException"); + throw IOException("Node already exists."); + } + + NodePtr result; + switch (type) { + case NT_FILE: + result = createAsFile(childPath, options); + break; + case NT_DIRECTORY: + result = createAsDirectory(childPath, options); + break; + default: + LoggerW("throw IOException"); + throw IOException("Unsupported node type."); + } + if (!!result) { + result->m_perms = m_perms; + } else { + LoggerW("throw IOException"); + throw IOException("Node creation error"); + } + + return result; +} + +void Node::remove(int options) +{ + switch (m_type) { + case NT_FILE: + removeAsFile(m_path); + break; + case NT_DIRECTORY: + removeAsDirectory(m_path, (options & OPT_RECURSIVE)); + break; + default: + LoggerE("throw UnknownError"); + throw UnknownException("Not supported value of m_type"); + } +} + +unsigned long long Node::getSize() const +{ + if (m_type == NT_DIRECTORY) { + LoggerW("throw IOException"); + throw IOException("Getting size for directories is not supported."); + } + + struct stat info = stat(m_path); + if (!S_ISREG(info.st_mode)) { + LoggerW("throw IOException"); + throw IOException("Specified node is not a regular file."); + } + + return info.st_size; +} + +std::time_t Node::getCreated() const +{ + return stat(m_path).st_ctime; +} + +std::time_t Node::getModified() const +{ + return stat(m_path).st_mtime; +} + +// TODO Optimize it, maybe store a flag indicating that node is a root. +NodePtr Node::getParent() const +{ +// LocationPaths roots = Manager::getInstance().getLocationPaths(); +// for (LocationPaths::iterator it = roots.begin(); it != roots.end(); ++it) { +// if (*(*it) == *m_path) { +// return NodePtr(); +// } +// } + NodePtr parent = Node::resolve(Path::create(m_path->getPath())); + parent->setPermissions(getPermissions()); + return parent; +} + +int Node::getMode() const +{ + int result = 0; + struct stat info = stat(m_path); + if (info.st_mode & S_IRUSR) { result |= PM_USER_READ; } + if (info.st_mode & S_IWUSR) { result |= PM_USER_WRITE; } + if (info.st_mode & S_IXUSR) { result |= PM_USER_EXEC; } + if (info.st_mode & S_IRGRP) { result |= PM_GROUP_READ; } + if (info.st_mode & S_IWGRP) { result |= PM_GROUP_WRITE; } + if (info.st_mode & S_IXGRP) { result |= PM_GROUP_EXEC; } + if (info.st_mode & S_IROTH) { result |= PM_OTHER_READ; } + if (info.st_mode & S_IWOTH) { result |= PM_OTHER_WRITE; } + if (info.st_mode & S_IXOTH) { result |= PM_OTHER_EXEC; } + return result; +} + +bool Node::exists(const PathPtr& path) +{ + struct stat info; + memset(&info, 0, sizeof(struct stat)); + int status = lstat(path->getFullPath().c_str(), &info); + + if (0 == status) + { + return true; + } + else if (ENAMETOOLONG == errno) + { + LoggerW("throw IOException"); + throw IOException("file name is too long"); + } + else if (errno != ENOENT) + { + return true; + } + return false; +} + +struct stat Node::stat(const PathPtr& path) +{ + struct stat result; + memset(&result, 0, sizeof(struct stat)); + if (::stat(path->getFullPath().c_str(), + &result) != 0) + { + LoggerE("File: %s", path->getFullPath().c_str()); + LoggerW("throw IOException"); + throw IOException("Node does not exist or no access"); + } + return result; +} + +Node::Node(const PathPtr& path, NodeType type): + m_path(path), + m_type(type), + m_perms(PERM_NONE) +{ +} + +NodePtr Node::createAsFile(const PathPtr& path, + int /* options */) +{ + createAsFileInternal(path); + return std::shared_ptr(new Node(path, NT_FILE)); +} + +void Node::createAsFileInternal(const PathPtr& path) +{ + FILE* file = std::fopen(path->getFullPath().c_str(), "wb"); + if (!file) { + LoggerW("fopen fails IOException throw for path [%s]", + path->getFullPath().c_str()); + throw IOException("Platform node could not be created."); + } + std::fclose(file); +} + +NodePtr Node::createAsDirectory(const PathPtr& path, + int options) +{ +// if (options & OPT_RECURSIVE) { +// auto parts = Utils::getParts(path); +// for (auto it = parts.begin(); it != parts.end(); ++it) { +// if (!exists(*it)) { createAsDirectoryInternal(*it); } +// } +// } + createAsDirectoryInternal(path); + return std::shared_ptr(new Node(path, NT_DIRECTORY)); +} + +void Node::createAsDirectoryInternal(const PathPtr& path) +{ + if (mkdir(path->getFullPath().c_str(), S_IRWXU | S_IRWXG | S_IROTH | + S_IXOTH) != 0) { + LoggerW("throw IOException"); + throw IOException("Platform node could not be created."); + } +} + +void Node::removeAsFile(const PathPtr& path) +{ + auto fullPath = path->getFullPath(); + if (unlink(fullPath.c_str()) != 0) { + LoggerW("remove [%s]", fullPath.c_str()); + LoggerW("throw IOException"); + throw IOException("Error while removing platform node."); + } +} + +void Node::removeAsDirectory(const PathPtr& path, + bool recursive) +{ + if (recursive) { + DIR* dir = opendir(path->getFullPath().c_str()); + if (!dir) { + LoggerW("File %s", path->getFullPath().c_str()); + LoggerW("throw IOException"); + throw IOException("Node does not exist or access denied."); + } + errno = 0; + struct dirent *entry = NULL; + while ((entry = readdir(dir))) { + if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { + continue; + } + PathPtr subPath = *path + entry->d_name; + struct stat info; + memset(&info, 0, sizeof(struct stat)); + if (lstat(subPath->getFullPath().c_str(), &info) == 0) { + try { + if (S_ISDIR(info.st_mode)) { + removeAsDirectory(subPath, true); + } else if (S_ISREG(info.st_mode)) { + removeAsFile(subPath); + } + } + catch (const PlatformException& ex) + { + } + // TODO: Not sure if above exception should be swallowed. + } + } + closedir(dir); + } + + errno = 0; + if (rmdir(path->getFullPath().c_str()) != 0) { + if (errno == EEXIST) { + LoggerW("throw IOException"); + throw IOException("Node has child nodes."); + } + LoggerW("throw IOException"); + throw IOException("Error while removing platform node."); + } +} + +std::string Node::toUri(int /*widgetId*/) const +{ + // TODO I believe moving this feature to WrtWrapper would make more sense. + return "file://" + m_path->getFullPath(); +} + +bool Node::isSubPath(std::string aDirPath, PathPtr aFilePath) +{ + auto myPath = aDirPath; + if(!myPath.empty() && myPath[myPath.length()-1] != Path::getSeparator()) { + myPath += Path::getSeparator(); + LoggerD("updated aDirPath to:%s", aDirPath.c_str()); + } + + auto childPath = aFilePath->getFullPath(); + bool isSubP = strncmp(myPath.c_str(), childPath.c_str(), myPath.size()) == 0; + + LoggerD("aDirPath:%s myPath:%s aFilePath:%s isSubP:%d", + aDirPath.c_str(), + myPath.c_str(), + aFilePath->getFullPath().c_str(), + isSubP); + + return isSubP; +} + +bool Node::isSubPath(PathPtr aPath) const +{ + LoggerD("Entered thisPath:%s aPath: %s", + this->getPath()->getFullPath().c_str(), + aPath->getFullPath().c_str()); + + resolve(aPath); + + bool isSubP = isSubPath(m_path->getFullPath(), aPath); + LoggerD("thisPath:%s aPath: %s isSubP:%d", + this->getPath()->getFullPath().c_str(), + aPath->getFullPath().c_str(), + isSubP); + return isSubP; +} + +} +} diff --git a/src/archive/filesystem_node.h b/src/archive/filesystem_node.h new file mode 100644 index 00000000..04109a7a --- /dev/null +++ b/src/archive/filesystem_node.h @@ -0,0 +1,251 @@ +// +// Tizen Web Device API +// Copyright (c) 2014 Samsung Electronics Co., Ltd. +// +// 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. +// + +/** + * @file Node.h + */ + +#ifndef _FILESYSTEM_NODE_H_ +#define _FILESYSTEM_NODE_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace extension { +namespace filesystem { + +enum LocationType +{ + LT_APPS, + LT_DOCUMENTS, + LT_DOWNLOADS, + LT_GAMES, + LT_IMAGES, + LT_OTHERS, + LT_ROOT, + LT_SDCARD, + LT_USBHOST, + LT_SOUNDS, + LT_TEMP, + LT_VIDEOS, + LT_RINGTONES, + LT_WGTPKG, + LT_WGTPRV, + LT_WGTPRVTMP, + LT_CAMERA +}; + +enum NodeType +{ + NT_DIRECTORY, + NT_FILE +}; + +enum AccessMode +{ + AM_READ = 0x0001, + AM_WRITE = 0x0002, + AM_READ_WRITE = 0x0003, + AM_APPEND = 0x0004 +}; + +/** + * Used in @see Manager::access(). + */ +enum AccessType +{ + AT_EXISTS = 0x0000, //!< AT_EXISTS - checks for existence + AT_READ = 0x0001, //!< AT_READ - checks for read access + AT_WRITE = 0x0002, //!< AT_WRITE - checks for write access + AT_EXEC = 0x0004 //!< AT_EXEC - checks for execution access +}; + +enum Permissions +{ + PERM_NONE = 0x0000, + PERM_READ = 0x0001, + PERM_WRITE = 0x0002 +}; + +enum PlatformMode +{ + PM_USER_READ = 0x0100, + PM_USER_WRITE = 0x0080, + PM_USER_EXEC = 0x0040, + PM_GROUP_READ = 0x0020, + PM_GROUP_WRITE = 0x0010, + PM_GROUP_EXEC = 0x0008, + PM_OTHER_READ = 0x0004, + PM_OTHER_WRITE = 0x0002, + PM_OTHER_EXEC = 0x0001, + PM_NONE = 0x0000 +}; + +enum Options +{ + OPT_NONE = 0x0000, + OPT_OVERWRITE = 0x0001, + OPT_RECURSIVE = 0x0002 +}; + +enum FindFilter +{ + FF_NAME, + FF_CREATED, + FF_MODIFIED, + FF_SIZE +}; +typedef std::map FiltersMap; + +class Node; +typedef std::shared_ptr NodePtr; +typedef std::vector NodeList; +typedef NodeList::iterator NodeListIterator; + +class Path; +typedef std::shared_ptr PathPtr; + +class Node : public std::enable_shared_from_this +{ +public: + typedef std::vector NameList; + typedef NameList::iterator NameListIterator; + + //! \brief Resolves Path into Node + //! + //! This function creates Node wich represent folder or file + //! in file system. + //! @return Node smart pointer + static NodePtr resolve(const PathPtr& path); + //! \brief Checks if path can be accessed + //! + //! Function opens path and base at reqested mode and type verifies access + //! priviliges. If type is NT_DIRECTORY, then functions open directory. + //! If mode is readonly, then function returns true. If mode is other than + //! "r", then function checksm, if write is possible. If type is NT_FILE, + //! then function open file for read mode for "r" mode! and for R/W + //! for other mode. + //! + //! @param path virtual path in filesystem + //! @param mode access mode: "r", "rw" + //! @param type folder or file + //! @return true if access is granted, false if not + bool checkPermission(const PathPtr& path, + const std::string& mode, + NodeType type); + //! \brief Gets path of current node. + //! @return Node's path. + PathPtr getPath() const; + //! \brief Gets type of current node. + //! @return Node's type. + NodeType getType() const; + //! \brief Gets permissions of the virtual node (not real filesystem node). + //! @return Node's permissions. + int getPermissions() const; + //! \brief Sets permissions on the virtual node (not real filesystem node). + //! @param perms Node's permissions @see Api::Filesystem::Permissions. + void setPermissions(int perms); + //! \brief Gets size of this node. + //! @return Size. + unsigned long long getSize() const; + //! \brief Gets creation date of this node. + //! @return Date. + std::time_t getCreated() const; + //! \brief Gets last modification date of this node. + //! @return Date. + std::time_t getModified() const; + //! \brief Gets parent of this node. + //! @return Parent node or NULL if no parent (e.g. in case of a root node). + NodePtr getParent() const; + //! \brief Gets platform permissions. + //! @return Platform permissions (set of flags from @see Permissions enum). + int getMode() const; + //! \brief Gets direct child of this node. + //! @param path Path to the child node. + //! @return Ptr to the child node. + //! @remarks Ownership passed to the caller. + NodePtr getChild(const PathPtr& path); + //! \brief Gets list of names of direct child nodes. + //! @return Names of child nodes. + NameList getChildNames() const; + //! \brief Gets list of direct child nodes. + //! @return Child nodes. + //! @remarks Ownership passed to the caller. + //! @deprecated + NodeList getChildNodes() const; + //! \brief Creates child of current node. + //! @param path Path to the node to create. + //! @param type Type of the node @see Api::Filesystem::NodeType. + //! @param options Additional options see remarks (no options by default). + //! @return Ptr to newly created node. + //! @remarks + //! Valid options: + //! - OPT_RECURSIVE - attempt to create all necessary sub-directories + NodePtr createChild( + const PathPtr& path, + NodeType, + int options = OPT_NONE); + //! \brief Removes underlying filesystem node. + //! @param options Removal options (by default removal is recursive). + //! @remarks Synchronous. + //! Valid options: + //! - OPT_RECURSIVE - remove node recursively. + void remove(int options); + + std::string toUri(int widgetId) const; + + bool isSubPath(PathPtr aPath) const; + static bool isSubPath(std::string aDirPath, PathPtr aFilePath); + +private: + static bool exists(const PathPtr& path); + static struct stat stat(const PathPtr& path); + + Node(const PathPtr& path, + NodeType type); + + NodePtr createAsFile(const PathPtr& path, + int options); + void createAsFileInternal(const PathPtr& path); + + NodePtr createAsDirectory(const PathPtr& path, + int options); + void createAsDirectoryInternal(const PathPtr& path); + + void removeAsFile(const PathPtr& path); + void removeAsDirectory(const PathPtr& path, + bool recursive); + + PathPtr m_path; + NodeType m_type; + int m_perms; + +}; + +} // extension +} // filesystem + +#endif /* _FILESYSTEM_NODE_H_ */ + diff --git a/src/archive/filesystem_path.cc b/src/archive/filesystem_path.cc new file mode 100755 index 00000000..c234b781 --- /dev/null +++ b/src/archive/filesystem_path.cc @@ -0,0 +1,174 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// 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. +// + +/** + * @file Path.cpp + */ + +#include +#include +#include +#include +#include + +#include "filesystem_path.h" + +#include "common/platform_exception.h" +#include "common/logger.h" + +namespace extension { +namespace filesystem { + +using namespace common; + +const Path::SeparatorType Path::m_pathSeparator = '/'; + +PathPtr Path::create(const std::string& path) +{ + auto result = std::shared_ptr(new Path()); + result->reset(path); + return result; +} + +std::string Path::getFullPath() const +{ + return m_fullPath; +} + +std::string Path::getPath() const +{ + return m_path; +} + +std::string Path::getName() const +{ + return m_name; +} + +PathPtr Path::append(const std::string& path) +{ + reset(m_fullPath + m_pathSeparator + path); + return shared_from_this(); +} + +PathPtr Path::append(const PathPtr& path) +{ + reset(m_fullPath + m_pathSeparator + path->getFullPath()); + return shared_from_this(); +} + +bool Path::isAbsolute() const +{ + return (!m_fullPath.empty() && (m_fullPath[0] == m_pathSeparator)); +} + +Path::SeparatorType Path::getSeparator() +{ + return m_pathSeparator; +} + +bool Path::isValid(const std::string& str) +{ + return !str.empty(); +} + +PathPtr Path::clone() const +{ + return Path::create(m_fullPath); +} + +Path::Path() +{ +} + +void Path::reset(const std::string& str) +{ + if (!isValid(str)) { + LoggerD("Invalid string %s", str.c_str()); + LoggerW("throw NotFoundException"); + throw NotFoundException("Invalid path"); + } +// std::string tmp = Commons::String::unique(/*Commons::String::trim*/( +// str), m_pathSeparator); + std::string tmp = str; + + if (m_pathSeparator == tmp.back()) { + tmp.erase(tmp.end() - 1, tmp.end()); + } + std::string::size_type pos = tmp.find_last_of(m_pathSeparator); + if (std::string::npos == pos) { + m_fullPath = m_name = tmp; + m_path.clear(); + } else { + if (0 == pos) { + m_fullPath = m_path = m_pathSeparator; + } else { + m_fullPath = m_path = tmp.substr(0, pos); + m_fullPath += m_pathSeparator; + } + m_name = tmp.substr(pos + 1); + m_fullPath += m_name; + } +} + +PathPtr operator+(const Path& lhs, const Path& rhs) +{ + return Path::create(lhs.getFullPath())->append(rhs.getFullPath()); +} + +PathPtr operator+(const Path& lhs, const std::string& rhs) +{ + return Path::create(lhs.getFullPath())->append(rhs); +} + +PathPtr operator+(const std::string& lhs, const Path& rhs) +{ + return Path::create(lhs)->append(rhs.getFullPath()); +} + +bool operator==(const Path& lhs, const Path& rhs) +{ + return (lhs.getFullPath() == rhs.getFullPath()); +} + +bool operator==(const Path& lhs, const std::string& rhs) +{ + return (lhs.getFullPath() == rhs); +} + +bool operator==(const std::string& lhs, const Path& rhs) +{ + return (lhs == rhs.getFullPath()); +} + +bool operator!=(const Path& lhs, const Path& rhs) +{ + return (lhs.getFullPath() != rhs.getFullPath()); +} + +bool operator!=(const Path& lhs, const std::string& rhs) +{ + return (lhs.getFullPath() != rhs); +} + +bool operator!=(const std::string& lhs, const Path& rhs) +{ + return (lhs != rhs.getFullPath()); +} + +} // filesystem +} // extension diff --git a/src/archive/filesystem_path.h b/src/archive/filesystem_path.h new file mode 100644 index 00000000..4150111b --- /dev/null +++ b/src/archive/filesystem_path.h @@ -0,0 +1,86 @@ +// +// Tizen Web Device API +// Copyright (c) 2014 Samsung Electronics Co., Ltd. +// +// 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. +// + +/** + * @file Path.h + */ + +#ifndef _FILESYSTEM_PATH_H_ +#define _FILESYSTEM_PATH_H_ + +#include +#include +#include + +namespace extension { +namespace filesystem { + +class Path; +typedef std::shared_ptr PathPtr; + +class Path : public std::enable_shared_from_this +{ +public: + typedef char SeparatorType; + static PathPtr create(const std::string& path); + static Path::SeparatorType getSeparator(); + std::string getFullPath() const; + std::string getPath() const; + std::string getName() const; + PathPtr append(const std::string& path); + PathPtr append(const PathPtr& path); + bool isAbsolute() const; + PathPtr clone() const; + +private: + /** + * Checks whether specified string is a valid path. + * @param path String to verify. + * @return True when string is a valid path, false otherwise. + */ + static bool isValid(const std::string& str); + Path(); + void reset(const std::string& str); + static const SeparatorType m_pathSeparator; ///< Path separator. + std::string m_fullPath; ///< Full path. + std::string m_path; ///< Base path. + std::string m_name; ///< Last part of the path. +}; + +PathPtr operator+(const Path& lhs, const Path& rhs); + +PathPtr operator+(const Path& lhs, const std::string& rhs); + +PathPtr operator+(const std::string& lhs, const Path& rhs); + +bool operator==(const Path& lhs, const Path& rhs); + +bool operator==(const Path& lhs, const std::string& rhs); + +bool operator==(const std::string& lhs, const Path& rhs); + +bool operator!=(const Path& lhs, const Path& rhs); + +bool operator!=(const Path& lhs, const std::string& rhs); + +bool operator!=(const std::string& lhs, const Path& rhs); + + +} // filesystem +} // extension + +#endif /* _FILESYSTEM_PATH_H_ */ diff --git a/src/archive/un_zip.cc b/src/archive/un_zip.cc index 3b0ebc93..525571ec 100644 --- a/src/archive/un_zip.cc +++ b/src/archive/un_zip.cc @@ -33,10 +33,10 @@ #include "archive_utils.h" #include "un_zip_extract_request.h" -using namespace common; +namespace extension { +namespace archive { -namespace DeviceAPI { -namespace Archive { +using namespace common; UnZip::UnZip(const std::string& filename) : m_zipfile_name(filename), @@ -225,26 +225,26 @@ void UnZip::extractTo(ExtractEntryProgressCallback* callback) throw UnknownException("Extract archive file entry failed"); } - Filesystem::FilePtr out_dir = callback->getDirectory(); + filesystem::FilePtr out_dir = callback->getDirectory(); if(!out_dir) { LOGE("Output directory is not valid"); throw InvalidValuesException("Output directory is not correct"); } -// Filesystem::NodePtr out_node = out_dir->getNode(); +// filesystem::NodePtr out_node = out_dir->getNode(); // if(!out_node) { // LOGE("Output directory is not valid"); // throw InvalidValuesException("Output directory is not correct"); // } // -// Filesystem::PathPtr out_path = out_node->getPath(); +// filesystem::PathPtr out_path = out_node->getPath(); // if(!out_path) { // LOGE("Output directory is not valid"); // throw InvalidValuesException("Output directory is not correct"); // } auto entry_name_in_zip = callback->getArchiveFileEntry()->getName(); - auto root_output_path = out_dir->getFullPath(); + auto root_output_path = out_dir->getNode()->getPath()->getFullPath(); LOGD("Extract: [%s] to root output directory: [%s] (stripBasePath: [%s])", entry_name_in_zip.c_str(), root_output_path.c_str(), @@ -422,5 +422,5 @@ void UnZip::updateCallbackWithArchiveStatistics(ExtractAllProgressCallback* call astats.number_of_folders); } -} //namespace Archive -} //namespace DeviceAPI +} //namespace archive +} //namespace extension diff --git a/src/archive/un_zip.h b/src/archive/un_zip.h index 0ccbe24d..eac7deff 100644 --- a/src/archive/un_zip.h +++ b/src/archive/un_zip.h @@ -27,8 +27,8 @@ #include "archive_callback_data.h" #include "archive_file_entry.h" -namespace DeviceAPI { -namespace Archive { +namespace extension { +namespace archive { class UnZipExtractRequest; @@ -93,7 +93,7 @@ private: friend class UnZipExtractRequest; }; -} //namespace Archive -} //namespace DeviceAPI +} //namespace archive +} //namespace extension #endif // __TIZEN_ARCHIVE_ZIP_H__ diff --git a/src/archive/un_zip_extract_request.cc b/src/archive/un_zip_extract_request.cc index fdcb1e4a..3ac57814 100644 --- a/src/archive/un_zip_extract_request.cc +++ b/src/archive/un_zip_extract_request.cc @@ -34,10 +34,10 @@ #include "archive_utils.h" #include "un_zip.h" -using namespace common; +namespace extension { +namespace archive { -namespace DeviceAPI { -namespace Archive { +using namespace common; FilePathStatus getPathStatus(const std::string& path) { @@ -92,7 +92,7 @@ void createMissingDirectories(const std::string& path, bool check_first = true) //LOGD("left_part: [%s] status:%d", left_part.c_str(), status); if(FPS_DIRECTORY != status) { - //TODO investigate 0775 (mode) - Filesystem assumed that file should have parent mode + //TODO investigate 0775 (mode) - filesystem assumed that file should have parent mode if(mkdir(left_part.c_str(), 0775) == -1) { LOGE("Couldn't create new directory: %s errno:%s", left_part.c_str(), strerror(errno)); @@ -326,7 +326,7 @@ bool UnZipExtractRequest::prepareOutputSubdirectory() } //Try to create new directory in output directory - //TODO investigate 0775 (mode) - Filesystem assumed that file should have parent mode + //TODO investigate 0775 (mode) - filesystem assumed that file should have parent mode if(mkdir(m_new_dir_path.c_str(), 0775) == -1) { LOGW("couldn't create new directory: %s errno:%s", m_new_dir_path.c_str(), strerror(errno)); @@ -354,10 +354,10 @@ bool UnZipExtractRequest::prepareOutputSubdirectory() if(FPS_DIRECTORY == output_fstatus) { try { LOGW("STUB Not removing directory"); - //Filesystem::PathPtr path = Filesystem::Path::create(m_output_filepath); - //Filesystem::NodePtr node = Filesystem::Node::resolve(path); - //node->remove(Filesystem::OPT_RECURSIVE); - Filesystem::External::removeDirectoryRecursive(m_output_filepath); + //filesystem::PathPtr path = filesystem::Path::create(m_output_filepath); + //filesystem::NodePtr node = filesystem::Node::resolve(path); + //node->remove(filesystem::OPT_RECURSIVE); + filesystem::External::removeDirectoryRecursive(m_output_filepath); LOGD("Removed directory: [%s]", m_output_filepath.c_str()); } catch(PlatformException& ex) { @@ -504,5 +504,5 @@ void UnZipExtractRequest::handleFileEntry() changeFileAccessAndModifyDate(m_output_filepath, m_file_info.tmu_date); } -} //namespace Archive -} //namespace DeviceAPI +} //namespace archive +} //namespace extension diff --git a/src/archive/un_zip_extract_request.h b/src/archive/un_zip_extract_request.h index 3612021f..c78789a6 100644 --- a/src/archive/un_zip_extract_request.h +++ b/src/archive/un_zip_extract_request.h @@ -22,8 +22,8 @@ #include #include "un_zip.h" -namespace DeviceAPI { -namespace Archive { +namespace extension { +namespace archive { enum FilePathStatus { FPS_NOT_EXIST = 0, @@ -79,7 +79,7 @@ private: std::string m_new_dir_path; }; -} //namespace Archive -} //namespace DeviceAPI +} //namespace archive +} //namespace extension #endif // __TIZEN_ARCHIVE_UNZIP_EXTRACT_REQUEST_H__ diff --git a/src/archive/zip.cc b/src/archive/zip.cc index 26b536de..12ba7127 100644 --- a/src/archive/zip.cc +++ b/src/archive/zip.cc @@ -32,10 +32,10 @@ #include "crypt.h" #include "zip_add_request.h" -using namespace common; +namespace extension { +namespace archive { -namespace DeviceAPI { -namespace Archive { +using namespace common; void Zip::generateZipFileInfo(const std::string& filename, zip_fileinfo& out_zi) { @@ -139,5 +139,5 @@ void Zip::addFile(AddProgressCallback*& callback) ZipAddRequest::execute(*this, callback); } -} //namespace Archive -} //namespace DeviceAPI +} //namespace archive +} //namespace extension diff --git a/src/archive/zip.h b/src/archive/zip.h index 5a65c1f2..3fb0807b 100644 --- a/src/archive/zip.h +++ b/src/archive/zip.h @@ -25,8 +25,8 @@ #include "archive_callback_data.h" -namespace DeviceAPI { -namespace Archive { +namespace extension { +namespace archive { class ZipAddRequest; @@ -70,7 +70,7 @@ private: friend class ZipAddRequest; }; -} //namespace Archive -} //namespace DeviceAPI +} //namespace archive +} //namespace extension #endif // __TIZEN_ARCHIVE_ZIP_H__ diff --git a/src/archive/zip_add_request.cc b/src/archive/zip_add_request.cc index 6ad5c6fa..ac045159 100644 --- a/src/archive/zip_add_request.cc +++ b/src/archive/zip_add_request.cc @@ -26,8 +26,8 @@ using namespace common; -namespace DeviceAPI { -namespace Archive { +namespace extension { +namespace archive { ZipAddRequest::ZipAddRequest(Zip& owner, AddProgressCallback*& callback) : m_owner(owner), @@ -92,10 +92,10 @@ void ZipAddRequest::run() //We just need read permission to list files in subdirectories LOGW("STUB Not setting PERM_READ permissions"); - //m_root_src_file_node->setPermissions(Filesystem::PERM_READ); + //m_root_src_file_node->setPermissions(filesystem::PERM_READ); std::string src_basepath, src_name; - getBasePathAndName(m_root_src_file_node->getFullPath(), src_basepath, + getBasePathAndName(m_root_src_file_node->getPath()->getFullPath(), src_basepath, src_name); m_absoulte_path_to_extract = src_basepath; @@ -127,7 +127,7 @@ void ZipAddRequest::run() // Generate list of files and all subdirectories // - Filesystem::NodeList all_sub_nodes; + filesystem::NodeList all_sub_nodes; addNodeAndSubdirsToList(m_root_src_file_node, all_sub_nodes); if(m_callback->isCanceled()) { @@ -144,13 +144,13 @@ void ZipAddRequest::run() for(auto it = all_sub_nodes.begin(); it != all_sub_nodes.end(); ++it, ++i) { unsigned long long size = 0; - if((*it)->getType() == Filesystem::NT_FILE) { + if((*it)->getType() == filesystem::NT_FILE) { size = (*it)->getSize(); m_bytes_to_compress += size; ++m_files_to_compress; } - LOGD("[%d] : [%s] --zip--> [%s] | size: %s", i, (*it)->getFullPath().c_str(), + LOGD("[%d] : [%s] --zip--> [%s] | size: %s", i, (*it)->getPath()->getFullPath().c_str(), getNameInZipArchiveFor(*it, m_callback->getFileEntry()->getStriped()).c_str(), bytesToReadableString(size).c_str()); } @@ -174,12 +174,12 @@ void ZipAddRequest::run() m_callback = NULL; } -void ZipAddRequest::addNodeAndSubdirsToList(Filesystem::NodePtr src_node, - Filesystem::NodeList& out_list_of_child_nodes) +void ZipAddRequest::addNodeAndSubdirsToList(filesystem::NodePtr src_node, + filesystem::NodeList& out_list_of_child_nodes) { out_list_of_child_nodes.push_back(src_node); - if(Filesystem::NT_DIRECTORY == src_node->getType()) { + if(filesystem::NT_DIRECTORY == src_node->getType()) { LOGW("STUB Not generating recursive list of files in directory"); //auto child_nodes = src_node->getChildNodes(); //for(auto it = child_nodes.begin(); it != child_nodes.end(); ++it) { @@ -273,11 +273,11 @@ void ZipAddRequest::addEmptyDirectoryToZipArchive(std::string name_in_zip) m_new_file_in_zip_opened = false; } -void ZipAddRequest::addToZipArchive(Filesystem::NodePtr src_file_node) +void ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) { const std::string name_in_zip = getNameInZipArchiveFor(src_file_node, m_callback->getFileEntry()->getStriped()); - const std::string src_file_path = src_file_node->getFullPath(); + const std::string src_file_path = src_file_node->getPath()->getFullPath(); LOGD("Compress: [%s] to zip archive as: [%s]", src_file_path.c_str(), name_in_zip.c_str()); @@ -289,7 +289,7 @@ void ZipAddRequest::addToZipArchive(Filesystem::NodePtr src_file_node) LOGE("WARNING: Previous new file in zip archive is opened!"); int err = zipCloseFileInZip(m_owner.m_zip); if (ZIP_OK != err) { - LOGE("%s",getArchiveLogMessage(err, "zipCloseFileInZip()").c_str()); + LOGE("zipCloseFileInZip failed with error: %d", err); } } @@ -318,8 +318,8 @@ void ZipAddRequest::addToZipArchive(Filesystem::NodePtr src_file_node) NULL, 0); if (err != ZIP_OK) { - LOGE("ret: %d", err); - throwArchiveException(err, "zipOpenNewFileInZip3()"); + LOGE("Error opening new file: [%s] in zipfile", name_in_zip.c_str()); + throw UnknownException("Could not add new file to zip archive"); } m_new_file_in_zip_opened = true; @@ -330,17 +330,12 @@ void ZipAddRequest::addToZipArchive(Filesystem::NodePtr src_file_node) m_input_file = NULL; } - //Filesystem::File::PermissionList perm_list; - //Filesystem::FilePtr cur_file(new Filesystem::File(src_file_node, perm_list)); - - LOGW("STUB ignore src_file_node and PermissionList"); - Filesystem::FilePtr cur_file(new Filesystem::File(src_file_path)); + filesystem::File::PermissionList perm_list; + filesystem::FilePtr cur_file(new filesystem::File(src_file_node, perm_list)); ArchiveFileEntryPtr cur_afentry(new ArchiveFileEntry(cur_file)); cur_afentry->setCompressionLevel(m_compression_level); cur_afentry->setName(name_in_zip); - - LOGW("STUB Not setting Modified"); - //cur_afentry->setModified(src_file_node->getModified()); + cur_afentry->setModified(src_file_node->getModified()); auto entry = m_callback->getFileEntry(); cur_afentry->setDestination(entry->getDestination()); @@ -353,7 +348,7 @@ void ZipAddRequest::addToZipArchive(Filesystem::NodePtr src_file_node) LOGD("m_files_compressed:%d / m_files_to_compress: %d", m_files_compressed, m_files_to_compress); - if(src_file_node->getType() == Filesystem::NT_FILE) { + if(src_file_node->getType() == filesystem::NT_FILE) { m_input_file = fopen(src_file_path.c_str(), "rb"); if (!m_input_file) { LOGE("Error opening source file:%s", src_file_path.c_str()); @@ -444,7 +439,7 @@ void ZipAddRequest::addToZipArchive(Filesystem::NodePtr src_file_node) err = zipCloseFileInZip(m_owner.m_zip); if (ZIP_OK != err) { - LOGE("%s",getArchiveLogMessage(err, "zipCloseFileInZip()").c_str()); + LOGE("Error in closing added file:%s in zipfile", src_file_path.c_str()); } m_new_file_in_zip_opened = false; @@ -497,7 +492,7 @@ std::string generateFullPathForZip(const std::string& path) return out; } -std::string ZipAddRequest::getNameInZipArchiveFor(Filesystem::NodePtr node, bool strip) +std::string ZipAddRequest::getNameInZipArchiveFor(filesystem::NodePtr node, bool strip) { const std::string node_full_path = node->getPath()->getFullPath(); std::string cut_path; @@ -518,7 +513,7 @@ std::string ZipAddRequest::getNameInZipArchiveFor(Filesystem::NodePtr node, bool } std::string name = generateFullPathForZip(m_destination_path_in_zip + "/" + cut_path); - if(node->getType() == Filesystem::NT_DIRECTORY) { + if(node->getType() == filesystem::NT_DIRECTORY) { if(name.length() > 0 && name[name.length()-1] != '/' && name[name.length()-1] != '\\') { @@ -530,5 +525,5 @@ std::string ZipAddRequest::getNameInZipArchiveFor(Filesystem::NodePtr node, bool return name; } -} //namespace Archive -} //namespace DeviceAPI +} //namespace archive +} //namespace extension diff --git a/src/archive/zip_add_request.h b/src/archive/zip_add_request.h index 081ba8c2..0bfd4e58 100644 --- a/src/archive/zip_add_request.h +++ b/src/archive/zip_add_request.h @@ -26,8 +26,8 @@ #include "archive_callback_data.h" #include "zip.h" -namespace DeviceAPI { -namespace Archive { +namespace extension { +namespace archive { class ZipAddRequest { @@ -45,13 +45,13 @@ private: ZipAddRequest(Zip& owner, AddProgressCallback*& callback); void run(); - void addNodeAndSubdirsToList(Filesystem::NodePtr src_node, - Filesystem::NodeList& out_list_of_child_nodes); + void addNodeAndSubdirsToList(filesystem::NodePtr src_node, + filesystem::NodeList& out_list_of_child_nodes); void addEmptyDirectoryToZipArchive(std::string name_in_zip); - void addToZipArchive(Filesystem::NodePtr src_file_node); + void addToZipArchive(filesystem::NodePtr src_file_node); - std::string getNameInZipArchiveFor(Filesystem::NodePtr node, bool strip); + std::string getNameInZipArchiveFor(filesystem::NodePtr node, bool strip); //----------------------------------------------------------------------------- //Input request variables @@ -70,8 +70,8 @@ private: unsigned long m_files_compressed; unsigned long long m_bytes_compressed; - Filesystem::FilePtr m_root_src_file; - Filesystem::NodePtr m_root_src_file_node; + filesystem::FilePtr m_root_src_file; + filesystem::NodePtr m_root_src_file_node; std::string m_absoulte_path_to_extract; std::string m_destination_path_in_zip; @@ -80,7 +80,7 @@ private: bool m_new_file_in_zip_opened; }; -} //namespace Archive -} //namespace DeviceAPI +} //namespace archive +} //namespace extension #endif // __TIZEN_ARCHIVE_ZIP_ADD_REQUEST_H__