From b726cb89e57c6eb4e8b5742f6351db3ddb09bd10 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Wed, 11 Jan 2023 13:39:50 +0800 Subject: [PATCH 01/25] add watchFileObserver Signed-off-by: Cao Chuan --- .../properties/watcher_observer.cpp | 199 ++++++++++++++++++ .../mod_fileio/properties/watcher_observer.h | 63 ++++++ 2 files changed, 262 insertions(+) create mode 100644 interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp new file mode 100644 index 000000000..18abab0d0 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2021 Huawei Device 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. + */ +#include "watcher_observer.h" +#include "../../log.h" +#include +#include +#include +#include +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; +bool WatcherObserver::isRunning_ = false; +int WatcherObserver::inotifyFd_ = 0; +std::mutex WatcherObserver::eventLock_; +std::vector WatcherObserver::watcherFileInfos_; +const int BUF_SIZE = 1024; + +void WatcherObserver::WatcherFileInfo::SetPath(const std::string &path) +{ + path_ = path; +} + +std::string WatcherObserver::WatcherFileInfo::GetPath() +{ + return path_; +} + +void WatcherObserver::WatcherFileInfo::SetWd(const int &wd) +{ + wd_ = wd; +} + +int WatcherObserver::WatcherFileInfo::GetWd() +{ + return wd_; +} + +void WatcherObserver::WatcherFileInfo::SetWatchEvents(const std::vector &events) +{ + events_.assign(events.begin(), events.end()); +} + +std::vector WatcherObserver::WatcherFileInfo::GetWatchEvents() +{ + return events_; +} + +bool WatcherObserver::StartObserver() +{ + isRunning_ = true; + inotifyFd_ = inotify_init(); + if (inotifyFd_ == -1) { + HILOGE("MtpFileObserver inotify_init false"); + return false; + } else { + inotifySuccess_ = true; + return true; + } +} + +bool WatcherObserver::StopObserver() +{ + isRunning_ = false; + for (auto fileInfo : watcherFileInfos_) { + if (inotify_rm_watch(inotifyFd_, fileInfo.GetWd()) == -1) { + HILOGE("MtpFileObserver StopFileInotify inotify_rm_watch error"); + return false; + } + } + close(inotifyFd_); + startThread_ = false; + inotifySuccess_ = false; + inotifyFd_ = 0; + return true; +} + +bool WatcherObserver::AddInotifyEvents(const int &inotifyFd) +{ + char eventBuf[BUF_SIZE] = {0}; + + int ret = read(inotifyFd, eventBuf, sizeof(eventBuf)); + if (ret < (int)sizeof(struct inotify_event)) { + HILOGE("MtpFileObserver AddInotifyEvents no event"); + return false; + } + + struct inotify_event *positionEvent = (struct inotify_event *)eventBuf; + struct inotify_event *event; + while (ret >= (int)sizeof(struct inotify_event)) { + lock_guard lock(eventLock_); + event = positionEvent; + if (event->len) { + for (auto watcherFileInfo : watcherFileInfos_) { + if (watcherFileInfo.GetWd() == event->wd) { + vector events = watcherFileInfo.GetWatchEvents(); + for (auto iter = events.begin(); iter != events.end(); ++iter) { + if (event->mask == *iter) { + // todo添加回调 + } + } + } + } + } + positionEvent++; + ret -= (int)sizeof(struct inotify_event); + } + return true; +} + +bool WatcherObserver::WatchPathThread() +{ + while (isRunning_) { + if (watcherFileInfos_.size() > 0) { + AddInotifyEvents(inotifyFd_); + } + } + return true; +} + +// todo 参数添加回调 +void WatcherObserver::AddObserver(const std::string &path, const std::vector &watchEvents) +{ + if (!inotifySuccess_) { + StartObserver(); + } + if (inotifySuccess_) { + if (!path.empty() && watchEvents.size() > 0) { + uint32_t event = 0; + for (auto watchEvent : watchEvents) { + event = event | watchEvent; + } + int wd = inotify_add_watch(inotifyFd_, path.c_str(), event); + + WatcherObserver::WatcherFileInfo fileInfo; + fileInfo.SetWd(wd); + fileInfo.SetPath(path); + fileInfo.SetWatchEvents(watchEvents); + watcherFileInfos_.push_back(fileInfo); + } + } + if (!startThread_) { + std::thread watchThread(WatchPathThread); + watchThread.detach(); + startThread_ = true; + } +} + +bool WatcherObserver::IsOnlyWatcherFileInfo(const std::string &path) +{ + int count = 0; + for (auto watcherFileInfo : watcherFileInfos_) { + if (strcmp(path.c_str(), watcherFileInfo.GetPath().c_str()) == 0) { + count++; + } + if (count > 1) { + return false; + } + } + if (count == 0) { + return false; + } + return true; +} + +// todo 参数添加回调 +void WatcherObserver::RemoveObserver(const std::string &path, const std::vector &watchEvents) +{ + + bool isOnly = IsOnlyWatcherFileInfo(path); + for (auto iter = watcherFileInfos_.begin(); iter != watcherFileInfos_.end(); ++iter) { + if (isOnly) { + if (inotify_rm_watch(inotifyFd_, iter->GetWd()) == -1) { + HILOGE("MtpFileObserver StopFileInotify inotify_rm_watch error"); + return; + } + } + watcherFileInfos_.erase(iter); + } + + if (watcherFileInfos_.size() == 0) { + StopObserver(); + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h new file mode 100644 index 000000000..68ba4c61d --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021 Huawei Device 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. + */ +#ifndef WATCHER_OBSERVER_H +#define WATCHER_OBSERVER_H +#include "singleton.h" +#include +#include +#include +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class WatcherObserver : public Singleton { +public: + // todo 添加回调 + void AddObserver(const std::string &path, const std::vector &watchEvents); + void RemoveObserver(const std::string &path, const std::vector &watchEvents); + class WatcherFileInfo { + public: + void SetWd(const int &wd); + int32_t GetWd(); + + void SetPath(const std::string &path); + std::string GetPath(); + + void SetWatchEvents(const std::vector &events); + std::vector GetWatchEvents(); + + private: + int wd_; + std::string path_; + std::vector events_; + }; + +private: + bool StartObserver(); + bool StopObserver(); + bool IsOnlyWatcherFileInfo(const std::string &path); + static bool AddInotifyEvents(const int &inotifyFd); + static bool WatchPathThread(); + static bool isRunning_; + static std::vector watcherFileInfos_; + static std::mutex eventLock_; + static int inotifyFd_; + + bool startThread_; + bool inotifySuccess_; +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file -- Gitee From 327fafd41b3f2fa2de5647ba45dc9989ddb78d55 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Wed, 11 Jan 2023 13:52:01 +0800 Subject: [PATCH 02/25] modify log Signed-off-by: Cao Chuan --- .../js/src/mod_fileio/properties/watcher_observer.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp index 18abab0d0..4da9ddb61 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp @@ -63,7 +63,7 @@ bool WatcherObserver::StartObserver() isRunning_ = true; inotifyFd_ = inotify_init(); if (inotifyFd_ == -1) { - HILOGE("MtpFileObserver inotify_init false"); + HILOGE("WatcherObserver inotify_init false"); return false; } else { inotifySuccess_ = true; @@ -76,7 +76,7 @@ bool WatcherObserver::StopObserver() isRunning_ = false; for (auto fileInfo : watcherFileInfos_) { if (inotify_rm_watch(inotifyFd_, fileInfo.GetWd()) == -1) { - HILOGE("MtpFileObserver StopFileInotify inotify_rm_watch error"); + HILOGE("WatcherObserver StopFileInotify inotify_rm_watch error"); return false; } } @@ -93,7 +93,7 @@ bool WatcherObserver::AddInotifyEvents(const int &inotifyFd) int ret = read(inotifyFd, eventBuf, sizeof(eventBuf)); if (ret < (int)sizeof(struct inotify_event)) { - HILOGE("MtpFileObserver AddInotifyEvents no event"); + HILOGE("WatcherObserver AddInotifyEvents no event"); return false; } @@ -183,7 +183,7 @@ void WatcherObserver::RemoveObserver(const std::string &path, const std::vector< for (auto iter = watcherFileInfos_.begin(); iter != watcherFileInfos_.end(); ++iter) { if (isOnly) { if (inotify_rm_watch(inotifyFd_, iter->GetWd()) == -1) { - HILOGE("MtpFileObserver StopFileInotify inotify_rm_watch error"); + HILOGE("WatcherObserver StopFileInotify inotify_rm_watch error"); return; } } -- Gitee From 672b151eac050c96fef9ef561c8b6c3bd7446066 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Thu, 12 Jan 2023 09:33:32 +0800 Subject: [PATCH 03/25] add callback Signed-off-by: Cao Chuan --- .../js/src/mod_fileio/properties/watcher.cpp | 8 +++- .../js/src/mod_fileio/properties/watcher.h | 9 ++++ .../mod_fileio/properties/watcher_callback.h | 24 ++++++++++ .../properties/watcher_observer.cpp | 45 ++++++++++--------- .../mod_fileio/properties/watcher_observer.h | 17 +++++-- 5 files changed, 77 insertions(+), 26 deletions(-) create mode 100644 interfaces/kits/js/src/mod_fileio/properties/watcher_callback.h diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp index b822f9a3c..ce477b402 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp @@ -36,8 +36,8 @@ using namespace std; void Watcher::RunCommand(uv_fs_event_t *handle, const char *filename, int events, int status) { WatcherInforArg *information = (WatcherInforArg *)handle->data; - uint32_t eventsFirst { events }; - uint32_t eventsSecond { information->events }; + uint32_t eventsFirst{events}; + uint32_t eventsSecond{information->events}; if (eventsFirst & eventsSecond) { napi_handle_scope scope = nullptr; napi_open_handle_scope(information->env, &scope); @@ -101,6 +101,10 @@ napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) return objWatcher; } + +void WatcherEventCallback::OnChanged(const std::string &path, const uint32_t &event) { + //todo 添加napi +} } // namespace ModuleFileIO } // namespace DistributedFS } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.h b/interfaces/kits/js/src/mod_fileio/properties/watcher.h index 45c100cb2..4a2d0a9ba 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.h +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.h @@ -18,6 +18,7 @@ #include #include "../../common/napi/n_val.h" +#include "watcher_callback.h" namespace OHOS { namespace DistributedFS { @@ -29,6 +30,14 @@ public: private: static void RunCommand(uv_fs_event_t *handle, const char *filename, int events, int status); }; + +class WatcherEventCallback : public WatcherCallback +{ +public: + void OnChanged(const std::string &path, const uint32_t &event); +private: + +}; } // namespace ModuleFileIO } // namespace DistributedFS } // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_callback.h b/interfaces/kits/js/src/mod_fileio/properties/watcher_callback.h new file mode 100644 index 000000000..db24fa623 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher_callback.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2021 Huawei Device 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. + */ +#ifndef WATCHER_CALLBACK_H +#define WATCHER_CALLBACK_H +#include +class WatcherCallback +{ +public: + virtual ~WatcherCallback() = default; + virtual void OnChanged(const std::string &path, const uint32_t &event) = 0; +}; +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp index 4da9ddb61..e1d434f4f 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp @@ -22,10 +22,11 @@ namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { using namespace std; + bool WatcherObserver::isRunning_ = false; int WatcherObserver::inotifyFd_ = 0; std::mutex WatcherObserver::eventLock_; -std::vector WatcherObserver::watcherFileInfos_; +std::map WatcherObserver::watcherFileMaps_; const int BUF_SIZE = 1024; void WatcherObserver::WatcherFileInfo::SetPath(const std::string &path) @@ -74,8 +75,8 @@ bool WatcherObserver::StartObserver() bool WatcherObserver::StopObserver() { isRunning_ = false; - for (auto fileInfo : watcherFileInfos_) { - if (inotify_rm_watch(inotifyFd_, fileInfo.GetWd()) == -1) { + for (auto fileInfo : watcherFileMaps_) { + if (inotify_rm_watch(inotifyFd_, fileInfo.second.GetWd()) == -1) { HILOGE("WatcherObserver StopFileInotify inotify_rm_watch error"); return false; } @@ -103,12 +104,13 @@ bool WatcherObserver::AddInotifyEvents(const int &inotifyFd) lock_guard lock(eventLock_); event = positionEvent; if (event->len) { - for (auto watcherFileInfo : watcherFileInfos_) { - if (watcherFileInfo.GetWd() == event->wd) { - vector events = watcherFileInfo.GetWatchEvents(); + for (auto watcherFileInfo : watcherFileMaps_) { + WatcherObserver::WatcherFileInfo info = watcherFileInfo.second; + if (info.GetWd() == event->wd) { + vector events = info.GetWatchEvents(); for (auto iter = events.begin(); iter != events.end(); ++iter) { if (event->mask == *iter) { - // todo添加回调 + watcherFileInfo.first->OnChanged(info.GetPath(), event->mask); } } } @@ -123,15 +125,16 @@ bool WatcherObserver::AddInotifyEvents(const int &inotifyFd) bool WatcherObserver::WatchPathThread() { while (isRunning_) { - if (watcherFileInfos_.size() > 0) { + if (watcherFileMaps_.size() > 0) { AddInotifyEvents(inotifyFd_); } } return true; } -// todo 参数添加回调 -void WatcherObserver::AddObserver(const std::string &path, const std::vector &watchEvents) +void WatcherObserver::AddObserver(const std::string &path, + const std::vector &watchEvents, + const WatcherCallbackPtr &callback) { if (!inotifySuccess_) { StartObserver(); @@ -144,11 +147,11 @@ void WatcherObserver::AddObserver(const std::string &path, const std::vector 1) { @@ -175,22 +178,24 @@ bool WatcherObserver::IsOnlyWatcherFileInfo(const std::string &path) return true; } -// todo 参数添加回调 -void WatcherObserver::RemoveObserver(const std::string &path, const std::vector &watchEvents) +void WatcherObserver::RemoveObserver(const std::string &path, + const std::vector &watchEvents, + const WatcherCallbackPtr &callback) { bool isOnly = IsOnlyWatcherFileInfo(path); - for (auto iter = watcherFileInfos_.begin(); iter != watcherFileInfos_.end(); ++iter) { + auto iter = watcherFileMaps_.find(callback); + if (iter != watcherFileMaps_.end()) { if (isOnly) { - if (inotify_rm_watch(inotifyFd_, iter->GetWd()) == -1) { + if (inotify_rm_watch(inotifyFd_, iter->second.GetWd()) == -1) { HILOGE("WatcherObserver StopFileInotify inotify_rm_watch error"); return; } } - watcherFileInfos_.erase(iter); + watcherFileMaps_.erase(iter); } - if (watcherFileInfos_.size() == 0) { + if (watcherFileMaps_.size() == 0) { StopObserver(); } } diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h index 68ba4c61d..1376ad65e 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h @@ -15,17 +15,26 @@ #ifndef WATCHER_OBSERVER_H #define WATCHER_OBSERVER_H #include "singleton.h" +#include "watcher_callback.h" +#include +#include #include #include #include namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { +using WatcherCallbackPtr = std::shared_ptr; + class WatcherObserver : public Singleton { public: - // todo 添加回调 - void AddObserver(const std::string &path, const std::vector &watchEvents); - void RemoveObserver(const std::string &path, const std::vector &watchEvents); + void AddObserver(const std::string &path, + const std::vector &watchEvents, + const WatcherCallbackPtr &callback); + void RemoveObserver(const std::string &path, + const std::vector &watchEvents, + const WatcherCallbackPtr &callback); + class WatcherFileInfo { public: void SetWd(const int &wd); @@ -50,7 +59,7 @@ private: static bool AddInotifyEvents(const int &inotifyFd); static bool WatchPathThread(); static bool isRunning_; - static std::vector watcherFileInfos_; + static std::map watcherFileMaps_; static std::mutex eventLock_; static int inotifyFd_; -- Gitee From 623aa654dec3cad6c0f1f23951a2287bc6aceb0c Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Fri, 13 Jan 2023 10:50:10 +0800 Subject: [PATCH 04/25] modify napi Signed-off-by: Cao Chuan --- interfaces/kits/js/BUILD.gn | 1 + interfaces/kits/js/src/common/napi/n_val.cpp | 22 ++++++++++++ interfaces/kits/js/src/common/napi/n_val.h | 4 ++- .../mod_fileio/class_watcher/watcher_entity.h | 9 ++++- .../js/src/mod_fileio/properties/watcher.cpp | 36 ++++++------------- .../js/src/mod_fileio/properties/watcher.h | 3 -- .../properties/watcher_observer.cpp | 21 +++++++++-- .../mod_fileio/properties/watcher_observer.h | 6 ++-- 8 files changed, 67 insertions(+), 35 deletions(-) diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 4a67419f1..d9828f4d7 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -87,6 +87,7 @@ ohos_shared_library("fileio") { "src/mod_fileio/properties/symlink.cpp", "src/mod_fileio/properties/truncate.cpp", "src/mod_fileio/properties/watcher.cpp", + "src/mod_fileio/properties/watcher_observer.cpp" ] deps = [ diff --git a/interfaces/kits/js/src/common/napi/n_val.cpp b/interfaces/kits/js/src/common/napi/n_val.cpp index d05ff5221..c3c31cbef 100644 --- a/interfaces/kits/js/src/common/napi/n_val.cpp +++ b/interfaces/kits/js/src/common/napi/n_val.cpp @@ -131,6 +131,13 @@ tuple NVal::ToDouble() const return make_tuple(status == napi_ok, res); } +tuple NVal::ToUint32() const +{ + uint32_t res = 0; + napi_status status = napi_get_value_uint32(env_, val_, &res); + return make_tuple(status == napi_ok, res); +} + tuple NVal::ToUint64() const { uint64_t res = 0; @@ -154,6 +161,21 @@ tuple, uint32_t> NVal::ToStringArray() return make_tuple(status == napi_ok, stringArray, size); } +tuple, uint32_t> NVal::ToUint32Array() +{ + napi_status status; + uint32_t size; + status = napi_get_array_length(env_, val_, &size); + vector uint32Array; + napi_value result; + for (uint32_t i = 0; i < size; i++) { + status = napi_get_element(env_, val_, i, &result); + auto [succ, uint32] = NVal(env_, result).ToUint32(); + uint32Array.push_back(uint32); + } + return make_tuple(status == napi_ok, uint32Array, size); +} + tuple NVal::ToArraybuffer() const { void *buf = nullptr; diff --git a/interfaces/kits/js/src/common/napi/n_val.h b/interfaces/kits/js/src/common/napi/n_val.h index 8fd57dc37..73b3c5616 100644 --- a/interfaces/kits/js/src/common/napi/n_val.h +++ b/interfaces/kits/js/src/common/napi/n_val.h @@ -47,9 +47,11 @@ public: std::tuple ToArraybuffer() const; std::tuple ToTypedArray() const; std::tuple, uint32_t> ToStringArray(); + std::tuple, uint32_t> ToUint32Array(); std::tuple ToUint64() const; + std::tuple ToUint32() const; std::tuple ToDouble() const; - + /* Static helpers to create js objects */ static NVal CreateUndefined(napi_env env); static NVal CreateBigInt64(napi_env env, int64_t val); diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h index ce604ee6b..e7fc997ad 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h @@ -23,6 +23,11 @@ namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { +#include +#include +#include +#include "../properties/watcher_callback.h" + class WatcherHandleDeleter { public: void operator()(uv_fs_event_t *ptr) @@ -38,7 +43,9 @@ public: }; struct WatcherInforArg { - int events = 0; + std::string filename; + std::vector events; + std::shared_ptr callbackPtr; napi_env env = nullptr; napi_ref ref = nullptr; }; diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp index ce477b402..ef68887b9 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp @@ -28,30 +28,12 @@ #include "../class_watcher/watcher_entity.h" #include "../class_watcher/watcher_n_exporter.h" +#include "watcher_callback.h" namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { using namespace std; -void Watcher::RunCommand(uv_fs_event_t *handle, const char *filename, int events, int status) -{ - WatcherInforArg *information = (WatcherInforArg *)handle->data; - uint32_t eventsFirst{events}; - uint32_t eventsSecond{information->events}; - if (eventsFirst & eventsSecond) { - napi_handle_scope scope = nullptr; - napi_open_handle_scope(information->env, &scope); - napi_value callback = nullptr; - napi_get_reference_value(information->env, information->ref, &callback); - vector argv; - argv.push_back(NVal::CreateInt64(information->env, events).val_); - napi_value global = nullptr; - napi_get_global(information->env, &global); - napi_value tmp = nullptr; - napi_call_function(information->env, global, callback, argv.size(), argv.data(), &tmp); - } -} - napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); @@ -66,23 +48,27 @@ napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) return nullptr; } - auto [succGetEvent, event] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + auto [succGetEvent, events, size] = NVal(env, funcArg[NARG_POS::SECOND]).ToUint32Array(); if (!succGetEvent) { UniError(EINVAL).ThrowErr(env, "Invalid event"); return nullptr; } + std::shared_ptr eventCallbackPtr = std::make_shared(); unique_ptr data = make_unique(); - data->events = event; + data->events = events; data->env = env; + data->callbackPtr = eventCallbackPtr; + data->filename = string(filename.get()); + NVal val = NVal(env, funcArg[NARG_POS::THIRD]); napi_create_reference(val.env_, val.val_, 1, &(data->ref)); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(env, &loop); + + unique_ptr fsEventReq(new uv_fs_event_t); - uv_fs_event_init(loop, fsEventReq.get()); + fsEventReq->data = data.get(); - uv_fs_event_start(fsEventReq.get(), RunCommand, filename.get(), UV_FS_EVENT_RECURSIVE); + napi_value objWatcher = NClass::InstantiateClass(env, WatcherNExporter::className_, {}); if (!objWatcher) { diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.h b/interfaces/kits/js/src/mod_fileio/properties/watcher.h index 4a2d0a9ba..531340e42 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.h +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.h @@ -26,9 +26,6 @@ namespace ModuleFileIO { class Watcher final { public: static napi_value CreateWatcher(napi_env env, napi_callback_info info); - -private: - static void RunCommand(uv_fs_event_t *handle, const char *filename, int events, int status); }; class WatcherEventCallback : public WatcherCallback diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp index e1d434f4f..a41cc459b 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp @@ -61,12 +61,14 @@ std::vector WatcherObserver::WatcherFileInfo::GetWatchEvents() bool WatcherObserver::StartObserver() { + HILOGI("WatcherObserver StartObserver IN"); isRunning_ = true; inotifyFd_ = inotify_init(); if (inotifyFd_ == -1) { HILOGE("WatcherObserver inotify_init false"); return false; } else { + HILOGI("WatcherObserver StartObserver Success"); inotifySuccess_ = true; return true; } @@ -74,6 +76,7 @@ bool WatcherObserver::StartObserver() bool WatcherObserver::StopObserver() { + HILOGI("WatcherObserver StopObserver IN"); isRunning_ = false; for (auto fileInfo : watcherFileMaps_) { if (inotify_rm_watch(inotifyFd_, fileInfo.second.GetWd()) == -1) { @@ -85,11 +88,13 @@ bool WatcherObserver::StopObserver() startThread_ = false; inotifySuccess_ = false; inotifyFd_ = 0; + HILOGI("WatcherObserver StopObserver OUT"); return true; } bool WatcherObserver::AddInotifyEvents(const int &inotifyFd) { + HILOGI("WatcherObserver AddInotifyEvents IN %{public}d", inotifyFd); char eventBuf[BUF_SIZE] = {0}; int ret = read(inotifyFd, eventBuf, sizeof(eventBuf)); @@ -107,9 +112,13 @@ bool WatcherObserver::AddInotifyEvents(const int &inotifyFd) for (auto watcherFileInfo : watcherFileMaps_) { WatcherObserver::WatcherFileInfo info = watcherFileInfo.second; if (info.GetWd() == event->wd) { + HILOGI("WatcherObserver AddInotifyEvents path:%{public}s wd:%{public}d", info.GetPath().c_str(), + event->wd); vector events = info.GetWatchEvents(); for (auto iter = events.begin(); iter != events.end(); ++iter) { if (event->mask == *iter) { + HILOGI("WatcherObserver AddInotifyEvents1 path:%{public}s wd:%{public}d", + info.GetPath().c_str(), info.GetWd()); watcherFileInfo.first->OnChanged(info.GetPath(), event->mask); } } @@ -119,16 +128,22 @@ bool WatcherObserver::AddInotifyEvents(const int &inotifyFd) positionEvent++; ret -= (int)sizeof(struct inotify_event); } + HILOGI("WatcherObserver AddInotifyEvents OUT"); return true; } bool WatcherObserver::WatchPathThread() { + HILOGI("WatcherObserver WatchPathThread IN"); while (isRunning_) { if (watcherFileMaps_.size() > 0) { - AddInotifyEvents(inotifyFd_); + bool ret = AddInotifyEvents(inotifyFd_); + if (!ret) { + return false; + } } } + HILOGI("WatcherObserver WatchPathThread OUT"); return true; } @@ -136,6 +151,7 @@ void WatcherObserver::AddObserver(const std::string &path, const std::vector &watchEvents, const WatcherCallbackPtr &callback) { + HILOGI("WatcherObserver AddObserver IN"); if (!inotifySuccess_) { StartObserver(); } @@ -151,7 +167,7 @@ void WatcherObserver::AddObserver(const std::string &path, fileInfo.SetWd(wd); fileInfo.SetPath(path); fileInfo.SetWatchEvents(watchEvents); - watcherFileMaps_.insert(make_pair(callback,fileInfo)); + watcherFileMaps_.insert(make_pair(callback, fileInfo)); } } if (!startThread_) { @@ -159,6 +175,7 @@ void WatcherObserver::AddObserver(const std::string &path, watchThread.detach(); startThread_ = true; } + HILOGI("WatcherObserver AddObserver OUT"); } bool WatcherObserver::IsOnlyWatcherFileInfo(const std::string &path) diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h index 1376ad65e..b33539f15 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h @@ -14,19 +14,19 @@ */ #ifndef WATCHER_OBSERVER_H #define WATCHER_OBSERVER_H -#include "singleton.h" -#include "watcher_callback.h" #include #include #include #include #include +#include "watcher_callback.h" + namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { using WatcherCallbackPtr = std::shared_ptr; -class WatcherObserver : public Singleton { +class WatcherObserver { public: void AddObserver(const std::string &path, const std::vector &watchEvents, -- Gitee From f45020e0d8c40b467f89318e8ec94df392421b4c Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Fri, 13 Jan 2023 17:08:07 +0800 Subject: [PATCH 05/25] OnChange add error Signed-off-by: Cao Chuan --- interfaces/kits/js/src/common/uni_error.h | 5 +++- .../js/src/mod_fileio/properties/watcher.cpp | 2 +- .../js/src/mod_fileio/properties/watcher.h | 2 +- .../mod_fileio/properties/watcher_callback.h | 2 +- .../properties/watcher_observer.cpp | 25 +++++++++++-------- .../mod_fileio/properties/watcher_observer.h | 8 +++--- 6 files changed, 24 insertions(+), 20 deletions(-) diff --git a/interfaces/kits/js/src/common/uni_error.h b/interfaces/kits/js/src/common/uni_error.h index b9d2b7a30..4918dc7f4 100644 --- a/interfaces/kits/js/src/common/uni_error.h +++ b/interfaces/kits/js/src/common/uni_error.h @@ -81,7 +81,9 @@ enum ErrCodeSuffix { E_BADFD, E_RESTART, E_DQUOT, - E_UKERR + E_UKERR, + E_WATHCER_INIT, + E_WATCHER_SUCCESS }; const std::unordered_map> errCodeTable { @@ -126,6 +128,7 @@ const std::unordered_map> errCodeTable { { EBADFD, { FILEIO_SYS_CAP_TAG + E_BADFD, "File descriptor in bad state" } }, { ERESTART, { FILEIO_SYS_CAP_TAG + E_RESTART, "Interrupted system call should be restarted" } }, { EDQUOT, { FILEIO_SYS_CAP_TAG + E_DQUOT, "Quota exceeded" } }, + { E_WATHCER_INIT, { FILEIO_SYS_CAP_TAG + E_WATHCER_INIT, "Watcher init error" } }, { -1, { FILEIO_SYS_CAP_TAG + E_UKERR, "Unknown error" } } }; diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp index ef68887b9..bc5bb0777 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp @@ -88,7 +88,7 @@ napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) return objWatcher; } -void WatcherEventCallback::OnChanged(const std::string &path, const uint32_t &event) { +void WatcherEventCallback::OnChanged(const int &err, const std::string &path, const uint32_t &event) { //todo 添加napi } } // namespace ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.h b/interfaces/kits/js/src/mod_fileio/properties/watcher.h index 531340e42..705dae53d 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.h +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.h @@ -31,7 +31,7 @@ public: class WatcherEventCallback : public WatcherCallback { public: - void OnChanged(const std::string &path, const uint32_t &event); + void OnChanged(const int &err, const std::string &path, const uint32_t &event); private: }; diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_callback.h b/interfaces/kits/js/src/mod_fileio/properties/watcher_callback.h index db24fa623..ed822807c 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher_callback.h +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher_callback.h @@ -19,6 +19,6 @@ class WatcherCallback { public: virtual ~WatcherCallback() = default; - virtual void OnChanged(const std::string &path, const uint32_t &event) = 0; + virtual void OnChanged(const int &err, const std::string &path, const uint32_t &event) = 0; }; #endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp index a41cc459b..91b9b8ac3 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp @@ -13,11 +13,12 @@ * limitations under the License. */ #include "watcher_observer.h" -#include "../../log.h" #include #include #include #include +#include "../../log.h" +#include "../../common/uni_error.h" namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { @@ -28,7 +29,8 @@ int WatcherObserver::inotifyFd_ = 0; std::mutex WatcherObserver::eventLock_; std::map WatcherObserver::watcherFileMaps_; const int BUF_SIZE = 1024; - +const uint32_t NONE_EVENT = 0; +const uint32_t SUCCESS = 0; void WatcherObserver::WatcherFileInfo::SetPath(const std::string &path) { path_ = path; @@ -92,12 +94,12 @@ bool WatcherObserver::StopObserver() return true; } -bool WatcherObserver::AddInotifyEvents(const int &inotifyFd) +bool WatcherObserver::AddInotifyEvents() { - HILOGI("WatcherObserver AddInotifyEvents IN %{public}d", inotifyFd); + HILOGI("WatcherObserver AddInotifyEvents IN"); char eventBuf[BUF_SIZE] = {0}; - int ret = read(inotifyFd, eventBuf, sizeof(eventBuf)); + int ret = read(inotifyFd_, eventBuf, sizeof(eventBuf)); if (ret < (int)sizeof(struct inotify_event)) { HILOGE("WatcherObserver AddInotifyEvents no event"); return false; @@ -119,7 +121,7 @@ bool WatcherObserver::AddInotifyEvents(const int &inotifyFd) if (event->mask == *iter) { HILOGI("WatcherObserver AddInotifyEvents1 path:%{public}s wd:%{public}d", info.GetPath().c_str(), info.GetWd()); - watcherFileInfo.first->OnChanged(info.GetPath(), event->mask); + watcherFileInfo.first->OnChanged(SUCCESS, info.GetPath(), event->mask); } } } @@ -137,7 +139,7 @@ bool WatcherObserver::WatchPathThread() HILOGI("WatcherObserver WatchPathThread IN"); while (isRunning_) { if (watcherFileMaps_.size() > 0) { - bool ret = AddInotifyEvents(inotifyFd_); + bool ret = AddInotifyEvents(); if (!ret) { return false; } @@ -153,7 +155,10 @@ void WatcherObserver::AddObserver(const std::string &path, { HILOGI("WatcherObserver AddObserver IN"); if (!inotifySuccess_) { - StartObserver(); + bool startRet = StartObserver(); + if(!startRet) { + callback->OnChanged(ErrCodeSuffix::E_WATHCER_INIT, path , NONE_EVENT); + } } if (inotifySuccess_) { if (!path.empty() && watchEvents.size() > 0) { @@ -195,9 +200,7 @@ bool WatcherObserver::IsOnlyWatcherFileInfo(const std::string &path) return true; } -void WatcherObserver::RemoveObserver(const std::string &path, - const std::vector &watchEvents, - const WatcherCallbackPtr &callback) +void WatcherObserver::RemoveObserver(const std::string &path, const WatcherCallbackPtr &callback) { bool isOnly = IsOnlyWatcherFileInfo(path); diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h index b33539f15..935a873a2 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h @@ -14,12 +14,12 @@ */ #ifndef WATCHER_OBSERVER_H #define WATCHER_OBSERVER_H +#include "watcher_callback.h" #include #include #include #include #include -#include "watcher_callback.h" namespace OHOS { namespace DistributedFS { @@ -31,9 +31,7 @@ public: void AddObserver(const std::string &path, const std::vector &watchEvents, const WatcherCallbackPtr &callback); - void RemoveObserver(const std::string &path, - const std::vector &watchEvents, - const WatcherCallbackPtr &callback); + void RemoveObserver(const std::string &path, const WatcherCallbackPtr &callback); class WatcherFileInfo { public: @@ -56,7 +54,7 @@ private: bool StartObserver(); bool StopObserver(); bool IsOnlyWatcherFileInfo(const std::string &path); - static bool AddInotifyEvents(const int &inotifyFd); + static bool AddInotifyEvents(); static bool WatchPathThread(); static bool isRunning_; static std::map watcherFileMaps_; -- Gitee From 1cdb12839cfe6485271d1f6460ddaaff6808ba17 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Mon, 16 Jan 2023 09:35:24 +0800 Subject: [PATCH 06/25] add error code Signed-off-by: Cao Chuan --- interfaces/kits/js/src/common/uni_error.h | 5 ++--- .../src/mod_fileio/properties/watcher_observer.cpp | 13 ++++++------- .../js/src/mod_fileio/properties/watcher_observer.h | 2 +- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/interfaces/kits/js/src/common/uni_error.h b/interfaces/kits/js/src/common/uni_error.h index 4918dc7f4..e7b47bb79 100644 --- a/interfaces/kits/js/src/common/uni_error.h +++ b/interfaces/kits/js/src/common/uni_error.h @@ -82,8 +82,7 @@ enum ErrCodeSuffix { E_RESTART, E_DQUOT, E_UKERR, - E_WATHCER_INIT, - E_WATCHER_SUCCESS + E_WATHCER_INIT }; const std::unordered_map> errCodeTable { @@ -128,7 +127,7 @@ const std::unordered_map> errCodeTable { { EBADFD, { FILEIO_SYS_CAP_TAG + E_BADFD, "File descriptor in bad state" } }, { ERESTART, { FILEIO_SYS_CAP_TAG + E_RESTART, "Interrupted system call should be restarted" } }, { EDQUOT, { FILEIO_SYS_CAP_TAG + E_DQUOT, "Quota exceeded" } }, - { E_WATHCER_INIT, { FILEIO_SYS_CAP_TAG + E_WATHCER_INIT, "Watcher init error" } }, + { FILEIO_SYS_CAP_TAG + E_WATHCER_INIT, { FILEIO_SYS_CAP_TAG + E_WATHCER_INIT, "Watcher init error" } }, { -1, { FILEIO_SYS_CAP_TAG + E_UKERR, "Unknown error" } } }; diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp index 91b9b8ac3..afd8e224b 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp @@ -13,12 +13,12 @@ * limitations under the License. */ #include "watcher_observer.h" +#include "../../common/uni_error.h" +#include "../../log.h" #include #include #include #include -#include "../../log.h" -#include "../../common/uni_error.h" namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { @@ -134,19 +134,18 @@ bool WatcherObserver::AddInotifyEvents() return true; } -bool WatcherObserver::WatchPathThread() +void WatcherObserver::WatchPathThread() { HILOGI("WatcherObserver WatchPathThread IN"); while (isRunning_) { if (watcherFileMaps_.size() > 0) { bool ret = AddInotifyEvents(); if (!ret) { - return false; + return; } } } HILOGI("WatcherObserver WatchPathThread OUT"); - return true; } void WatcherObserver::AddObserver(const std::string &path, @@ -156,8 +155,8 @@ void WatcherObserver::AddObserver(const std::string &path, HILOGI("WatcherObserver AddObserver IN"); if (!inotifySuccess_) { bool startRet = StartObserver(); - if(!startRet) { - callback->OnChanged(ErrCodeSuffix::E_WATHCER_INIT, path , NONE_EVENT); + if (!startRet) { + callback->OnChanged(FILEIO_SYS_CAP_TAG + E_WATHCER_INIT, path, NONE_EVENT); } } if (inotifySuccess_) { diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h index 935a873a2..8e31dcc72 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h @@ -55,7 +55,7 @@ private: bool StopObserver(); bool IsOnlyWatcherFileInfo(const std::string &path); static bool AddInotifyEvents(); - static bool WatchPathThread(); + static void WatchPathThread(); static bool isRunning_; static std::map watcherFileMaps_; static std::mutex eventLock_; -- Gitee From 031003cc23a50780aa0eec3a86800bd414212f11 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Tue, 17 Jan 2023 15:04:16 +0800 Subject: [PATCH 07/25] modify watcher Signed-off-by: Cao Chuan --- interfaces/kits/js/BUILD.gn | 3 +- .../mod_fileio/class_watcher/watcher_entity.h | 12 +- .../class_watcher/watcher_n_exporter.cpp | 76 +++++- .../class_watcher/watcher_n_exporter.h | 14 +- .../js/src/mod_fileio/properties/watcher.cpp | 26 +- .../js/src/mod_fileio/properties/watcher.h | 9 - .../mod_fileio/properties/watcher_callback.h | 24 -- .../properties/watcher_observer.cpp | 223 ------------------ .../mod_fileio/properties/watcher_observer.h | 70 ------ 9 files changed, 97 insertions(+), 360 deletions(-) delete mode 100644 interfaces/kits/js/src/mod_fileio/properties/watcher_callback.h delete mode 100644 interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp delete mode 100644 interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index d9828f4d7..ed2d33d10 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -86,8 +86,7 @@ ohos_shared_library("fileio") { "src/mod_fileio/properties/stat.cpp", "src/mod_fileio/properties/symlink.cpp", "src/mod_fileio/properties/truncate.cpp", - "src/mod_fileio/properties/watcher.cpp", - "src/mod_fileio/properties/watcher_observer.cpp" + "src/mod_fileio/properties/watcher.cpp" ] deps = [ diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h index e7fc997ad..af08a35bf 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h @@ -26,7 +26,6 @@ namespace ModuleFileIO { #include #include #include -#include "../properties/watcher_callback.h" class WatcherHandleDeleter { public: @@ -42,16 +41,21 @@ public: } }; -struct WatcherInforArg { +struct WatcherInfoArg { std::string filename; std::vector events; - std::shared_ptr callbackPtr; napi_env env = nullptr; napi_ref ref = nullptr; }; +struct WatcherResult { + std::string filename; + int32_t err; + uint32_t event; +}; + struct WatcherEntity { - std::unique_ptr data_; + std::unique_ptr data_; std::unique_ptr fsEventReq_; }; } // namespace ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp index 2947b10cb..ebe640aa8 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include "../../common/log.h" #include "../../common/napi/n_async/n_async_work_callback.h" @@ -27,13 +28,13 @@ #include "../../common/napi/n_func_arg.h" #include "../../common/uni_error.h" #include "securec.h" -#include "watcher_entity.h" namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { using namespace std; - +const int SUCCESS = 0; +const int BUF_SIZE = 1024; napi_value WatcherNExporter::Constructor(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); @@ -51,6 +52,67 @@ napi_value WatcherNExporter::Constructor(napi_env env, napi_callback_info info) return funcArg.GetThisVar(); } +bool WatcherNExporter::InitNofity() +{ + HILOGI("WatcherNExporter InitNofity IN"); + fd_ = inotify_init(); + if (fd_ == -1) { + HILOGE("WatcherNExporter inotify_init fail"); + return false; + } + return true; +} + +bool WatcherNExporter::StopNotify() +{ + HILOGI("WatcherNExporter StopObserver IN"); + if (inotify_rm_watch(fd_, wd_) == -1) { + HILOGE("WatcherNExporter StopFileInotify inotify_rm_watch error"); + return false; + } + close(fd_); + + HILOGI("WatcherNExporter StopObserver OUT"); + return true; +} + +void WatcherNExporter::HandleEvent(std::shared_ptr &arg, + const struct inotify_event *event, + std::shared_ptr &result) +{ + if (event->wd == wd_) { + for (auto tempEvent : arg->events) { + if (event->mask == tempEvent) { + result->filename = arg->filename; + result->event = event->mask; + result->err = SUCCESS; + } + } + } +} + +void WatcherNExporter::GetNotifyEvent(std::shared_ptr &arg, std::shared_ptr &result) +{ + HILOGI("WatcherNExporter GetNotifyEvent IN"); + char buf[BUF_SIZE] = {0}; + struct inotify_event *event = nullptr; + fd_set fds; + FD_ZERO(&fds); + FD_SET(fd_, &fds); + + if (select(fd_ + 1, &fds, NULL, NULL, NULL) > 0) { + int len, index = 0; + while (((len = read(fd_, &buf, sizeof(buf))) < 0) && (errno == EINTR)) { + while (index < len) { + event = (struct inotify_event *)(buf + index); + HandleEvent(arg, event, result); + index += sizeof(struct inotify_event) + event->len; + } + } + } + HILOGI("WatcherNExporter AddInotifyEvents OUT"); +} + napi_value WatcherNExporter::StopSync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); @@ -90,9 +152,9 @@ napi_value WatcherNExporter::Stop(napi_env env, napi_callback_info info) auto cbCompl = [](napi_env env, UniError err) -> NVal { if (err) { - return { env, err.GetNapiErr(env) }; + return {env, err.GetNapiErr(env)}; } - return { NVal::CreateUndefined(env) }; + return {NVal::CreateUndefined(env)}; }; const string procedureName = "FileIOCreaterWatcher"; @@ -113,10 +175,8 @@ bool WatcherNExporter::Export() }; string className = GetClassName(); - auto [resDefineClass, classValue] = NClass::DefineClass(exports_.env_, - className, - WatcherNExporter::Constructor, - std::move(props)); + auto [resDefineClass, classValue] = + NClass::DefineClass(exports_.env_, className, WatcherNExporter::Constructor, std::move(props)); if (!resDefineClass) { UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to define class"); return false; diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h index 3d3502b7b..883b91b3d 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h @@ -15,9 +15,9 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_N_EXPORTER_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_N_EXPORTER_H - #include "../../common/napi/n_exporter.h" - +#include "watcher_entity.h" +#include namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { @@ -34,6 +34,16 @@ public: WatcherNExporter(napi_env env, napi_value exports); ~WatcherNExporter() override; + +private: + bool InitNofity(); + bool StopNotify(); + void HandleEvent(std::shared_ptr &arg, + const struct inotify_event *event, + std::shared_ptr &result); + void GetNotifyEvent(std::shared_ptr &arg, std::shared_ptr &result); + int fd_; + int wd_; }; } // namespace ModuleFileIO } // namespace DistributedFS diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp index bc5bb0777..845698326 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp @@ -15,25 +15,23 @@ #include "watcher.h" -#include -#include -#include -#include - #include "../../common/napi/n_async/n_ref.h" #include "../../common/napi/n_class.h" #include "../../common/napi/n_func_arg.h" #include "../../common/napi/n_val.h" #include "../../common/uni_error.h" +#include +#include +#include +#include +#include #include "../class_watcher/watcher_entity.h" #include "../class_watcher/watcher_n_exporter.h" -#include "watcher_callback.h" namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { using namespace std; - napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); @@ -54,21 +52,17 @@ napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) return nullptr; } - std::shared_ptr eventCallbackPtr = std::make_shared(); - unique_ptr data = make_unique(); + unique_ptr data = make_unique(); data->events = events; data->env = env; - data->callbackPtr = eventCallbackPtr; data->filename = string(filename.get()); - + NVal val = NVal(env, funcArg[NARG_POS::THIRD]); napi_create_reference(val.env_, val.val_, 1, &(data->ref)); - unique_ptr fsEventReq(new uv_fs_event_t); - + fsEventReq->data = data.get(); - napi_value objWatcher = NClass::InstantiateClass(env, WatcherNExporter::className_, {}); if (!objWatcher) { @@ -87,10 +81,6 @@ napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) return objWatcher; } - -void WatcherEventCallback::OnChanged(const int &err, const std::string &path, const uint32_t &event) { - //todo 添加napi -} } // namespace ModuleFileIO } // namespace DistributedFS } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.h b/interfaces/kits/js/src/mod_fileio/properties/watcher.h index 705dae53d..9493dd696 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.h +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.h @@ -18,7 +18,6 @@ #include #include "../../common/napi/n_val.h" -#include "watcher_callback.h" namespace OHOS { namespace DistributedFS { @@ -27,14 +26,6 @@ class Watcher final { public: static napi_value CreateWatcher(napi_env env, napi_callback_info info); }; - -class WatcherEventCallback : public WatcherCallback -{ -public: - void OnChanged(const int &err, const std::string &path, const uint32_t &event); -private: - -}; } // namespace ModuleFileIO } // namespace DistributedFS } // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_callback.h b/interfaces/kits/js/src/mod_fileio/properties/watcher_callback.h deleted file mode 100644 index ed822807c..000000000 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher_callback.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device 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. - */ -#ifndef WATCHER_CALLBACK_H -#define WATCHER_CALLBACK_H -#include -class WatcherCallback -{ -public: - virtual ~WatcherCallback() = default; - virtual void OnChanged(const int &err, const std::string &path, const uint32_t &event) = 0; -}; -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp deleted file mode 100644 index afd8e224b..000000000 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.cpp +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device 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. - */ -#include "watcher_observer.h" -#include "../../common/uni_error.h" -#include "../../log.h" -#include -#include -#include -#include -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -bool WatcherObserver::isRunning_ = false; -int WatcherObserver::inotifyFd_ = 0; -std::mutex WatcherObserver::eventLock_; -std::map WatcherObserver::watcherFileMaps_; -const int BUF_SIZE = 1024; -const uint32_t NONE_EVENT = 0; -const uint32_t SUCCESS = 0; -void WatcherObserver::WatcherFileInfo::SetPath(const std::string &path) -{ - path_ = path; -} - -std::string WatcherObserver::WatcherFileInfo::GetPath() -{ - return path_; -} - -void WatcherObserver::WatcherFileInfo::SetWd(const int &wd) -{ - wd_ = wd; -} - -int WatcherObserver::WatcherFileInfo::GetWd() -{ - return wd_; -} - -void WatcherObserver::WatcherFileInfo::SetWatchEvents(const std::vector &events) -{ - events_.assign(events.begin(), events.end()); -} - -std::vector WatcherObserver::WatcherFileInfo::GetWatchEvents() -{ - return events_; -} - -bool WatcherObserver::StartObserver() -{ - HILOGI("WatcherObserver StartObserver IN"); - isRunning_ = true; - inotifyFd_ = inotify_init(); - if (inotifyFd_ == -1) { - HILOGE("WatcherObserver inotify_init false"); - return false; - } else { - HILOGI("WatcherObserver StartObserver Success"); - inotifySuccess_ = true; - return true; - } -} - -bool WatcherObserver::StopObserver() -{ - HILOGI("WatcherObserver StopObserver IN"); - isRunning_ = false; - for (auto fileInfo : watcherFileMaps_) { - if (inotify_rm_watch(inotifyFd_, fileInfo.second.GetWd()) == -1) { - HILOGE("WatcherObserver StopFileInotify inotify_rm_watch error"); - return false; - } - } - close(inotifyFd_); - startThread_ = false; - inotifySuccess_ = false; - inotifyFd_ = 0; - HILOGI("WatcherObserver StopObserver OUT"); - return true; -} - -bool WatcherObserver::AddInotifyEvents() -{ - HILOGI("WatcherObserver AddInotifyEvents IN"); - char eventBuf[BUF_SIZE] = {0}; - - int ret = read(inotifyFd_, eventBuf, sizeof(eventBuf)); - if (ret < (int)sizeof(struct inotify_event)) { - HILOGE("WatcherObserver AddInotifyEvents no event"); - return false; - } - - struct inotify_event *positionEvent = (struct inotify_event *)eventBuf; - struct inotify_event *event; - while (ret >= (int)sizeof(struct inotify_event)) { - lock_guard lock(eventLock_); - event = positionEvent; - if (event->len) { - for (auto watcherFileInfo : watcherFileMaps_) { - WatcherObserver::WatcherFileInfo info = watcherFileInfo.second; - if (info.GetWd() == event->wd) { - HILOGI("WatcherObserver AddInotifyEvents path:%{public}s wd:%{public}d", info.GetPath().c_str(), - event->wd); - vector events = info.GetWatchEvents(); - for (auto iter = events.begin(); iter != events.end(); ++iter) { - if (event->mask == *iter) { - HILOGI("WatcherObserver AddInotifyEvents1 path:%{public}s wd:%{public}d", - info.GetPath().c_str(), info.GetWd()); - watcherFileInfo.first->OnChanged(SUCCESS, info.GetPath(), event->mask); - } - } - } - } - } - positionEvent++; - ret -= (int)sizeof(struct inotify_event); - } - HILOGI("WatcherObserver AddInotifyEvents OUT"); - return true; -} - -void WatcherObserver::WatchPathThread() -{ - HILOGI("WatcherObserver WatchPathThread IN"); - while (isRunning_) { - if (watcherFileMaps_.size() > 0) { - bool ret = AddInotifyEvents(); - if (!ret) { - return; - } - } - } - HILOGI("WatcherObserver WatchPathThread OUT"); -} - -void WatcherObserver::AddObserver(const std::string &path, - const std::vector &watchEvents, - const WatcherCallbackPtr &callback) -{ - HILOGI("WatcherObserver AddObserver IN"); - if (!inotifySuccess_) { - bool startRet = StartObserver(); - if (!startRet) { - callback->OnChanged(FILEIO_SYS_CAP_TAG + E_WATHCER_INIT, path, NONE_EVENT); - } - } - if (inotifySuccess_) { - if (!path.empty() && watchEvents.size() > 0) { - uint32_t event = 0; - for (auto watchEvent : watchEvents) { - event = event | watchEvent; - } - int wd = inotify_add_watch(inotifyFd_, path.c_str(), event); - - WatcherFileInfo fileInfo; - fileInfo.SetWd(wd); - fileInfo.SetPath(path); - fileInfo.SetWatchEvents(watchEvents); - watcherFileMaps_.insert(make_pair(callback, fileInfo)); - } - } - if (!startThread_) { - std::thread watchThread(WatchPathThread); - watchThread.detach(); - startThread_ = true; - } - HILOGI("WatcherObserver AddObserver OUT"); -} - -bool WatcherObserver::IsOnlyWatcherFileInfo(const std::string &path) -{ - int count = 0; - for (auto watcherFileInfo : watcherFileMaps_) { - if (strcmp(path.c_str(), watcherFileInfo.second.GetPath().c_str()) == 0) { - count++; - } - if (count > 1) { - return false; - } - } - if (count == 0) { - return false; - } - return true; -} - -void WatcherObserver::RemoveObserver(const std::string &path, const WatcherCallbackPtr &callback) -{ - - bool isOnly = IsOnlyWatcherFileInfo(path); - auto iter = watcherFileMaps_.find(callback); - if (iter != watcherFileMaps_.end()) { - if (isOnly) { - if (inotify_rm_watch(inotifyFd_, iter->second.GetWd()) == -1) { - HILOGE("WatcherObserver StopFileInotify inotify_rm_watch error"); - return; - } - } - watcherFileMaps_.erase(iter); - } - - if (watcherFileMaps_.size() == 0) { - StopObserver(); - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h b/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h deleted file mode 100644 index 8e31dcc72..000000000 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher_observer.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device 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. - */ -#ifndef WATCHER_OBSERVER_H -#define WATCHER_OBSERVER_H -#include "watcher_callback.h" -#include -#include -#include -#include -#include - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using WatcherCallbackPtr = std::shared_ptr; - -class WatcherObserver { -public: - void AddObserver(const std::string &path, - const std::vector &watchEvents, - const WatcherCallbackPtr &callback); - void RemoveObserver(const std::string &path, const WatcherCallbackPtr &callback); - - class WatcherFileInfo { - public: - void SetWd(const int &wd); - int32_t GetWd(); - - void SetPath(const std::string &path); - std::string GetPath(); - - void SetWatchEvents(const std::vector &events); - std::vector GetWatchEvents(); - - private: - int wd_; - std::string path_; - std::vector events_; - }; - -private: - bool StartObserver(); - bool StopObserver(); - bool IsOnlyWatcherFileInfo(const std::string &path); - static bool AddInotifyEvents(); - static void WatchPathThread(); - static bool isRunning_; - static std::map watcherFileMaps_; - static std::mutex eventLock_; - static int inotifyFd_; - - bool startThread_; - bool inotifySuccess_; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file -- Gitee From 15998324645c4f85ea1003ec8b375c58b6353ff2 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Wed, 18 Jan 2023 10:56:31 +0800 Subject: [PATCH 08/25] modify file notify Signed-off-by: Cao Chuan --- .../mod_fileio/class_watcher/watcher_entity.h | 1 + .../class_watcher/watcher_n_exporter.cpp | 44 ++++++++++++------- .../class_watcher/watcher_n_exporter.h | 6 +-- .../js/src/mod_fileio/properties/watcher.cpp | 8 ++++ 4 files changed, 40 insertions(+), 19 deletions(-) diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h index af08a35bf..32ba6f73b 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h @@ -44,6 +44,7 @@ public: struct WatcherInfoArg { std::string filename; std::vector events; + int fd; napi_env env = nullptr; napi_ref ref = nullptr; }; diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp index ebe640aa8..155027f31 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp @@ -52,26 +52,36 @@ napi_value WatcherNExporter::Constructor(napi_env env, napi_callback_info info) return funcArg.GetThisVar(); } -bool WatcherNExporter::InitNofity() +bool WatcherNExporter::StartNotify(std::shared_ptr &arg) { HILOGI("WatcherNExporter InitNofity IN"); - fd_ = inotify_init(); - if (fd_ == -1) { - HILOGE("WatcherNExporter inotify_init fail"); + if (arg->events.size() == 0) { + HILOGI( + "WatcherNExporter InitNofity No events suitable for MASK parameter " + "of INOTIFY_ADD_WATCH"); return false; } + + uint32_t watchEvent = 0; + for (auto event : arg->events) { + watchEvent = watchEvent | event; + } + wd_ = inotify_add_watch(arg->fd, arg->filename.c_str(), watchEvent); + run_ = true; return true; } -bool WatcherNExporter::StopNotify() +bool WatcherNExporter::StopNotify(std::shared_ptr &arg) { HILOGI("WatcherNExporter StopObserver IN"); - if (inotify_rm_watch(fd_, wd_) == -1) { + + if (inotify_rm_watch(arg->fd, wd_) == -1) { HILOGE("WatcherNExporter StopFileInotify inotify_rm_watch error"); return false; } - close(fd_); + run_ = false; + close(arg->fd); HILOGI("WatcherNExporter StopObserver OUT"); return true; } @@ -98,18 +108,20 @@ void WatcherNExporter::GetNotifyEvent(std::shared_ptr &arg, std: struct inotify_event *event = nullptr; fd_set fds; FD_ZERO(&fds); - FD_SET(fd_, &fds); - - if (select(fd_ + 1, &fds, NULL, NULL, NULL) > 0) { - int len, index = 0; - while (((len = read(fd_, &buf, sizeof(buf))) < 0) && (errno == EINTR)) { - while (index < len) { - event = (struct inotify_event *)(buf + index); - HandleEvent(arg, event, result); - index += sizeof(struct inotify_event) + event->len; + FD_SET(arg->fd, &fds); + while (run_) { + if (select(arg->fd + 1, &fds, NULL, NULL, NULL) > 0) { + int len, index = 0; + while (((len = read(arg->fd, &buf, sizeof(buf))) < 0) && (errno == EINTR)) { + while (index < len) { + event = (struct inotify_event *)(buf + index); + HandleEvent(arg, event, result); + index += sizeof(struct inotify_event) + event->len; + } } } } + HILOGI("WatcherNExporter AddInotifyEvents OUT"); } diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h index 883b91b3d..85c772e95 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h @@ -36,14 +36,14 @@ public: ~WatcherNExporter() override; private: - bool InitNofity(); - bool StopNotify(); + bool StartNotify(std::shared_ptr &arg); + bool StopNotify(std::shared_ptr &arg); void HandleEvent(std::shared_ptr &arg, const struct inotify_event *event, std::shared_ptr &result); void GetNotifyEvent(std::shared_ptr &arg, std::shared_ptr &result); - int fd_; int wd_; + bool run_; }; } // namespace ModuleFileIO } // namespace DistributedFS diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp index 845698326..2079050d1 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp @@ -32,8 +32,15 @@ namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { using namespace std; + napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) { + int fd = inotify_init(); + if (fd == -1) { + // todo 加异常报错 + return nullptr; + } + NFuncArg funcArg(env, info); if (!funcArg.InitArgs(NARG_CNT::THREE)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); @@ -56,6 +63,7 @@ napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) data->events = events; data->env = env; data->filename = string(filename.get()); + data->fd = fd; NVal val = NVal(env, funcArg[NARG_POS::THIRD]); napi_create_reference(val.env_, val.val_, 1, &(data->ref)); -- Gitee From 3001abf12347883bde0b97c0720ad526e0201ad5 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Wed, 18 Jan 2023 17:23:43 +0800 Subject: [PATCH 09/25] modify gn Signed-off-by: Cao Chuan --- interfaces/kits/js/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index ed2d33d10..4a67419f1 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -86,7 +86,7 @@ ohos_shared_library("fileio") { "src/mod_fileio/properties/stat.cpp", "src/mod_fileio/properties/symlink.cpp", "src/mod_fileio/properties/truncate.cpp", - "src/mod_fileio/properties/watcher.cpp" + "src/mod_fileio/properties/watcher.cpp", ] deps = [ -- Gitee From 6fec3c3144cf102ac4553ec602bc46afda1a899c Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Thu, 19 Jan 2023 10:26:23 +0800 Subject: [PATCH 10/25] add file_watcher Signed-off-by: Cao Chuan --- .../mod_fileio/class_watcher/file_watcher.cpp | 106 ++++++++++++++++++ .../mod_fileio/class_watcher/file_watcher.h | 40 +++++++ .../mod_fileio/class_watcher/watcher_entity.h | 1 + .../class_watcher/watcher_n_exporter.cpp | 76 +------------ .../js/src/mod_fileio/properties/watcher.cpp | 10 +- 5 files changed, 152 insertions(+), 81 deletions(-) create mode 100644 interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.h diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp new file mode 100644 index 000000000..fddf64241 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2021 Huawei Device 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. + */ +#include "file_watcher.h" +#include "utils/filemgmt_libhilog/filemgmt_libhilog.h" +#include + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +const int BUF_SIZE = 1024; +FileWatcher::FileWatcher() {} + +FileWatcher::~FileWatcher() {} + +bool FileWatcher::InitNotify() +{ + int fd = inotify_init(); + if (fd == -1) { + return false; + } + return true; +} + +bool FileWatcher::StartNotify(std::shared_ptr &arg) +{ + HILOGI("FileWatcher InitNofity IN"); + if (arg->events.size() == 0) { + HILOGE("FileWatcher StartNotify No events to watch"); + return false; + } + + uint32_t watchEvent = 0; + for (auto event : arg->events) { + watchEvent = watchEvent | event; + } + arg->wd = inotify_add_watch(arg->fd, arg->filename.c_str(), watchEvent); + run_ = true; + return true; +} + +bool FileWatcher::StopNotify(std::shared_ptr &arg) +{ + HILOGI("FileWatcher StopObserver IN"); + + if (inotify_rm_watch(arg->fd, arg->wd) == -1) { + HILOGE("FileWatcher StopFileInotify inotify_rm_watch error"); + return false; + } + run_ = false; + close(arg->fd); + HILOGI("FileWatcher StopObserver OUT"); + return true; +} + +void FileWatcher::HandleEvent(std::shared_ptr &arg, + const struct inotify_event *event, + std::shared_ptr &result) +{ + if (event->wd == wd_) { + for (auto tempEvent : arg->events) { + if (event->mask == tempEvent) { + result->filename = arg->filename; + result->event = event->mask; + } + } + } +} + +void FileWatcher::GetNotifyEvent(std::shared_ptr &arg, std::shared_ptr &result) +{ + HILOGI("FileWatcher GetNotifyEvent IN"); + char buf[BUF_SIZE] = {0}; + struct inotify_event *event = nullptr; + fd_set fds; + FD_ZERO(&fds); + FD_SET(arg->fd, &fds); + while (run_) { + if (select(arg->fd + 1, &fds, NULL, NULL, NULL) > 0) { + int len, index = 0; + while (((len = read(arg->fd, &buf, sizeof(buf))) < 0) && (errno == EINTR)) { + while (index < len) { + event = (struct inotify_event *)(buf + index); + HandleEvent(arg, event, result); + index += sizeof(struct inotify_event) + event->len; + } + } + } + } + + HILOGI("FileWatcher AddInotifyEvents OUT"); +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.h b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.h new file mode 100644 index 000000000..92012e6d8 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device 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. + */ + +#ifndef FILE_WATCHER_H +#define FILE_WATCHER_H +#include "watcher_entity.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class FileWatcher { +public: + bool InitNotify(); + bool StartNotify(std::shared_ptr &arg); + bool StopNotify(std::shared_ptr &arg); + void GetNotifyEvent(std::shared_ptr &arg, std::shared_ptr &result); + +private: + bool run_; + void HandleEvent(std::shared_ptr &arg, + const struct inotify_event *event, + std::shared_ptr &result); + +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h index 32ba6f73b..be538fd11 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h @@ -45,6 +45,7 @@ struct WatcherInfoArg { std::string filename; std::vector events; int fd; + int wd; napi_env env = nullptr; napi_ref ref = nullptr; }; diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp index 155027f31..48234512e 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp @@ -33,8 +33,7 @@ namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { using namespace std; -const int SUCCESS = 0; -const int BUF_SIZE = 1024; + napi_value WatcherNExporter::Constructor(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); @@ -52,79 +51,6 @@ napi_value WatcherNExporter::Constructor(napi_env env, napi_callback_info info) return funcArg.GetThisVar(); } -bool WatcherNExporter::StartNotify(std::shared_ptr &arg) -{ - HILOGI("WatcherNExporter InitNofity IN"); - if (arg->events.size() == 0) { - HILOGI( - "WatcherNExporter InitNofity No events suitable for MASK parameter " - "of INOTIFY_ADD_WATCH"); - return false; - } - - uint32_t watchEvent = 0; - for (auto event : arg->events) { - watchEvent = watchEvent | event; - } - wd_ = inotify_add_watch(arg->fd, arg->filename.c_str(), watchEvent); - run_ = true; - return true; -} - -bool WatcherNExporter::StopNotify(std::shared_ptr &arg) -{ - HILOGI("WatcherNExporter StopObserver IN"); - - if (inotify_rm_watch(arg->fd, wd_) == -1) { - HILOGE("WatcherNExporter StopFileInotify inotify_rm_watch error"); - return false; - } - - run_ = false; - close(arg->fd); - HILOGI("WatcherNExporter StopObserver OUT"); - return true; -} - -void WatcherNExporter::HandleEvent(std::shared_ptr &arg, - const struct inotify_event *event, - std::shared_ptr &result) -{ - if (event->wd == wd_) { - for (auto tempEvent : arg->events) { - if (event->mask == tempEvent) { - result->filename = arg->filename; - result->event = event->mask; - result->err = SUCCESS; - } - } - } -} - -void WatcherNExporter::GetNotifyEvent(std::shared_ptr &arg, std::shared_ptr &result) -{ - HILOGI("WatcherNExporter GetNotifyEvent IN"); - char buf[BUF_SIZE] = {0}; - struct inotify_event *event = nullptr; - fd_set fds; - FD_ZERO(&fds); - FD_SET(arg->fd, &fds); - while (run_) { - if (select(arg->fd + 1, &fds, NULL, NULL, NULL) > 0) { - int len, index = 0; - while (((len = read(arg->fd, &buf, sizeof(buf))) < 0) && (errno == EINTR)) { - while (index < len) { - event = (struct inotify_event *)(buf + index); - HandleEvent(arg, event, result); - index += sizeof(struct inotify_event) + event->len; - } - } - } - } - - HILOGI("WatcherNExporter AddInotifyEvents OUT"); -} - napi_value WatcherNExporter::StopSync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp index 2079050d1..c5b24d15f 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include "../class_watcher/watcher_entity.h" #include "../class_watcher/watcher_n_exporter.h" @@ -37,7 +38,7 @@ napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) { int fd = inotify_init(); if (fd == -1) { - // todo 加异常报错 + UniError(errno).ThrowErr(env); return nullptr; } @@ -68,9 +69,6 @@ napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) NVal val = NVal(env, funcArg[NARG_POS::THIRD]); napi_create_reference(val.env_, val.val_, 1, &(data->ref)); - unique_ptr fsEventReq(new uv_fs_event_t); - - fsEventReq->data = data.get(); napi_value objWatcher = NClass::InstantiateClass(env, WatcherNExporter::className_, {}); if (!objWatcher) { @@ -84,11 +82,11 @@ napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) return nullptr; } - watcherEntity->fsEventReq_ = std::move(fsEventReq); + watcherEntity->data_ = std::move(data); return objWatcher; } } // namespace ModuleFileIO } // namespace DistributedFS -} // namespace OHOS \ No newline at end of file +} // namespace OHOS -- Gitee From 4f0b3afcf884be8de8239a42c3748ddb170fb555 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Thu, 19 Jan 2023 15:00:08 +0800 Subject: [PATCH 11/25] modify watcher Signed-off-by: Cao Chuan --- interfaces/kits/js/BUILD.gn | 1 + .../mod_fileio/class_watcher/file_watcher.cpp | 60 +++++++++++-------- .../mod_fileio/class_watcher/file_watcher.h | 25 +++++--- .../mod_fileio/class_watcher/watcher_entity.h | 2 +- .../class_watcher/watcher_n_exporter.cpp | 49 +++------------ .../class_watcher/watcher_n_exporter.h | 14 ++--- .../js/src/mod_fileio/properties/watcher.cpp | 23 +++---- 7 files changed, 76 insertions(+), 98 deletions(-) diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 4a67419f1..b427d1251 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -53,6 +53,7 @@ ohos_shared_library("fileio") { "src/mod_fileio/class_stream/flush.cpp", "src/mod_fileio/class_stream/stream_n_exporter.cpp", "src/mod_fileio/class_watcher/watcher_n_exporter.cpp", + "src/mod_fileio/class_watcher/file_watcher.cpp", "src/mod_fileio/common_func.cpp", "src/mod_fileio/module.cpp", "src/mod_fileio/properties/chmod.cpp", diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp index fddf64241..54375c698 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp @@ -13,9 +13,9 @@ * limitations under the License. */ #include "file_watcher.h" -#include "utils/filemgmt_libhilog/filemgmt_libhilog.h" -#include - +#include "../../common/log.h" +#include +#include namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { @@ -24,38 +24,46 @@ FileWatcher::FileWatcher() {} FileWatcher::~FileWatcher() {} -bool FileWatcher::InitNotify() +bool FileWatcher::InitNotify(int &fd, int &errCode) { - int fd = inotify_init(); + HILOGI("FileWatcher InitNotify IN"); + fd = inotify_init(); if (fd == -1) { + errCode = errno; + HILOGE("FileWatcher InitNotify fail errCode:%{public}d", errCode); return false; } + HILOGI("FileWatcher InitNotify OUT"); return true; } -bool FileWatcher::StartNotify(std::shared_ptr &arg) +bool FileWatcher::StartNotify(std::shared_ptr &arg, int &errCode) { - HILOGI("FileWatcher InitNofity IN"); - if (arg->events.size() == 0) { - HILOGE("FileWatcher StartNotify No events to watch"); - return false; - } - + HILOGI("FileWatcher StartNotify IN"); + int wd = 0; uint32_t watchEvent = 0; for (auto event : arg->events) { watchEvent = watchEvent | event; } - arg->wd = inotify_add_watch(arg->fd, arg->filename.c_str(), watchEvent); + wd = inotify_add_watch(arg->fd, arg->filename.c_str(), watchEvent); + if(wd == -1) { + errCode = errno; + HILOGE("FileWatcher StartNotify fail errCode:%{public}d", errCode); + return false; + } + arg->wd = wd; run_ = true; + HILOGI("FileWatcher StartNotify OUT"); return true; } -bool FileWatcher::StopNotify(std::shared_ptr &arg) +bool FileWatcher::StopNotify(std::shared_ptr &arg, int &errCode) { HILOGI("FileWatcher StopObserver IN"); - + if (inotify_rm_watch(arg->fd, arg->wd) == -1) { - HILOGE("FileWatcher StopFileInotify inotify_rm_watch error"); + errCode = errno; + HILOGE("FileWatcher StopNotify fail errCode:%{public}d", errCode); return false; } run_ = false; @@ -66,19 +74,20 @@ bool FileWatcher::StopNotify(std::shared_ptr &arg) void FileWatcher::HandleEvent(std::shared_ptr &arg, const struct inotify_event *event, - std::shared_ptr &result) + WatcherCallback callback) { - if (event->wd == wd_) { - for (auto tempEvent : arg->events) { - if (event->mask == tempEvent) { - result->filename = arg->filename; - result->event = event->mask; + HILOGI("FileWatcher HandleEvent IN"); + if (event->wd == arg->wd) { + for (auto watchEvent : arg->events) { + if (event->mask == watchEvent) { + callback(arg->env, arg->ref, event->name, event->mask); } } } + HILOGI("FileWatcher HandleEvent OUT"); } -void FileWatcher::GetNotifyEvent(std::shared_ptr &arg, std::shared_ptr &result) +void FileWatcher::GetNotifyEvent(std::shared_ptr &arg, WatcherCallback callback) { HILOGI("FileWatcher GetNotifyEvent IN"); char buf[BUF_SIZE] = {0}; @@ -92,14 +101,13 @@ void FileWatcher::GetNotifyEvent(std::shared_ptr &arg, std::shar while (((len = read(arg->fd, &buf, sizeof(buf))) < 0) && (errno == EINTR)) { while (index < len) { event = (struct inotify_event *)(buf + index); - HandleEvent(arg, event, result); + HandleEvent(arg, event, callback); index += sizeof(struct inotify_event) + event->len; } } } } - - HILOGI("FileWatcher AddInotifyEvents OUT"); + HILOGI("FileWatcher GetNotifyEvent OUT"); } } // namespace ModuleFileIO } // namespace DistributedFS diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.h b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.h index 92012e6d8..c7d798c54 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.h @@ -15,24 +15,31 @@ #ifndef FILE_WATCHER_H #define FILE_WATCHER_H +#include +#include +#include #include "watcher_entity.h" - namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { +using WatcherCallback = void (*)(napi_env env, napi_ref callback, const std::string &filename, const uint32_t &event); +struct ErrorInfo { + int errCode; + std::string errMsg; +}; + class FileWatcher { public: - bool InitNotify(); - bool StartNotify(std::shared_ptr &arg); - bool StopNotify(std::shared_ptr &arg); - void GetNotifyEvent(std::shared_ptr &arg, std::shared_ptr &result); + FileWatcher(); + ~FileWatcher(); + bool InitNotify(int &fd, int &errCode); + bool StartNotify(std::shared_ptr &arg, int &errCode); + bool StopNotify(std::shared_ptr &arg, int &errCode); + void GetNotifyEvent(std::shared_ptr &arg, WatcherCallback callback); private: + void HandleEvent(std::shared_ptr &arg, const struct inotify_event *event, WatcherCallback callback); bool run_; - void HandleEvent(std::shared_ptr &arg, - const struct inotify_event *event, - std::shared_ptr &result); - }; } // namespace ModuleFileIO } // namespace DistributedFS diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h index be538fd11..1f6fdc6b5 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h @@ -57,7 +57,7 @@ struct WatcherResult { }; struct WatcherEntity { - std::unique_ptr data_; + std::shared_ptr data_; std::unique_ptr fsEventReq_; }; } // namespace ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp index 48234512e..6d5cea742 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp @@ -19,7 +19,6 @@ #include #include #include -#include #include "../../common/log.h" #include "../../common/napi/n_async/n_async_work_callback.h" @@ -33,7 +32,7 @@ namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { using namespace std; - +std::shared_ptr WatcherNExporter::watcherPtr_; napi_value WatcherNExporter::Constructor(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); @@ -48,10 +47,11 @@ napi_value WatcherNExporter::Constructor(napi_env env, napi_callback_info info) return nullptr; } + watcherPtr_ = make_shared(); return funcArg.GetThisVar(); } -napi_value WatcherNExporter::StopSync(napi_env env, napi_callback_info info) +napi_value WatcherNExporter::Stop(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); if (!funcArg.InitArgs(NARG_CNT::ZERO)) { @@ -64,52 +64,19 @@ napi_value WatcherNExporter::StopSync(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "get watcherEntity fail"); return nullptr; } - - watchEntity->fsEventReq_.reset(); - return NVal::CreateUndefined(env).val_; -} - -napi_value WatcherNExporter::Stop(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + int errCode = 0; + if (!watcherPtr_->StopNotify(watchEntity->data_, errCode)) { + UniError(errCode).ThrowErr(env); return nullptr; } - - auto watchEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!watchEntity) { - UniError(EINVAL).ThrowErr(env, "get watcherEntity fail"); - return nullptr; - } - - auto cbExec = [watchEntity](napi_env env) -> UniError { - watchEntity->fsEventReq_.reset(); - return UniError(ERRNO_NOERR); - }; - - auto cbCompl = [](napi_env env, UniError err) -> NVal { - if (err) { - return {env, err.GetNapiErr(env)}; - } - return {NVal::CreateUndefined(env)}; - }; - - const string procedureName = "FileIOCreaterWatcher"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ZERO) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::FIRST]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } + + return NVal::CreateUndefined(env).val_; } bool WatcherNExporter::Export() { vector props = { NVal::DeclareNapiFunction("stop", Stop), - NVal::DeclareNapiFunction("stopSync", StopSync), }; string className = GetClassName(); diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h index 85c772e95..9577596e3 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h @@ -15,9 +15,11 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_N_EXPORTER_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_N_EXPORTER_H +#include +#include #include "../../common/napi/n_exporter.h" #include "watcher_entity.h" -#include +#include "file_watcher.h" namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { @@ -30,20 +32,12 @@ public: static napi_value Constructor(napi_env env, napi_callback_info info); static napi_value Stop(napi_env env, napi_callback_info info); - static napi_value StopSync(napi_env env, napi_callback_info info); WatcherNExporter(napi_env env, napi_value exports); ~WatcherNExporter() override; private: - bool StartNotify(std::shared_ptr &arg); - bool StopNotify(std::shared_ptr &arg); - void HandleEvent(std::shared_ptr &arg, - const struct inotify_event *event, - std::shared_ptr &result); - void GetNotifyEvent(std::shared_ptr &arg, std::shared_ptr &result); - int wd_; - bool run_; + static std::shared_ptr watcherPtr_; }; } // namespace ModuleFileIO } // namespace DistributedFS diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp index c5b24d15f..35da67dce 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp @@ -25,8 +25,8 @@ #include #include #include -#include +#include "../class_watcher/file_watcher.h" #include "../class_watcher/watcher_entity.h" #include "../class_watcher/watcher_n_exporter.h" namespace OHOS { @@ -36,12 +36,6 @@ using namespace std; napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) { - int fd = inotify_init(); - if (fd == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - NFuncArg funcArg(env, info); if (!funcArg.InitArgs(NARG_CNT::THREE)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); @@ -60,12 +54,21 @@ napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) return nullptr; } - unique_ptr data = make_unique(); + int fd = 0; + int errCode; + shared_ptr watcherPtr = make_shared(); + if (!watcherPtr->InitNotify(fd, errCode)) { + UniError(errCode).ThrowErr(env); + return nullptr; + } + + shared_ptr data = make_shared(); data->events = events; data->env = env; data->filename = string(filename.get()); data->fd = fd; + NVal val = NVal(env, funcArg[NARG_POS::THIRD]); napi_create_reference(val.env_, val.val_, 1, &(data->ref)); @@ -81,9 +84,7 @@ napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "watcherEntity get failed"); return nullptr; } - - - watcherEntity->data_ = std::move(data); + watcherEntity->data_ = data; return objWatcher; } -- Gitee From 2b63ae5c9000d167730a11e0fb246aa433a03c79 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Fri, 20 Jan 2023 08:49:46 +0800 Subject: [PATCH 12/25] Add callback for JS Signed-off-by: Cao Chuan --- interfaces/kits/js/src/common/napi/n_val.cpp | 7 ++ interfaces/kits/js/src/common/napi/n_val.h | 1 + .../class_watcher/watcher_n_exporter.cpp | 68 +++++++++++++++++++ .../class_watcher/watcher_n_exporter.h | 15 ++++ 4 files changed, 91 insertions(+) diff --git a/interfaces/kits/js/src/common/napi/n_val.cpp b/interfaces/kits/js/src/common/napi/n_val.cpp index c3c31cbef..41ccc75a2 100644 --- a/interfaces/kits/js/src/common/napi/n_val.cpp +++ b/interfaces/kits/js/src/common/napi/n_val.cpp @@ -281,6 +281,13 @@ NVal NVal::CreateInt32(napi_env env, int32_t val) return { env, res }; } +NVal NVal::CreateUint32(napi_env env, int32_t val) +{ + napi_value res = nullptr; + napi_create_uint32(env, val, &res); + return {env, res}; +} + NVal NVal::CreateObject(napi_env env) { napi_value res = nullptr; diff --git a/interfaces/kits/js/src/common/napi/n_val.h b/interfaces/kits/js/src/common/napi/n_val.h index 73b3c5616..21fa6c1aa 100644 --- a/interfaces/kits/js/src/common/napi/n_val.h +++ b/interfaces/kits/js/src/common/napi/n_val.h @@ -57,6 +57,7 @@ public: static NVal CreateBigInt64(napi_env env, int64_t val); static NVal CreateInt64(napi_env env, int64_t val); static NVal CreateInt32(napi_env env, int32_t val); + static NVal CreateUint32(napi_env env, int32_t val); static NVal CreateObject(napi_env env); static NVal CreateBool(napi_env env, bool val); static NVal CreateUTF8String(napi_env env, std::string str); diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp index 6d5cea742..fbad911c6 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp @@ -73,9 +73,77 @@ napi_value WatcherNExporter::Stop(napi_env env, napi_callback_info info) return NVal::CreateUndefined(env).val_; } +napi_value WatcherNExporter::Start(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto watchEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!watchEntity) { + UniError(EINVAL).ThrowErr(env, "get watcherEntity fail"); + return nullptr; + } + + StartNotify(watchEntity->data); + + auto cbExec = [watchEntity](napi_env env, UniError err) -> UniError { + GetNotifyEvent(watchEntity->data, WatcherCallback); + return UniError(ERRNO_NOERR); + }; + + auto cbCompl = [](napi_env env, UniError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return {NVal::CreateUndefined(env)}; + }; + + const string procedureName = "FileIOStartWatcher"; + NVal thisVar(env, funcArg.GetThisVar()); + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; +} + +void WatcherNExporter::WatcherCallback(napi_env env, + napi_ref callback, + const std::string &fileName, + const uint32_t &event) +{ + auto callbackContext = make_unique(); + callbackContext->env_ = env; + callbackContext->ref_ = callback; + callbackContext->fileName_ = fileName; + callbackContext->event_ = event; + napi_value resource = nullptr; + napi_create_string_utf8(env, "FileIOCreateWatcher", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( + env, nullptr, resource, [](napi_env env, void *data) {}, + [](napi_env env, napi_status status, void *data) { + // JSCallbackData* jsCallbackData = (JSCallbackData*)data; + auto context = static_cast(data); + napi_value jsCallback = nullptr; + napi_get_reference_value(env, context->ref, &jsCallback); + vector argv; + argv.push_back(NVal::CreateUTF8String(env, context->fileName_).val_); + argv.push_back(NVal::CreateUint32(env, context->event_).val_); + napi_value global = nullptr; + napi_get_global(env, &global); + napi_value jsObj = nullptr; + napi_call_function(env, global, jsCallback, argv.size(), argv.data(), &jsObj); + napi_delete_async_work(env, context->work); + }, + static_cast(callbackContext.get()), &callbackContext->work); + napi_queue_async_work(env, callbackContext->work); + callbackContext.release(); +} + bool WatcherNExporter::Export() { vector props = { + NVal::DeclareNapiFunction("start", Start), NVal::DeclareNapiFunction("stop", Stop), }; diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h index 9577596e3..be4ea3823 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h @@ -25,13 +25,28 @@ namespace DistributedFS { namespace ModuleFileIO { class WatcherNExporter final : public NExporter { public: + class JSCallbackContext { + public: + JSCallbackContext() {} + ~JSCallbackContext() {} + + public: + napi_env env_; + napi_ref ref_; + std::string fileName_; + uint32_t event_; + napi_async_work work; + } + inline static const std::string className_ = "Watcher"; bool Export() override; std::string GetClassName() override; static napi_value Constructor(napi_env env, napi_callback_info info); + static napi_value Start(napi_env env, napi_callback_info info); static napi_value Stop(napi_env env, napi_callback_info info); + static void WatcherCallback(napi_env env, napi_ref callback, const std::string &fileName, const uint32_t &event); WatcherNExporter(napi_env env, napi_value exports); ~WatcherNExporter() override; -- Gitee From ef0326551e992244f00564149b0f14cc3fb944ed Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Fri, 20 Jan 2023 08:55:03 +0800 Subject: [PATCH 13/25] modify watcher Signed-off-by: Cao Chuan --- .../kits/js/src/mod_fileio/class_watcher/file_watcher.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp index 54375c698..c598a2eb5 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp @@ -60,13 +60,12 @@ bool FileWatcher::StartNotify(std::shared_ptr &arg, int &errCode bool FileWatcher::StopNotify(std::shared_ptr &arg, int &errCode) { HILOGI("FileWatcher StopObserver IN"); - + run_ = false; if (inotify_rm_watch(arg->fd, arg->wd) == -1) { errCode = errno; HILOGE("FileWatcher StopNotify fail errCode:%{public}d", errCode); return false; } - run_ = false; close(arg->fd); HILOGI("FileWatcher StopObserver OUT"); return true; -- Gitee From bb85c2e8b9fce21b4ecd9172454eb0743b4a1cac Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Fri, 20 Jan 2023 09:21:43 +0800 Subject: [PATCH 14/25] detail build error Signed-off-by: Cao Chuan --- .../mod_fileio/class_watcher/watcher_entity.h | 22 ------------------- .../class_watcher/watcher_n_exporter.cpp | 13 ++++++----- .../class_watcher/watcher_n_exporter.h | 2 +- 3 files changed, 9 insertions(+), 28 deletions(-) diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h index 1f6fdc6b5..f7127accf 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h @@ -26,21 +26,6 @@ namespace ModuleFileIO { #include #include #include - -class WatcherHandleDeleter { -public: - void operator()(uv_fs_event_t *ptr) - { - if (ptr == nullptr) { - return; - } - - uv_fs_event_stop(ptr); - uv_handle_t *handle = reinterpret_cast(ptr); - uv_close(handle, [](uv_handle_t *handle) { delete handle; }); - } -}; - struct WatcherInfoArg { std::string filename; std::vector events; @@ -50,15 +35,8 @@ struct WatcherInfoArg { napi_ref ref = nullptr; }; -struct WatcherResult { - std::string filename; - int32_t err; - uint32_t event; -}; - struct WatcherEntity { std::shared_ptr data_; - std::unique_ptr fsEventReq_; }; } // namespace ModuleFileIO } // namespace DistributedFS diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp index fbad911c6..cc69c5926 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp @@ -86,11 +86,14 @@ napi_value WatcherNExporter::Start(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "get watcherEntity fail"); return nullptr; } + int errCode = 0; + if(!watcherPtr_->StartNotify(watchEntity->data_, errCode)) { + UniError(errCode).ThrowErr(env); + return nullptr; + } - StartNotify(watchEntity->data); - - auto cbExec = [watchEntity](napi_env env, UniError err) -> UniError { - GetNotifyEvent(watchEntity->data, WatcherCallback); + auto cbExec = [watchEntity](napi_env env) -> UniError { + watcherPtr_->GetNotifyEvent(watchEntity->data_, WatcherCallback); return UniError(ERRNO_NOERR); }; @@ -125,7 +128,7 @@ void WatcherNExporter::WatcherCallback(napi_env env, // JSCallbackData* jsCallbackData = (JSCallbackData*)data; auto context = static_cast(data); napi_value jsCallback = nullptr; - napi_get_reference_value(env, context->ref, &jsCallback); + napi_get_reference_value(env, context->ref_, &jsCallback); vector argv; argv.push_back(NVal::CreateUTF8String(env, context->fileName_).val_); argv.push_back(NVal::CreateUint32(env, context->event_).val_); diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h index be4ea3823..76f6c646d 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h @@ -36,7 +36,7 @@ public: std::string fileName_; uint32_t event_; napi_async_work work; - } + }; inline static const std::string className_ = "Watcher"; -- Gitee From 212c26c5dcc6a8afde7d66515c66e5126144b26e Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Fri, 20 Jan 2023 09:44:23 +0800 Subject: [PATCH 15/25] add log Signed-off-by: Cao Chuan --- interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp index c598a2eb5..50248593e 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp @@ -79,6 +79,7 @@ void FileWatcher::HandleEvent(std::shared_ptr &arg, if (event->wd == arg->wd) { for (auto watchEvent : arg->events) { if (event->mask == watchEvent) { + HILOGI("FileWatcher HandleEvent fileName:%{public}s, mask:%{public}d", event->name, event->mask); callback(arg->env, arg->ref, event->name, event->mask); } } -- Gitee From 35b8e65bcdbb407f4a10dbc3731761c5dd3e8cc6 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Sun, 29 Jan 2023 18:19:08 +0800 Subject: [PATCH 16/25] add log Signed-off-by: Cao Chuan --- .../mod_fileio/class_watcher/file_watcher.cpp | 21 +++++++++++++------ .../mod_fileio/class_watcher/watcher_entity.h | 2 -- .../js/src/mod_fileio/properties/watcher.cpp | 1 - 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp index 50248593e..ccdd89797 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp @@ -77,6 +77,7 @@ void FileWatcher::HandleEvent(std::shared_ptr &arg, { HILOGI("FileWatcher HandleEvent IN"); if (event->wd == arg->wd) { + HILOGI("FileWatcher HandleEvent event->wd == arg->wd"); for (auto watchEvent : arg->events) { if (event->mask == watchEvent) { HILOGI("FileWatcher HandleEvent fileName:%{public}s, mask:%{public}d", event->name, event->mask); @@ -92,14 +93,22 @@ void FileWatcher::GetNotifyEvent(std::shared_ptr &arg, WatcherCa HILOGI("FileWatcher GetNotifyEvent IN"); char buf[BUF_SIZE] = {0}; struct inotify_event *event = nullptr; - fd_set fds; - FD_ZERO(&fds); - FD_SET(arg->fd, &fds); while (run_) { - if (select(arg->fd + 1, &fds, NULL, NULL, NULL) > 0) { + int fd = arg->fd; + fd_set fds; + FD_ZERO(&fds); + FD_SET(fd, &fds); + HILOGI("FileWatcher GetNotifyEvent fd:%{public}d", fd); + if (select(fd + 1, &fds, NULL, NULL, NULL) > 0) { + HILOGI("FileWatcher GetNotifyEvent fd+1:%{public}d", fd + 1); int len, index = 0; - while (((len = read(arg->fd, &buf, sizeof(buf))) < 0) && (errno == EINTR)) { + if(errno == EINTR) { + HILOGI("FileWatcher GetNotifyEvent errno == EINT"); + } + while (((len = read(fd, &buf, sizeof(buf))) < 0) && (errno == EINTR)) { + HILOGI("FileWatcher GetNotifyEvent read"); while (index < len) { + HILOGI("FileWatcher GetNotifyEvent index < len"); event = (struct inotify_event *)(buf + index); HandleEvent(arg, event, callback); index += sizeof(struct inotify_event) + event->len; @@ -111,4 +120,4 @@ void FileWatcher::GetNotifyEvent(std::shared_ptr &arg, WatcherCa } } // namespace ModuleFileIO } // namespace DistributedFS -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h index f7127accf..acb57c72c 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h @@ -17,9 +17,7 @@ #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_ENTITY_H #include - #include "../../common/napi/uni_header.h" - namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp index 35da67dce..e4a671e41 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp @@ -68,7 +68,6 @@ napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) data->filename = string(filename.get()); data->fd = fd; - NVal val = NVal(env, funcArg[NARG_POS::THIRD]); napi_create_reference(val.env_, val.val_, 1, &(data->ref)); -- Gitee From 84b62ee618e4df9aba2e83fce3ca8673619eae95 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Mon, 30 Jan 2023 09:36:49 +0800 Subject: [PATCH 17/25] modify file watcher Signed-off-by: Cao Chuan --- .../mod_fileio/class_watcher/file_watcher.cpp | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp index ccdd89797..47d12d766 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp @@ -79,9 +79,10 @@ void FileWatcher::HandleEvent(std::shared_ptr &arg, if (event->wd == arg->wd) { HILOGI("FileWatcher HandleEvent event->wd == arg->wd"); for (auto watchEvent : arg->events) { - if (event->mask == watchEvent) { + if (event->mask == watchEvent || watchEvent == IN_ALL_EVENTS) { HILOGI("FileWatcher HandleEvent fileName:%{public}s, mask:%{public}d", event->name, event->mask); - callback(arg->env, arg->ref, event->name, event->mask); + std::string filename = arg->filename + "/" + event->name; + callback(arg->env, arg->ref, filename, event->mask); } } } @@ -105,19 +106,17 @@ void FileWatcher::GetNotifyEvent(std::shared_ptr &arg, WatcherCa if(errno == EINTR) { HILOGI("FileWatcher GetNotifyEvent errno == EINT"); } - while (((len = read(fd, &buf, sizeof(buf))) < 0) && (errno == EINTR)) { - HILOGI("FileWatcher GetNotifyEvent read"); - while (index < len) { - HILOGI("FileWatcher GetNotifyEvent index < len"); - event = (struct inotify_event *)(buf + index); - HandleEvent(arg, event, callback); - index += sizeof(struct inotify_event) + event->len; - } - } + while (((len = read(fd, &buf, sizeof(buf))) < 0) && (errno == EINTR)); + while (index < len) { + HILOGI("FileWatcher GetNotifyEvent index < len"); + event = (struct inotify_event *)(buf + index); + HandleEvent(arg, event, callback); + index += sizeof(struct inotify_event) + event->len; + } } } HILOGI("FileWatcher GetNotifyEvent OUT"); } } // namespace ModuleFileIO } // namespace DistributedFS -} // namespace OHOS +} // namespace OHOS \ No newline at end of file -- Gitee From ea6fa2a11498dc6b63b111da50fef80d0e0e8721 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Mon, 30 Jan 2023 09:58:05 +0800 Subject: [PATCH 18/25] modify watcher Signed-off-by: Cao Chuan --- .../kits/js/src/mod_fileio/class_watcher/file_watcher.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp index 47d12d766..7efcdf56e 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp @@ -80,8 +80,8 @@ void FileWatcher::HandleEvent(std::shared_ptr &arg, HILOGI("FileWatcher HandleEvent event->wd == arg->wd"); for (auto watchEvent : arg->events) { if (event->mask == watchEvent || watchEvent == IN_ALL_EVENTS) { - HILOGI("FileWatcher HandleEvent fileName:%{public}s, mask:%{public}d", event->name, event->mask); std::string filename = arg->filename + "/" + event->name; + HILOGI("FileWatcher HandleEvent fileName:%{public}s, mask:%{public}d", filename, event->mask); callback(arg->env, arg->ref, filename, event->mask); } } -- Gitee From 7f0e825d1ca372df81573dda728b0d66e38f5513 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Mon, 30 Jan 2023 10:07:31 +0800 Subject: [PATCH 19/25] modify build error Signed-off-by: Cao Chuan --- .../kits/js/src/mod_fileio/class_watcher/file_watcher.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp index 7efcdf56e..a9c32a1dc 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp @@ -81,7 +81,7 @@ void FileWatcher::HandleEvent(std::shared_ptr &arg, for (auto watchEvent : arg->events) { if (event->mask == watchEvent || watchEvent == IN_ALL_EVENTS) { std::string filename = arg->filename + "/" + event->name; - HILOGI("FileWatcher HandleEvent fileName:%{public}s, mask:%{public}d", filename, event->mask); + HILOGI("FileWatcher HandleEvent fileName:%{public}s, mask:%{public}d", filename.c_str(), event->mask); callback(arg->env, arg->ref, filename, event->mask); } } -- Gitee From 683575f1064aa16adcc78d0497e7f3ec7e839a91 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Mon, 30 Jan 2023 16:58:11 +0800 Subject: [PATCH 20/25] modify NAPI Signed-off-by: Cao Chuan --- .../class_watcher/watcher_n_exporter.cpp | 14 +++++++------- .../mod_fileio/class_watcher/watcher_n_exporter.h | 4 ++-- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp index cc69c5926..2b32f8fb8 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp @@ -129,17 +129,17 @@ void WatcherNExporter::WatcherCallback(napi_env env, auto context = static_cast(data); napi_value jsCallback = nullptr; napi_get_reference_value(env, context->ref_, &jsCallback); - vector argv; - argv.push_back(NVal::CreateUTF8String(env, context->fileName_).val_); - argv.push_back(NVal::CreateUint32(env, context->event_).val_); + NVal objn = NVal::CreateObject(env); + objn.AddProp("fileName", NVal::CreateUTF8String(env, context->fileName_).val_); + objn.AddProp("event", NVal::CreateUint32(env, context->event_).val_); napi_value global = nullptr; napi_get_global(env, &global); napi_value jsObj = nullptr; - napi_call_function(env, global, jsCallback, argv.size(), argv.data(), &jsObj); - napi_delete_async_work(env, context->work); + napi_call_function(env, global, jsCallback, 1, &(objn.val_), &jsObj); + napi_delete_async_work(env, context->work_); }, - static_cast(callbackContext.get()), &callbackContext->work); - napi_queue_async_work(env, callbackContext->work); + static_cast(callbackContext.get()), &callbackContext->work_); + napi_queue_async_work(env, callbackContext->work_); callbackContext.release(); } diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h index 76f6c646d..7bbc67739 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h @@ -35,7 +35,7 @@ public: napi_ref ref_; std::string fileName_; uint32_t event_; - napi_async_work work; + napi_async_work work_; }; inline static const std::string className_ = "Watcher"; @@ -57,4 +57,4 @@ private: } // namespace ModuleFileIO } // namespace DistributedFS } // namespace OHOS -#endif +#endif \ No newline at end of file -- Gitee From c0de1d6e87fbea2ab72af2c236850f9c674c3749 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Tue, 31 Jan 2023 10:49:23 +0800 Subject: [PATCH 21/25] modify format Signed-off-by: Cao Chuan --- interfaces/kits/js/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index b427d1251..28f71b80a 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -52,8 +52,8 @@ ohos_shared_library("fileio") { "src/mod_fileio/class_stat/stat_n_exporter.cpp", "src/mod_fileio/class_stream/flush.cpp", "src/mod_fileio/class_stream/stream_n_exporter.cpp", - "src/mod_fileio/class_watcher/watcher_n_exporter.cpp", "src/mod_fileio/class_watcher/file_watcher.cpp", + "src/mod_fileio/class_watcher/watcher_n_exporter.cpp", "src/mod_fileio/common_func.cpp", "src/mod_fileio/module.cpp", "src/mod_fileio/properties/chmod.cpp", -- Gitee From 704ec26dbbfc88c8769aa957a44013c1fa927976 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Thu, 2 Feb 2023 08:49:33 +0800 Subject: [PATCH 22/25] add tdd Signed-off-by: Cao Chuan --- interfaces/test/unittest/BUILD.gn | 5 +- .../test/unittest/file_watcher/BUILD.gn | 43 ++ .../file_watcher/file_watcher_test.cpp | 380 ++++++++++++++++++ 3 files changed, 427 insertions(+), 1 deletion(-) create mode 100644 interfaces/test/unittest/file_watcher/BUILD.gn create mode 100644 interfaces/test/unittest/file_watcher/file_watcher_test.cpp diff --git a/interfaces/test/unittest/BUILD.gn b/interfaces/test/unittest/BUILD.gn index 4351bd3fe..d74288bc7 100644 --- a/interfaces/test/unittest/BUILD.gn +++ b/interfaces/test/unittest/BUILD.gn @@ -13,5 +13,8 @@ group("unittest") { testonly = true - deps = [ "remote_uri:remote_uri_test" ] + deps = [ + "remote_uri:remote_uri_test", + "file_watcher:file_watcher_test" + ] } diff --git a/interfaces/test/unittest/file_watcher/BUILD.gn b/interfaces/test/unittest/file_watcher/BUILD.gn new file mode 100644 index 000000000..fdfc92061 --- /dev/null +++ b/interfaces/test/unittest/file_watcher/BUILD.gn @@ -0,0 +1,43 @@ +# Copyright (c) 2022 Huawei Device 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. + +import("//build/test.gni") + +ohos_unittest("file_watcher_test") { + module_out_path = "filemanagement/file_api" + + resource_config_file = "../resource/ohos_test.xml" + + sources = [ "file_watcher_test.cpp" ] + + include_dirs = [ + "include", + "//utils/system/safwk/native/include", + "//commonlibrary/c_utils/base/include", + "//foundation/filemanagement/file_api/interfaces/kits/js/src/common/napi", + "//foundation/filemanagement/file_api/interfaces/kits/js/src/mod_fileio/class_watcher", + "//third_party/libuv/include", + ] + + deps = [ + "//foundation/filemanagement/file_api/interfaces/kits/js:fileio", + "//third_party/googletest:gtest_main", + "//foundation/arkui/napi:ace_napi", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "ipc:ipc_core", + ] +} diff --git a/interfaces/test/unittest/file_watcher/file_watcher_test.cpp b/interfaces/test/unittest/file_watcher/file_watcher_test.cpp new file mode 100644 index 000000000..0a1db2167 --- /dev/null +++ b/interfaces/test/unittest/file_watcher/file_watcher_test.cpp @@ -0,0 +1,380 @@ +/* +* Copyright (c) 2022 Huawei Device 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. +*/ + +#include "file_watcher.h" +#include +#include +#include +#include +#include +#include +#include +#include +namespace { + using namespace std; + using namespace OHOS::DistributedFS::ModuleFileIO; + + class FileWatcherTest : public testing::Test { + public: + static void SetUpTestCase(void){}; + static void TearDownTestCase(){}; + void SetUp(){}; + void TearDown(){}; + }; + + + void WatcherCallback(napi_env env, napi_ref callback, const std::string &filename, const uint32_t &event) + { + string path = "/data/data/test2"; + EXPECT_STREQ(path.c_str(), filename.c_str()); + if (event == IN_CLOSE || event == IN_DELETE) { + EXPECT_TRUE(true); + } else { + EXPECT_TRUE(false); + } + } + + void GetEvent(shared_ptr &fileWatcherPtr, std::shared_ptr &arg) + { + fileWatcherPtr->GetNotifyEvent(arg, WatcherCallback); + } + + /** + * @tc.name: Watcher_InitNotify_0000 + * @tc.desc: Test function of InitNotify() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000HG8M4 + */ + HWTEST_F(FileWatcherTest, Watcher_InitNotify_0000, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "FileWatcherTest-begin Watcher_InitNotify_0000"; + int fd = 0; + int error = 0; + + shared_ptr fileWatcherPtr = make_shared(); + bool ret = fileWatcherPtr->InitNotify(fd, error); + + EXPECT_TRUE(fd > 0); + EXPECT_TRUE(error == 0); + EXPECT_TRUE(ret == true); + + GTEST_LOG_(INFO) << "FileWatcherTest-end Watcher_InitNotify_0000"; + } + + /** + * @tc.name: Watcher_StartNotify_0000 + * @tc.desc: Test function of StartNotify() interface for FAIL. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000HG8M4 + */ + HWTEST_F(FileWatcherTest, Watcher_StartNotify_0000, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "FileWatcherTest-begin Watcher_StartNotify_0000"; + int error = 0; + std::shared_ptr arg = make_shared(); + shared_ptr fileWatcherPtr = make_shared(); + bool ret = fileWatcherPtr->StartNotify(arg, error); + EXPECT_TRUE(ret == false); + EXPECT_TRUE(error > 0); + + GTEST_LOG_(INFO) << "FileWatcherTest-end Watcher_StartNotify_0000"; + } + + /** + * @tc.name: Watcher_StartNotify_0001 + * @tc.desc: Test function of StartNotify() interface for FAIL. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000HG8M4 + */ + HWTEST_F(FileWatcherTest, Watcher_StartNotify_0001, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "FileWatcherTest-begin Watcher_StartNotify_0001"; + int error = 0; + std::shared_ptr arg = make_shared(); + arg->fd = 10; + + shared_ptr fileWatcherPtr = make_shared(); + bool ret = fileWatcherPtr->StartNotify(arg, error); + EXPECT_TRUE(ret == false); + EXPECT_TRUE(error > 0); + + GTEST_LOG_(INFO) << "FileWatcherTest-end Watcher_StartNotify_0001"; + } + + /** + * @tc.name: Watcher_StartNotify_0002 + * @tc.desc: Test function of StartNotify() interface for FAIL. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000HG8M4 + */ + HWTEST_F(FileWatcherTest, Watcher_StartNotify_0002, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "FileWatcherTest-begin Watcher_StartNotify_0002"; + int fd = 0; + int error = 0; + bool ret = false; + + shared_ptr fileWatcherPtr = make_shared(); + ret = fileWatcherPtr->InitNotify(fd, error); + EXPECT_TRUE(fd > 0); + EXPECT_TRUE(ret == true); + + std::shared_ptr arg = make_shared(); + arg->fd = fd; + arg->filename = ""; + + ret = fileWatcherPtr->StartNotify(arg, error); + EXPECT_TRUE(ret == false); + EXPECT_TRUE(error > 0); + + GTEST_LOG_(INFO) << "FileWatcherTest-end Watcher_StartNotify_0002"; + } + + /** + * @tc.name: Watcher_StartNotify_0003 + * @tc.desc: Test function of StartNotify() interface for FAIL. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000HG8M4 + */ + HWTEST_F(FileWatcherTest, Watcher_StartNotify_0003, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "FileWatcherTest-begin Watcher_StartNotify_0003"; + int fd = 0; + int error = 0; + bool ret = false; + + shared_ptr fileWatcherPtr = make_shared(); + ret = fileWatcherPtr->InitNotify(fd, error); + EXPECT_TRUE(fd > 0); + EXPECT_TRUE(ret == true); + + std::shared_ptr arg = make_shared(); + arg->fd = fd; + arg->filename = "/data/data"; + + ret = fileWatcherPtr->StartNotify(arg, error); + EXPECT_TRUE(ret == false); + EXPECT_TRUE(error > 0); + + GTEST_LOG_(INFO) << "FileWatcherTest-end Watcher_StartNotify_0003"; + } + + /** + * @tc.name: Watcher_StartNotify_0004 + * @tc.desc: Test function of StartNotify() interface for FAIL. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000HG8M4 + */ + HWTEST_F(FileWatcherTest, Watcher_StartNotify_0004, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "FileWatcherTest-begin Watcher_StartNotify_0004"; + int fd = 0; + int error = 0; + bool ret = false; + + shared_ptr fileWatcherPtr = make_shared(); + ret = fileWatcherPtr->InitNotify(fd, error); + EXPECT_TRUE(fd > 0); + EXPECT_TRUE(ret == true); + + std::vector events; + events.push_back(0); + + std::shared_ptr arg = make_shared(); + arg->fd = fd; + arg->filename = "/data/data"; + arg->events = events; + + ret = fileWatcherPtr->StartNotify(arg, error); + EXPECT_TRUE(ret == false); + EXPECT_TRUE(error > 0); + + GTEST_LOG_(INFO) << "FileWatcherTest-end Watcher_StartNotify_0004"; + } + + /** + * @tc.name: Watcher_StartNotify_0005 + * @tc.desc: Test function of StartNotify() interface for FAIL. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000HG8M4 + */ + HWTEST_F(FileWatcherTest, Watcher_StartNotify_0005, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "FileWatcherTest-begin Watcher_StartNotify_0005"; + int fd = 0; + int error = 0; + bool ret = false; + + shared_ptr fileWatcherPtr = make_shared(); + ret = fileWatcherPtr->InitNotify(fd, error); + EXPECT_TRUE(fd > 0); + EXPECT_TRUE(ret == true); + + std::vector events; + events.push_back(IN_ACCESS); + + std::shared_ptr arg = make_shared(); + arg->fd = fd; + arg->filename = "/data/test"; + arg->events = events; + + ret = fileWatcherPtr->StartNotify(arg, error); + EXPECT_TRUE(ret == false); + EXPECT_TRUE(error > 0); + + GTEST_LOG_(INFO) << "FileWatcherTest-end Watcher_StartNotify_0005"; + } + + /** + * @tc.name: Watcher_StartNotify_0006 + * @tc.desc: Test function of StartNotify() interface for FAIL. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000HG8M4 + */ + HWTEST_F(FileWatcherTest, Watcher_StartNotify_0006, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "FileWatcherTest-begin Watcher_StartNotify_0006"; + int fd = 0; + int error = 0; + bool ret = false; + + shared_ptr fileWatcherPtr = make_shared(); + ret = fileWatcherPtr->InitNotify(fd, error); + EXPECT_TRUE(fd > 0); + EXPECT_TRUE(ret == true); + + std::vector events; + events.push_back(IN_ACCESS); + + std::shared_ptr arg = make_shared(); + arg->fd = fd; + arg->filename = "/data/test"; + arg->events = events; + + ret = fileWatcherPtr->StartNotify(arg, error); + EXPECT_TRUE(ret == false); + EXPECT_TRUE(error > 0); + + GTEST_LOG_(INFO) << "FileWatcherTest-end Watcher_StartNotify_0006"; + } + + /** + * @tc.name: Watcher_StartNotify_0007 + * @tc.desc: Test function of StartNotify() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000HG8M4 + */ + HWTEST_F(FileWatcherTest, Watcher_StartNotify_0007, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "FileWatcherTest-begin Watcher_StartNotify_0007"; + int fd = 0; + int error = 0; + bool ret = false; + string filename = "/data/data/test"; + int fileFd = open(filename.c_str(), O_CREAT); + EXPECT_TRUE(fileFd > 0); + + shared_ptr fileWatcherPtr = make_shared(); + ret = fileWatcherPtr->InitNotify(fd, error); + EXPECT_TRUE(fd > 0); + EXPECT_TRUE(ret == true); + + std::vector events; + events.push_back(IN_ACCESS); + + std::shared_ptr arg = make_shared(); + arg->fd = fd; + arg->filename = filename; + arg->events = events; + + ret = fileWatcherPtr->StartNotify(arg, error); + EXPECT_TRUE(ret == true); + EXPECT_TRUE(error == 0); + + ret = fileWatcherPtr->StopNotify(arg, error); + EXPECT_TRUE(ret == true); + GTEST_LOG_(INFO) << "FileWatcherTest-end Watcher_StartNotify_0007"; + } + + /** + * @tc.name: Watcher_GetNotifyEvent_0000 + * @tc.desc: Test function of GetNotifyEvent() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: AR000HG8M4 + */ + HWTEST_F(FileWatcherTest, Watcher_GetNotifyEvent_0000, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "FileWatcherTest-begin Watcher_GetNotifyEvent_0000"; + int fd = 0; + int error = 0; + bool ret = false; + + shared_ptr fileWatcherPtr = make_shared(); + ret = fileWatcherPtr->InitNotify(fd, error); + EXPECT_TRUE(fd > 0); + EXPECT_TRUE(ret == true); + + string filename = "/data/data/test2"; + int fileFd = open(filename.c_str(), O_CREAT); + EXPECT_TRUE(fileFd > 0); + + std::vector events; + events.push_back(IN_CLOSE); + events.push_back(IN_DELETE); + + std::shared_ptr arg = make_shared(); + arg->fd = fd; + arg->filename = filename; + arg->events = events; + + ret = fileWatcherPtr->StartNotify(arg, error); + EXPECT_TRUE(error == 0); + EXPECT_TRUE(ret == true); + + thread t(GetEvent, ref(fileWatcherPtr), ref(arg)); + t.detach(); + + this_thread::sleep_for(chrono::seconds(2)); + int clsoeRet = close(fileFd); + EXPECT_TRUE(clsoeRet == 0); + + this_thread::sleep_for(chrono::seconds(2)); + int removeRet = remove(filename.c_str()); + EXPECT_TRUE(removeRet == 0); + + GTEST_LOG_(INFO) << "FileWatcherTest-end Watcher_GetNotifyEvent_0000"; + } + +} // namespace \ No newline at end of file -- Gitee From b53358b45fafa521c4e376056986dada3ac713b4 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Fri, 3 Feb 2023 13:11:13 +0800 Subject: [PATCH 23/25] add to mod_fs Signed-off-by: Cao Chuan --- interfaces/kits/js/BUILD.gn | 3 + .../src/mod_fs/class_watcher/file_watcher.cpp | 100 ++++++++++ .../src/mod_fs/class_watcher/file_watcher.h | 43 +++++ .../src/mod_fs/class_watcher/watcher_entity.h | 37 ++++ .../class_watcher/watcher_n_exporter.cpp | 172 ++++++++++++++++++ .../mod_fs/class_watcher/watcher_n_exporter.h | 57 ++++++ interfaces/kits/js/src/mod_fs/module.cpp | 4 +- .../kits/js/src/mod_fs/properties/watcher.cpp | 81 +++++++++ .../kits/js/src/mod_fs/properties/watcher.h | 26 +++ utils/filemgmt_libn/include/n_val.h | 3 + utils/filemgmt_libn/src/n_val.cpp | 30 +++ 11 files changed, 555 insertions(+), 1 deletion(-) create mode 100644 interfaces/kits/js/src/mod_fs/class_watcher/file_watcher.cpp create mode 100644 interfaces/kits/js/src/mod_fs/class_watcher/file_watcher.h create mode 100644 interfaces/kits/js/src/mod_fs/class_watcher/watcher_entity.h create mode 100644 interfaces/kits/js/src/mod_fs/class_watcher/watcher_n_exporter.cpp create mode 100644 interfaces/kits/js/src/mod_fs/class_watcher/watcher_n_exporter.h create mode 100644 interfaces/kits/js/src/mod_fs/properties/watcher.cpp create mode 100644 interfaces/kits/js/src/mod_fs/properties/watcher.h diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 28f71b80a..b34a66507 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -118,6 +118,8 @@ ohos_shared_library("fs") { "src/common/file_helper/fd_guard.cpp", "src/mod_fs/class_file/file_n_exporter.cpp", "src/mod_fs/class_stat/stat_n_exporter.cpp", + "src/mod_fs/class_watcher/file_watcher.cpp", + "src/mod_fs/class_watcher/watcher_n_exporter.cpp", "src/mod_fs/common_func.cpp", "src/mod_fs/module.cpp", "src/mod_fs/properties/lstat.cpp", @@ -126,6 +128,7 @@ ohos_shared_library("fs") { "src/mod_fs/properties/stat.cpp", "src/mod_fs/properties/symlink.cpp", "src/mod_fs/properties/truncate.cpp", + "src/mod_fs/properties/watcher.cpp", ] deps = [ diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/file_watcher.cpp b/interfaces/kits/js/src/mod_fs/class_watcher/file_watcher.cpp new file mode 100644 index 000000000..d6b0f8f69 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_watcher/file_watcher.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2021 Huawei Device 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. + */ +#include "file_watcher.h" +#include +#include +#include "filemgmt_libhilog.h" +#include "uv.h" +namespace OHOS::FileManagement::ModuleFileIO { +using namespace OHOS::FileManagement::LibN; +const int BUF_SIZE = 1024; +FileWatcher::FileWatcher() {} + +FileWatcher::~FileWatcher() {} + +bool FileWatcher::InitNotify(int &fd) +{ + fd = inotify_init(); + if (fd == -1) { + HILOGE("FileWatcher InitNotify fail errCode:%{public}d", errno); + return false; + } + return true; +} + +bool FileWatcher::StartNotify(std::shared_ptr &arg) +{ + int wd = 0; + uint32_t watchEvent = 0; + for (auto event : arg->events) { + watchEvent = watchEvent | event; + } + wd = inotify_add_watch(arg->fd, arg->filename.c_str(), watchEvent); + if(wd == -1) { + HILOGE("FileWatcher StartNotify fail errCode:%{public}d", errno); + return false; + } + arg->wd = wd; + run_ = true; + return true; +} + +bool FileWatcher::StopNotify(std::shared_ptr &arg) +{ + run_ = false; + if (inotify_rm_watch(arg->fd, arg->wd) == -1) { + HILOGE("FileWatcher StopNotify fail errCode:%{public}d", errno); + return false; + } + close(arg->fd); + return true; +} + +void FileWatcher::HandleEvent(std::shared_ptr &arg, + const struct inotify_event *event, + WatcherCallback callback) +{ + if (event->wd == arg->wd) { + for (auto watchEvent : arg->events) { + if (event->mask == watchEvent || watchEvent == IN_ALL_EVENTS) { + std::string filename = arg->filename + "/" + event->name; + HILOGI("FileWatcher HandleEvent fileName:%{public}s, mask:%{public}d", filename.c_str(), event->mask); + callback(arg->env, arg->ref, filename, event->mask); + } + } + } +} + +void FileWatcher::GetNotifyEvent(std::shared_ptr &arg, WatcherCallback callback) +{ + char buf[BUF_SIZE] = {0}; + struct inotify_event *event = nullptr; + while (run_) { + int fd = arg->fd; + fd_set fds; + FD_ZERO(&fds); + FD_SET(fd, &fds); + if (select(fd + 1, &fds, NULL, NULL, NULL) > 0) { + int len, index = 0; + while (((len = read(fd, &buf, sizeof(buf))) < 0) && (errno == EINTR)); + while (index < len) { + event = (struct inotify_event *)(buf + index); + HandleEvent(arg, event, callback); + index += sizeof(struct inotify_event) + event->len; + } + } + } +} +} // namespace OHOS::FileManagement::ModuleFileIO \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/file_watcher.h b/interfaces/kits/js/src/mod_fs/class_watcher/file_watcher.h new file mode 100644 index 000000000..ae11351ba --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_watcher/file_watcher.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device 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. + */ + +#ifndef FILE_WATCHER_H +#define FILE_WATCHER_H +#include +#include +#include +#include "watcher_entity.h" +namespace OHOS::FileManagement::ModuleFileIO { +using WatcherCallback = void (*)(napi_env env, napi_ref callback, const std::string &filename, const uint32_t &event); +struct ErrorInfo { + int errCode; + std::string errMsg; +}; + +class FileWatcher { +public: + FileWatcher(); + ~FileWatcher(); + bool InitNotify(int &fd); + bool StartNotify(std::shared_ptr &arg); + bool StopNotify(std::shared_ptr &arg); + void GetNotifyEvent(std::shared_ptr &arg, WatcherCallback callback); + +private: + void HandleEvent(std::shared_ptr &arg, const struct inotify_event *event, WatcherCallback callback); + bool run_; +}; +} // namespace OHOS::FileManagement::ModuleFileIO +#endif diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/watcher_entity.h b/interfaces/kits/js/src/mod_fs/class_watcher/watcher_entity.h new file mode 100644 index 000000000..e11891195 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_watcher/watcher_entity.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021 Huawei Device 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_ENTITY_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_ENTITY_H +#include +#include +#include +#include "filemgmt_libn.h" +namespace OHOS::FileManagement::ModuleFileIO { + +struct WatcherInfoArg { + std::string filename; + std::vector events; + int fd; + int wd; + napi_env env = nullptr; + napi_ref ref = nullptr; +}; + +struct WatcherEntity { + std::shared_ptr data_; +}; +} // namespace OHOS::FileManagement::ModuleFileIO namespace OHOS +#endif diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/watcher_n_exporter.cpp b/interfaces/kits/js/src/mod_fs/class_watcher/watcher_n_exporter.cpp new file mode 100644 index 000000000..042bfee9a --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_watcher/watcher_n_exporter.cpp @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2021 Huawei Device 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. + */ + +#include "watcher_n_exporter.h" + +#include +#include +#include +#include +#include "filemgmt_libn.h" +#include "filemgmt_libhilog.h" +#include "../common_func.h" +#include "securec.h" + +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; +using namespace OHOS::FileManagement::LibN; + +std::shared_ptr WatcherNExporter::watcherPtr_; +napi_value WatcherNExporter::Constructor(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + unique_ptr watcherEntity = make_unique(); + if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(watcherEntity))) { + NError(EIO).ThrowErr(env, "INNER BUG. Failed to wrap entity for obj stat"); + return nullptr; + } + + watcherPtr_ = make_shared(); + return funcArg.GetThisVar(); +} + +napi_value WatcherNExporter::Stop(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto watchEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!watchEntity) { + NError(EINVAL).ThrowErr(env, "get watcherEntity fail"); + return nullptr; + } + if (!watcherPtr_->StopNotify(watchEntity->data_)) { + NError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +napi_value WatcherNExporter::Start(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto watchEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!watchEntity) { + NError(EINVAL).ThrowErr(env, "get watcherEntity fail"); + return nullptr; + } + if(!watcherPtr_->StartNotify(watchEntity->data_)) { + NError(errno).ThrowErr(env); + return nullptr; + } + + auto cbExec = [watchEntity]() -> NError { + watcherPtr_->GetNotifyEvent(watchEntity->data_, WatcherCallback); + return NError(ERRNO_NOERR); + }; + + auto cbCompl = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return {NVal::CreateUndefined(env)}; + }; + + const string procedureName = "FileIOStartWatcher"; + NVal thisVar(env, funcArg.GetThisVar()); + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; +} + +void WatcherNExporter::WatcherCallback(napi_env env, + napi_ref callback, + const std::string &fileName, + const uint32_t &event) +{ + auto callbackContext = make_unique(); + callbackContext->env_ = env; + callbackContext->ref_ = callback; + callbackContext->fileName_ = fileName; + callbackContext->event_ = event; + napi_value resource = nullptr; + napi_create_string_utf8(env, "FileIOCreateWatcher", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( + env, nullptr, resource, [](napi_env env, void *data) {}, + [](napi_env env, napi_status status, void *data) { + // JSCallbackData* jsCallbackData = (JSCallbackData*)data; + auto context = static_cast(data); + napi_value jsCallback = nullptr; + napi_get_reference_value(env, context->ref_, &jsCallback); + NVal objn = NVal::CreateObject(env); + objn.AddProp("fileName", NVal::CreateUTF8String(env, context->fileName_).val_); + objn.AddProp("event", NVal::CreateUint32(env, context->event_).val_); + napi_value global = nullptr; + napi_get_global(env, &global); + napi_value jsObj = nullptr; + napi_call_function(env, global, jsCallback, 1, &(objn.val_), &jsObj); + napi_delete_async_work(env, context->work_); + }, + static_cast(callbackContext.get()), &callbackContext->work_); + napi_queue_async_work(env, callbackContext->work_); + callbackContext.release(); +} + +bool WatcherNExporter::Export() +{ + vector props = { + NVal::DeclareNapiFunction("start", Start), + NVal::DeclareNapiFunction("stop", Stop), + }; + + string className = GetClassName(); + auto [resDefineClass, classValue] = + NClass::DefineClass(exports_.env_, className, WatcherNExporter::Constructor, std::move(props)); + if (!resDefineClass) { + NError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to define class"); + return false; + } + + bool succ = NClass::SaveClass(exports_.env_, className, classValue); + if (!succ) { + NError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to save class"); + return false; + } + + return exports_.AddProp(className, classValue); +} + +string WatcherNExporter::GetClassName() +{ + return WatcherNExporter::className_; +} + +WatcherNExporter::WatcherNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} + +WatcherNExporter::~WatcherNExporter() {} +} // namespace OHOS::FileManagement::ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fs/class_watcher/watcher_n_exporter.h b/interfaces/kits/js/src/mod_fs/class_watcher/watcher_n_exporter.h new file mode 100644 index 000000000..b4e053386 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_watcher/watcher_n_exporter.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_N_EXPORTER_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_N_EXPORTER_H +#include +#include +#include "watcher_entity.h" +#include "file_watcher.h" +#include "filemgmt_libn.h" +namespace OHOS::FileManagement::ModuleFileIO { +using namespace OHOS::FileManagement::LibN; +class WatcherNExporter final : public NExporter { +public: + class JSCallbackContext { + public: + JSCallbackContext() {} + ~JSCallbackContext() {} + + public: + napi_env env_; + napi_ref ref_; + std::string fileName_; + uint32_t event_; + napi_async_work work_; + }; + + inline static const std::string className_ = "Watcher"; + + bool Export() override; + std::string GetClassName() override; + + static napi_value Constructor(napi_env env, napi_callback_info info); + static napi_value Start(napi_env env, napi_callback_info info); + static napi_value Stop(napi_env env, napi_callback_info info); + static void WatcherCallback(napi_env env, napi_ref callback, const std::string &fileName, const uint32_t &event); + + WatcherNExporter(napi_env env, napi_value exports); + ~WatcherNExporter() override; + +private: + static std::shared_ptr watcherPtr_; +}; +} // namespace OHOS::FileManagement::ModuleFileIO +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/module.cpp b/interfaces/kits/js/src/mod_fs/module.cpp index 936045839..b4e7e3afb 100644 --- a/interfaces/kits/js/src/mod_fs/module.cpp +++ b/interfaces/kits/js/src/mod_fs/module.cpp @@ -20,6 +20,7 @@ #include "class_file/file_n_exporter.h" #include "class_stat/stat_n_exporter.h" +#include "class_watcher/watcher_n_exporter.h" #include "filemgmt_libhilog.h" #include "properties/prop_n_exporter.h" @@ -35,6 +36,7 @@ static napi_value Export(napi_env env, napi_value exports) products.emplace_back(make_unique(env, exports)); products.emplace_back(make_unique(env, exports)); products.emplace_back(make_unique(env, exports)); + products.emplace_back(make_unique(env, exports)); for (auto &&product : products) { if (!product->Export()) { @@ -50,4 +52,4 @@ static napi_value Export(napi_env env, napi_value exports) NAPI_MODULE(fs, Export) } // namespace ModuleFileIO } // namespace FileManagement -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fs/properties/watcher.cpp b/interfaces/kits/js/src/mod_fs/properties/watcher.cpp new file mode 100644 index 000000000..0115353b5 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/watcher.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device 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. + */ + +#include "watcher.h" +#include +#include +#include +#include +#include +#include "filemgmt_libhilog.h" +#include "../class_watcher/file_watcher.h" +#include "../class_watcher/watcher_entity.h" +#include "../class_watcher/watcher_n_exporter.h" +namespace OHOS::FileManagement::ModuleFileIO { +using namespace std; +using namespace OHOS::FileManagement::LibN; +napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::THREE)) { + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto [succGetPath, filename, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succGetPath) { + NError(EINVAL).ThrowErr(env, "Invalid filename"); + return nullptr; + } + + auto [succGetEvent, events, size] = NVal(env, funcArg[NARG_POS::SECOND]).ToUint32Array(); + if (!succGetEvent) { + NError(EINVAL).ThrowErr(env, "Invalid event"); + return nullptr; + } + + int fd = 0; + shared_ptr watcherPtr = make_shared(); + if (!watcherPtr->InitNotify(fd)) { + NError(errno).ThrowErr(env); + return nullptr; + } + + shared_ptr data = make_shared(); + data->events = events; + data->env = env; + data->filename = string(filename.get()); + data->fd = fd; + + NVal val = NVal(env, funcArg[NARG_POS::THIRD]); + napi_create_reference(val.env_, val.val_, 1, &(data->ref)); + + + napi_value objWatcher = NClass::InstantiateClass(env, WatcherNExporter::className_, {}); + if (!objWatcher) { + NError(EINVAL).ThrowErr(env, "objWatcher create failed"); + return nullptr; + } + + auto watcherEntity = NClass::GetEntityOf(env, objWatcher); + if (!watcherEntity) { + NError(EINVAL).ThrowErr(env, "watcherEntity get failed"); + return nullptr; + } + watcherEntity->data_ = data; + + return objWatcher; +} +} // namespace OHOS::FileManagement::ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fs/properties/watcher.h b/interfaces/kits/js/src/mod_fs/properties/watcher.h new file mode 100644 index 000000000..22059672c --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/watcher.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2021 Huawei Device 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_WATCHER_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_WATCHER_H +#include "filemgmt_libn.h" +namespace OHOS::FileManagement::ModuleFileIO { + +class Watcher final { +public: + static napi_value CreateWatcher(napi_env env, napi_callback_info info); +}; +} // namespace OHOS::FileManagement::ModuleFileIO +#endif \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_val.h b/utils/filemgmt_libn/include/n_val.h index c66b88a56..5f40f8fdd 100644 --- a/utils/filemgmt_libn/include/n_val.h +++ b/utils/filemgmt_libn/include/n_val.h @@ -52,7 +52,9 @@ public: std::tuple ToArraybuffer() const; std::tuple ToTypedArray() const; std::tuple, uint32_t> ToStringArray(); + std::tuple, uint32_t> ToUint32Array(); std::tuple ToUint64() const; + std::tuple ToUint32() const; std::tuple ToDouble() const; /* Static helpers to create js objects */ @@ -60,6 +62,7 @@ public: static NVal CreateBigInt64(napi_env env, int64_t val); static NVal CreateInt64(napi_env env, int64_t val); static NVal CreateInt32(napi_env env, int32_t val); + static NVal CreateUint32(napi_env env, int32_t val); static NVal CreateObject(napi_env env); static NVal CreateBool(napi_env env, bool val); static NVal CreateUTF8String(napi_env env, std::string str); diff --git a/utils/filemgmt_libn/src/n_val.cpp b/utils/filemgmt_libn/src/n_val.cpp index a2d6a5912..8eb6bd48e 100644 --- a/utils/filemgmt_libn/src/n_val.cpp +++ b/utils/filemgmt_libn/src/n_val.cpp @@ -131,6 +131,14 @@ tuple NVal::ToDouble() const return make_tuple(status == napi_ok, res); } +tuple NVal::ToUint32() const +{ + uint32_t res = 0; + napi_status status = napi_get_value_uint32(env_, val_, &res); + return make_tuple(status == napi_ok, res); +} + + tuple NVal::ToUint64() const { uint64_t res = 0; @@ -154,6 +162,21 @@ tuple, uint32_t> NVal::ToStringArray() return make_tuple(status == napi_ok, stringArray, size); } +tuple, uint32_t> NVal::ToUint32Array() +{ + napi_status status; + uint32_t size; + status = napi_get_array_length(env_, val_, &size); + vector uint32Array; + napi_value result; + for (uint32_t i = 0; i < size; i++) { + status = napi_get_element(env_, val_, i, &result); + auto [succ, uint32] = NVal(env_, result).ToUint32(); + uint32Array.push_back(uint32); + } + return make_tuple(status == napi_ok, uint32Array, size); +} + tuple NVal::ToArraybuffer() const { void *buf = nullptr; @@ -258,6 +281,13 @@ NVal NVal::CreateInt32(napi_env env, int32_t val) return {env, res}; } +NVal NVal::CreateUint32(napi_env env, int32_t val) +{ + napi_value res = nullptr; + napi_create_uint32(env, val, &res); + return {env, res}; +} + NVal NVal::CreateObject(napi_env env) { napi_value res = nullptr; -- Gitee From 5e5215de9d077a509d3de111764421a665a61845 Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Fri, 3 Feb 2023 14:46:10 +0800 Subject: [PATCH 24/25] move to mode_fs Signed-off-by: Cao Chuan --- interfaces/kits/js/BUILD.gn | 3 - .../mod_fileio/class_watcher/file_watcher.cpp | 122 ------------ .../mod_fileio/class_watcher/file_watcher.h | 47 ----- .../mod_fileio/class_watcher/watcher_entity.h | 42 ---- .../class_watcher/watcher_n_exporter.cpp | 180 ------------------ .../class_watcher/watcher_n_exporter.h | 60 ------ interfaces/kits/js/src/mod_fileio/module.cpp | 2 - .../mod_fileio/properties/prop_n_exporter.cpp | 2 +- 8 files changed, 1 insertion(+), 457 deletions(-) delete mode 100644 interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp delete mode 100644 interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.h delete mode 100644 interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h delete mode 100644 interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp delete mode 100644 interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index b34a66507..b95321ad7 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -52,8 +52,6 @@ ohos_shared_library("fileio") { "src/mod_fileio/class_stat/stat_n_exporter.cpp", "src/mod_fileio/class_stream/flush.cpp", "src/mod_fileio/class_stream/stream_n_exporter.cpp", - "src/mod_fileio/class_watcher/file_watcher.cpp", - "src/mod_fileio/class_watcher/watcher_n_exporter.cpp", "src/mod_fileio/common_func.cpp", "src/mod_fileio/module.cpp", "src/mod_fileio/properties/chmod.cpp", @@ -87,7 +85,6 @@ ohos_shared_library("fileio") { "src/mod_fileio/properties/stat.cpp", "src/mod_fileio/properties/symlink.cpp", "src/mod_fileio/properties/truncate.cpp", - "src/mod_fileio/properties/watcher.cpp", ] deps = [ diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp deleted file mode 100644 index a9c32a1dc..000000000 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device 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. - */ -#include "file_watcher.h" -#include "../../common/log.h" -#include -#include -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -const int BUF_SIZE = 1024; -FileWatcher::FileWatcher() {} - -FileWatcher::~FileWatcher() {} - -bool FileWatcher::InitNotify(int &fd, int &errCode) -{ - HILOGI("FileWatcher InitNotify IN"); - fd = inotify_init(); - if (fd == -1) { - errCode = errno; - HILOGE("FileWatcher InitNotify fail errCode:%{public}d", errCode); - return false; - } - HILOGI("FileWatcher InitNotify OUT"); - return true; -} - -bool FileWatcher::StartNotify(std::shared_ptr &arg, int &errCode) -{ - HILOGI("FileWatcher StartNotify IN"); - int wd = 0; - uint32_t watchEvent = 0; - for (auto event : arg->events) { - watchEvent = watchEvent | event; - } - wd = inotify_add_watch(arg->fd, arg->filename.c_str(), watchEvent); - if(wd == -1) { - errCode = errno; - HILOGE("FileWatcher StartNotify fail errCode:%{public}d", errCode); - return false; - } - arg->wd = wd; - run_ = true; - HILOGI("FileWatcher StartNotify OUT"); - return true; -} - -bool FileWatcher::StopNotify(std::shared_ptr &arg, int &errCode) -{ - HILOGI("FileWatcher StopObserver IN"); - run_ = false; - if (inotify_rm_watch(arg->fd, arg->wd) == -1) { - errCode = errno; - HILOGE("FileWatcher StopNotify fail errCode:%{public}d", errCode); - return false; - } - close(arg->fd); - HILOGI("FileWatcher StopObserver OUT"); - return true; -} - -void FileWatcher::HandleEvent(std::shared_ptr &arg, - const struct inotify_event *event, - WatcherCallback callback) -{ - HILOGI("FileWatcher HandleEvent IN"); - if (event->wd == arg->wd) { - HILOGI("FileWatcher HandleEvent event->wd == arg->wd"); - for (auto watchEvent : arg->events) { - if (event->mask == watchEvent || watchEvent == IN_ALL_EVENTS) { - std::string filename = arg->filename + "/" + event->name; - HILOGI("FileWatcher HandleEvent fileName:%{public}s, mask:%{public}d", filename.c_str(), event->mask); - callback(arg->env, arg->ref, filename, event->mask); - } - } - } - HILOGI("FileWatcher HandleEvent OUT"); -} - -void FileWatcher::GetNotifyEvent(std::shared_ptr &arg, WatcherCallback callback) -{ - HILOGI("FileWatcher GetNotifyEvent IN"); - char buf[BUF_SIZE] = {0}; - struct inotify_event *event = nullptr; - while (run_) { - int fd = arg->fd; - fd_set fds; - FD_ZERO(&fds); - FD_SET(fd, &fds); - HILOGI("FileWatcher GetNotifyEvent fd:%{public}d", fd); - if (select(fd + 1, &fds, NULL, NULL, NULL) > 0) { - HILOGI("FileWatcher GetNotifyEvent fd+1:%{public}d", fd + 1); - int len, index = 0; - if(errno == EINTR) { - HILOGI("FileWatcher GetNotifyEvent errno == EINT"); - } - while (((len = read(fd, &buf, sizeof(buf))) < 0) && (errno == EINTR)); - while (index < len) { - HILOGI("FileWatcher GetNotifyEvent index < len"); - event = (struct inotify_event *)(buf + index); - HandleEvent(arg, event, callback); - index += sizeof(struct inotify_event) + event->len; - } - } - } - HILOGI("FileWatcher GetNotifyEvent OUT"); -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.h b/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.h deleted file mode 100644 index c7d798c54..000000000 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/file_watcher.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device 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. - */ - -#ifndef FILE_WATCHER_H -#define FILE_WATCHER_H -#include -#include -#include -#include "watcher_entity.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using WatcherCallback = void (*)(napi_env env, napi_ref callback, const std::string &filename, const uint32_t &event); -struct ErrorInfo { - int errCode; - std::string errMsg; -}; - -class FileWatcher { -public: - FileWatcher(); - ~FileWatcher(); - bool InitNotify(int &fd, int &errCode); - bool StartNotify(std::shared_ptr &arg, int &errCode); - bool StopNotify(std::shared_ptr &arg, int &errCode); - void GetNotifyEvent(std::shared_ptr &arg, WatcherCallback callback); - -private: - void HandleEvent(std::shared_ptr &arg, const struct inotify_event *event, WatcherCallback callback); - bool run_; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h deleted file mode 100644 index acb57c72c..000000000 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device 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. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_ENTITY_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_ENTITY_H - -#include -#include "../../common/napi/uni_header.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -#include -#include -#include -struct WatcherInfoArg { - std::string filename; - std::vector events; - int fd; - int wd; - napi_env env = nullptr; - napi_ref ref = nullptr; -}; - -struct WatcherEntity { - std::shared_ptr data_; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp deleted file mode 100644 index 2b32f8fb8..000000000 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device 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. - */ - -#include "watcher_n_exporter.h" - -#include -#include -#include -#include - -#include "../../common/log.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/uni_error.h" -#include "securec.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; -std::shared_ptr WatcherNExporter::watcherPtr_; -napi_value WatcherNExporter::Constructor(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - unique_ptr watcherEntity = make_unique(); - if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(watcherEntity))) { - UniError(EIO).ThrowErr(env, "INNER BUG. Failed to wrap entity for obj stat"); - return nullptr; - } - - watcherPtr_ = make_shared(); - return funcArg.GetThisVar(); -} - -napi_value WatcherNExporter::Stop(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto watchEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!watchEntity) { - UniError(EINVAL).ThrowErr(env, "get watcherEntity fail"); - return nullptr; - } - int errCode = 0; - if (!watcherPtr_->StopNotify(watchEntity->data_, errCode)) { - UniError(errCode).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value WatcherNExporter::Start(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto watchEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!watchEntity) { - UniError(EINVAL).ThrowErr(env, "get watcherEntity fail"); - return nullptr; - } - int errCode = 0; - if(!watcherPtr_->StartNotify(watchEntity->data_, errCode)) { - UniError(errCode).ThrowErr(env); - return nullptr; - } - - auto cbExec = [watchEntity](napi_env env) -> UniError { - watcherPtr_->GetNotifyEvent(watchEntity->data_, WatcherCallback); - return UniError(ERRNO_NOERR); - }; - - auto cbCompl = [](napi_env env, UniError err) -> NVal { - if (err) { - return {env, err.GetNapiErr(env)}; - } - return {NVal::CreateUndefined(env)}; - }; - - const string procedureName = "FileIOStartWatcher"; - NVal thisVar(env, funcArg.GetThisVar()); - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; -} - -void WatcherNExporter::WatcherCallback(napi_env env, - napi_ref callback, - const std::string &fileName, - const uint32_t &event) -{ - auto callbackContext = make_unique(); - callbackContext->env_ = env; - callbackContext->ref_ = callback; - callbackContext->fileName_ = fileName; - callbackContext->event_ = event; - napi_value resource = nullptr; - napi_create_string_utf8(env, "FileIOCreateWatcher", NAPI_AUTO_LENGTH, &resource); - - napi_create_async_work( - env, nullptr, resource, [](napi_env env, void *data) {}, - [](napi_env env, napi_status status, void *data) { - // JSCallbackData* jsCallbackData = (JSCallbackData*)data; - auto context = static_cast(data); - napi_value jsCallback = nullptr; - napi_get_reference_value(env, context->ref_, &jsCallback); - NVal objn = NVal::CreateObject(env); - objn.AddProp("fileName", NVal::CreateUTF8String(env, context->fileName_).val_); - objn.AddProp("event", NVal::CreateUint32(env, context->event_).val_); - napi_value global = nullptr; - napi_get_global(env, &global); - napi_value jsObj = nullptr; - napi_call_function(env, global, jsCallback, 1, &(objn.val_), &jsObj); - napi_delete_async_work(env, context->work_); - }, - static_cast(callbackContext.get()), &callbackContext->work_); - napi_queue_async_work(env, callbackContext->work_); - callbackContext.release(); -} - -bool WatcherNExporter::Export() -{ - vector props = { - NVal::DeclareNapiFunction("start", Start), - NVal::DeclareNapiFunction("stop", Stop), - }; - - string className = GetClassName(); - auto [resDefineClass, classValue] = - NClass::DefineClass(exports_.env_, className, WatcherNExporter::Constructor, std::move(props)); - if (!resDefineClass) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to define class"); - return false; - } - - bool succ = NClass::SaveClass(exports_.env_, className, classValue); - if (!succ) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to save class"); - return false; - } - - return exports_.AddProp(className, classValue); -} - -string WatcherNExporter::GetClassName() -{ - return WatcherNExporter::className_; -} - -WatcherNExporter::WatcherNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} - -WatcherNExporter::~WatcherNExporter() {} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h deleted file mode 100644 index 7bbc67739..000000000 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device 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. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_N_EXPORTER_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_N_EXPORTER_H -#include -#include -#include "../../common/napi/n_exporter.h" -#include "watcher_entity.h" -#include "file_watcher.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class WatcherNExporter final : public NExporter { -public: - class JSCallbackContext { - public: - JSCallbackContext() {} - ~JSCallbackContext() {} - - public: - napi_env env_; - napi_ref ref_; - std::string fileName_; - uint32_t event_; - napi_async_work work_; - }; - - inline static const std::string className_ = "Watcher"; - - bool Export() override; - std::string GetClassName() override; - - static napi_value Constructor(napi_env env, napi_callback_info info); - static napi_value Start(napi_env env, napi_callback_info info); - static napi_value Stop(napi_env env, napi_callback_info info); - static void WatcherCallback(napi_env env, napi_ref callback, const std::string &fileName, const uint32_t &event); - - WatcherNExporter(napi_env env, napi_value exports); - ~WatcherNExporter() override; - -private: - static std::shared_ptr watcherPtr_; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/module.cpp b/interfaces/kits/js/src/mod_fileio/module.cpp index b26592acb..f45251a66 100644 --- a/interfaces/kits/js/src/mod_fileio/module.cpp +++ b/interfaces/kits/js/src/mod_fileio/module.cpp @@ -23,7 +23,6 @@ #include "class_randomaccessfile/randomaccessfile_n_exporter.h" #include "class_stat/stat_n_exporter.h" #include "class_stream/stream_n_exporter.h" -#include "class_watcher/watcher_n_exporter.h" #include "properties/prop_n_exporter.h" using namespace std; @@ -40,7 +39,6 @@ static napi_value Export(napi_env env, napi_value exports) products.emplace_back(make_unique(env, exports)); products.emplace_back(make_unique(env, exports)); products.emplace_back(make_unique(env, exports)); - products.emplace_back(make_unique(env, exports)); products.emplace_back(make_unique(env, exports)); for (auto &&product : products) { diff --git a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp index a7a1acbac..166279aba 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp @@ -687,7 +687,7 @@ bool PropNExporter::Export() NVal::DeclareNapiFunction("createRandomAccessFileSync", CreateRandomAccessFile::Sync), NVal::DeclareNapiFunction("createStream", CreateStream::Async), NVal::DeclareNapiFunction("createStreamSync", CreateStream::Sync), - NVal::DeclareNapiFunction("createWatcher", Watcher::CreateWatcher), + // NVal::DeclareNapiFunction("createWatcher", Watcher::CreateWatcher), NVal::DeclareNapiFunction("fchmod", Fchmod::Async), NVal::DeclareNapiFunction("fchmodSync", Fchmod::Sync), NVal::DeclareNapiFunction("fchown", Fchown::Async), -- Gitee From fcb53985279b3810a0f968c5fb02daeebeeac73c Mon Sep 17 00:00:00 2001 From: Cao Chuan Date: Fri, 3 Feb 2023 15:39:06 +0800 Subject: [PATCH 25/25] modify build Signed-off-by: Cao Chuan --- .../mod_fileio/properties/prop_n_exporter.cpp | 5 +- .../js/src/mod_fileio/properties/watcher.cpp | 92 ------------------- .../js/src/mod_fileio/properties/watcher.h | 32 ------- .../src/mod_fs/properties/prop_n_exporter.cpp | 3 +- 4 files changed, 4 insertions(+), 128 deletions(-) delete mode 100644 interfaces/kits/js/src/mod_fileio/properties/watcher.cpp delete mode 100644 interfaces/kits/js/src/mod_fileio/properties/watcher.h diff --git a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp index 166279aba..6f7518610 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp @@ -20,7 +20,8 @@ #include #include #include - +#include +#include #include "../common_func.h" #include "chmod.h" #include "chown.h" @@ -52,7 +53,6 @@ #include "stat.h" #include "symlink.h" #include "truncate.h" -#include "watcher.h" namespace OHOS { namespace DistributedFS { @@ -687,7 +687,6 @@ bool PropNExporter::Export() NVal::DeclareNapiFunction("createRandomAccessFileSync", CreateRandomAccessFile::Sync), NVal::DeclareNapiFunction("createStream", CreateStream::Async), NVal::DeclareNapiFunction("createStreamSync", CreateStream::Sync), - // NVal::DeclareNapiFunction("createWatcher", Watcher::CreateWatcher), NVal::DeclareNapiFunction("fchmod", Fchmod::Async), NVal::DeclareNapiFunction("fchmodSync", Fchmod::Sync), NVal::DeclareNapiFunction("fchown", Fchown::Async), diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp deleted file mode 100644 index e4a671e41..000000000 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device 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. - */ - -#include "watcher.h" - -#include "../../common/napi/n_async/n_ref.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" -#include -#include -#include -#include -#include - -#include "../class_watcher/file_watcher.h" -#include "../class_watcher/watcher_entity.h" -#include "../class_watcher/watcher_n_exporter.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto [succGetPath, filename, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succGetPath) { - UniError(EINVAL).ThrowErr(env, "Invalid filename"); - return nullptr; - } - - auto [succGetEvent, events, size] = NVal(env, funcArg[NARG_POS::SECOND]).ToUint32Array(); - if (!succGetEvent) { - UniError(EINVAL).ThrowErr(env, "Invalid event"); - return nullptr; - } - - int fd = 0; - int errCode; - shared_ptr watcherPtr = make_shared(); - if (!watcherPtr->InitNotify(fd, errCode)) { - UniError(errCode).ThrowErr(env); - return nullptr; - } - - shared_ptr data = make_shared(); - data->events = events; - data->env = env; - data->filename = string(filename.get()); - data->fd = fd; - - NVal val = NVal(env, funcArg[NARG_POS::THIRD]); - napi_create_reference(val.env_, val.val_, 1, &(data->ref)); - - - napi_value objWatcher = NClass::InstantiateClass(env, WatcherNExporter::className_, {}); - if (!objWatcher) { - UniError(EINVAL).ThrowErr(env, "objWatcher create failed"); - return nullptr; - } - - auto watcherEntity = NClass::GetEntityOf(env, objWatcher); - if (!watcherEntity) { - UniError(EINVAL).ThrowErr(env, "watcherEntity get failed"); - return nullptr; - } - watcherEntity->data_ = data; - - return objWatcher; -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.h b/interfaces/kits/js/src/mod_fileio/properties/watcher.h deleted file mode 100644 index 9493dd696..000000000 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device 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. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_WATCHER_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_WATCHER_H - -#include -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Watcher final { -public: - static napi_value CreateWatcher(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp b/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp index 62baa5206..1a47906cd 100644 --- a/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/prop_n_exporter.cpp @@ -32,7 +32,7 @@ #include "stat.h" #include "symlink.h" #include "truncate.h" - +#include "watcher.h" namespace OHOS { namespace FileManagement { namespace ModuleFileIO { @@ -284,6 +284,7 @@ bool PropNExporter::Export() NVal::DeclareNapiFunction("truncateSync", Truncate::Sync), NVal::DeclareNapiFunction("write", Write), NVal::DeclareNapiFunction("writeSync", WriteSync), + NVal::DeclareNapiFunction("createWatcher", Watcher::CreateWatcher), }); } -- Gitee