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