1 /*
2 * Copyright (c) 2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "watcher_ani.h"
17
18 #include "ani_helper.h"
19 #include "error_handler.h"
20 #include "file_utils.h"
21 #include "filemgmt_libhilog.h"
22 #include "fs_watcher_wrapper.h"
23 #include "type_converter.h"
24 #include "watch_event_listener.h"
25 #include "watcher_core.h"
26
27 namespace OHOS {
28 namespace FileManagement {
29 namespace ModuleFileIO {
30 namespace ANI {
31 using namespace OHOS::FileManagement::ModuleFileIO;
32
CreateWatcherSync(ani_env * env,ani_class clazz,ani_string path,ani_double events,ani_ref listener)33 ani_object WatcherAni::CreateWatcherSync(
34 ani_env *env, [[maybe_unused]] ani_class clazz, ani_string path, ani_double events, ani_ref listener)
35 {
36 auto [succPath, filePath] = TypeConverter::ToUTF8String(env, path);
37 if (!succPath) {
38 HILOGE("Invalid path");
39 ErrorHandler::Throw(env, EINVAL);
40 return nullptr;
41 }
42
43 ani_ref cbRef;
44 if (ANI_OK != env->GlobalReference_Create(move(listener), &cbRef)) {
45 HILOGE("Failed to get callback");
46 ErrorHandler::Throw(env, EINVAL);
47 return nullptr;
48 }
49 ani_vm *vm = nullptr;
50 env->GetVM(&vm);
51 auto eventListener = CreateSharedPtr<WatchEventListener>(vm, cbRef);
52 if (eventListener == nullptr) {
53 HILOGE("Failed to request heap memory.");
54 ErrorHandler::Throw(env, ENOMEM);
55 return nullptr;
56 }
57
58 FsResult<FsWatcher *> ret =
59 WatcherCore::DoCreateWatcher(filePath, static_cast<int32_t>(events), move(eventListener));
60 if (!ret.IsSuccess()) {
61 HILOGE("Create watcher failed");
62 const auto &err = ret.GetError();
63 ErrorHandler::Throw(env, err);
64 return nullptr;
65 }
66 const FsWatcher *watcher = ret.GetData().value();
67 auto result = FsWatcherWrapper::Wrap(env, move(watcher));
68 if (result == nullptr) {
69 HILOGE("Failed to Wrap");
70 delete watcher;
71 watcher = nullptr;
72 ErrorHandler::Throw(env, UNKNOWN_ERR);
73 return nullptr;
74 }
75 return result;
76 }
77 } // namespace ANI
78 } // namespace ModuleFileIO
79 } // namespace FileManagement
80 } // namespace OHOS