1 /*
2  * Copyright (c) 2023 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 #ifndef INTERFACE_OBSERVER_H
17 #define INTERFACE_OBSERVER_H
18 
19 #include <cstdint>
20 #include <memory>
21 #include <string>
22 #include <utility>
23 
24 #include <napi/native_api.h>
25 #include <napi/native_node_api.h>
26 #include <uv.h>
27 
28 #include "event_manager.h"
29 #include "interface_state_callback_stub.h"
30 #include "napi_utils.h"
31 
32 namespace OHOS {
33 namespace NetManagerStandard {
34 class InterfaceStateObserver : public InterfaceStateCallbackStub {
35 public:
36     int32_t OnInterfaceAdded(const std::string &iface) override;
37     int32_t OnInterfaceRemoved(const std::string &iface) override;
38     int32_t OnInterfaceChanged(const std::string &iface, bool up) override;
39 
40 private:
CallbackTemplate(uv_work_t * work,int status)41     template <napi_value (*MakeJsValue)(napi_env, void *)> static void CallbackTemplate(uv_work_t *work, int status)
42     {
43         (void)status;
44         if (work == nullptr) {
45             return;
46         }
47         auto workWrapper = static_cast<UvWorkWrapper *>(work->data);
48         if (workWrapper == nullptr) {
49             delete work;
50             return;
51         }
52         napi_env env = workWrapper->env;
53         auto closeScope = [env](napi_handle_scope scope) { NapiUtils::CloseScope(env, scope); };
54         std::unique_ptr<napi_handle_scope__, decltype(closeScope)> scope(NapiUtils::OpenScope(env), closeScope);
55         napi_value obj = MakeJsValue(env, workWrapper->data);
56         std::pair<napi_value, napi_value> arg = {NapiUtils::GetUndefined(workWrapper->env), obj};
57         workWrapper->manager->Emit(workWrapper->type, arg);
58         delete workWrapper;
59         delete work;
60     }
61 
62     static napi_value CreateIfaceChangedParam(napi_env env, void *data);
63     static void IfaceChangedCallback(uv_work_t *work, int status);
64 };
65 } // namespace NetManagerStandard
66 } // namespace OHOS
67 #endif // NETMANAGER_BASE_NET_STATS_CALLBACK_OBSERVER_H
68