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 #include "net_stats_listener.h"
17
18 #include "bundle_constants.h"
19
20 #include "net_manager_constants.h"
21 #include "net_mgr_log_wrapper.h"
22 #include "net_stats_data_handler.h"
23 #include "netmanager_base_common_utils.h"
24
25 namespace OHOS {
26 namespace NetManagerStandard {
27 namespace {
28 using namespace OHOS::EventFwk;
__anon6ca2f4f30202(const Want &want) 29 NetStatsListener::StatsCallback onUidRemove = [](const Want &want) {
30 uint32_t uid = want.GetIntParam(AppExecFwk::Constants::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 }
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