1 /*
2  * Copyright (C) 2022-2024 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 "net_stats_listener.h"
17 
18 #include "net_manager_constants.h"
19 #include "net_mgr_log_wrapper.h"
20 #include "net_stats_cached.h"
21 #include "net_stats_data_handler.h"
22 #include "netmanager_base_common_utils.h"
23 
24 namespace OHOS {
25 namespace NetManagerStandard {
26 namespace {
27 using namespace OHOS::EventFwk;
28 constexpr const char* UID = "uid";
__anonc0ad164c0202(const Want &want) 29 NetStatsListener::StatsCallback onUidRemove = [](const Want &want) {
30     uint32_t uid = want.GetIntParam(UID, 0);
31     auto handler = std::make_unique<NetStatsDataHandler>();
32     NETMGR_LOG_D("Net Manager delete uid, uid:[%{public}d]", uid);
33     return handler->DeleteByUid(uid);
34 };
35 } // namespace
36 
NetStatsListener(const EventFwk::CommonEventSubscribeInfo & sp)37 NetStatsListener::NetStatsListener(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
38 {
39     callbackMap_[CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED] = onUidRemove;
40 }
41 
RegisterStatsCallback(const std::string & event,StatsCallback callback)42 void NetStatsListener::RegisterStatsCallback(const std::string &event, StatsCallback callback)
43 {
44     if (callbackMap_.find(event) != callbackMap_.end()) {
45         NETMGR_LOG_W("Key %{public}s has been assigned and will be replaced", event.c_str());
46     }
47     callbackMap_[event] = callback;
48     NETMGR_LOG_I("NetStatsListener RegisterStatsCallback is successful");
49 }
50 
OnReceiveEvent(const CommonEventData & data)51 void NetStatsListener::OnReceiveEvent(const CommonEventData &data)
52 {
53     NETMGR_LOG_I("NetStatsListener::OnReceiveEvent(), event:[%{public}s], data:[%{public}s], code:[%{public}d]",
54                  data.GetWant().GetAction().c_str(), data.GetData().c_str(), data.GetCode());
55 
56     auto want = data.GetWant();
57     auto callback = callbackMap_.find(want.GetAction());
58     if (callback == callbackMap_.end()) {
59         return;
60     }
61     if (callback->second == nullptr) {
62         callbackMap_.erase(want.GetAction());
63         return;
64     }
65     auto ret = callback->second(want);
66     if (ret != 0) {
67         NETMGR_LOG_E("Callback run failed");
68     }
69 }
70 } // namespace NetManagerStandard
71 } // namespace OHOS
72