1 /*
2  * Copyright (c) 2022 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 NETMANAGER_BASE_NETWORK_OBSERVER_H
17 #define NETMANAGER_BASE_NETWORK_OBSERVER_H
18 
19 #include "net_all_capabilities.h"
20 #include "net_conn_callback_stub.h"
21 #include "event_manager.h"
22 #include "napi_utils.h"
23 
24 namespace OHOS::NetManagerStandard {
25 struct NetworkType {
26     std::set<NetBearType> bearerTypes;
27 };
28 
29 class NetworkObserver : public NetConnCallbackStub {
30 public:
31     int32_t NetAvailable(sptr<NetHandle> &netHandle) override;
32 
33     int32_t NetCapabilitiesChange(sptr<NetHandle> &netHandle, const sptr<NetAllCapabilities> &netAllCap) override;
34 
35     int32_t NetConnectionPropertiesChange(sptr<NetHandle> &netHandle, const sptr<NetLinkInfo> &info) override;
36 
37     int32_t NetLost(sptr<NetHandle> &netHandle) override;
38 
39     int32_t NetUnavailable() override;
40 
41     int32_t NetBlockStatusChange(sptr<NetHandle> &netHandle, bool blocked) override;
42 
43     void SetManager(EventManager *manager);
44 
45 private:
46     template <napi_value (*MakeJsValue)(napi_env, NetworkType *)>
CallbackTemplate(uv_work_t * work,int status)47     static void CallbackTemplate(uv_work_t *work, int status)
48     {
49         (void)status;
50 
51         auto workWrapper = static_cast<UvWorkWrapper *>(work->data);
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 
56         napi_value obj = MakeJsValue(env, static_cast<NetworkType *>(workWrapper->data));
57 
58         std::pair<napi_value, napi_value> arg = {NapiUtils::GetUndefined(workWrapper->env), obj};
59         workWrapper->manager->Emit(workWrapper->type, arg);
60 
61         delete workWrapper;
62         delete work;
63     }
64 
65     EventManager *manager_;
66 };
67 
68 extern std::map<EventManager *, sptr<NetworkObserver>> g_observerMap;
69 } // namespace OHOS::NetManagerStandard
70 #endif /* NETMANAGER_BASE_NETWORK_OBSERVER_H */
71