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 "command_send_limit.h"
17 #include "avsession_errors.h"
18 #include "avsession_log.h"
19
20 namespace OHOS::AVSession {
21 std::shared_ptr<CommandSendLimit> CommandSendLimit::instance_;
22 std::once_flag CommandSendLimit::onceFlag_;
23
GetInstance()24 CommandSendLimit& CommandSendLimit::GetInstance()
25 {
26 std::call_once(onceFlag_, [] {
27 instance_ = std::make_shared<CommandSendLimit>();
28 });
29 return *instance_;
30 }
31
CommandSendLimit()32 CommandSendLimit::CommandSendLimit()
33 {
34 SLOGD("CommandSendLimit construct");
35 }
36
~CommandSendLimit()37 CommandSendLimit::~CommandSendLimit()
38 {
39 SLOGD("CommandSendLimit destroy");
40 }
41
IsCommandSendEnable(pid_t pid)42 bool CommandSendLimit::IsCommandSendEnable(pid_t pid)
43 {
44 std::lock_guard lockGuard(commandLimitLock_);
45 if (timer_ == nullptr) {
46 return true;
47 }
48 if (commandLimits_.find(pid) != commandLimits_.end()) {
49 if (commandLimits_[pid] >= COMMAND_SEND_NUM_MAX) {
50 SLOGD("commandSendTime=%{public}d", commandLimits_[pid]);
51 return false;
52 }
53 SLOGD("commandSendTime=%{public}d", commandLimits_[pid]);
54 commandLimits_[pid] += 1;
55 } else {
56 SLOGD("commandSendTime=0");
57 commandLimits_.insert(std::make_pair(pid, 1));
58 }
59 return true;
60 }
61
ClearCommandLimits()62 void CommandSendLimit::ClearCommandLimits()
63 {
64 std::lock_guard lockGuard(commandLimitLock_);
65 commandLimits_.clear();
66 }
StartTimer()67 void CommandSendLimit::StartTimer()
68 {
69 SLOGD("CommandSendLimit StartTimer");
70 std::lock_guard lockGuard(commandLimitLock_);
71 if (!timer_) {
72 timer_ = std::make_unique<OHOS::Utils::Timer>("CommandLimitTimer");
73 CHECK_AND_RETURN_LOG(timer_ != nullptr, "create Timer failed");
74 Utils::Timer::TimerCallback timerCallback = [this]() {
75 ClearCommandLimits();
76 };
77 timerId_ = timer_->Register(timerCallback, COMMAND_SEND_TIME, false);
78 timer_->Setup();
79 }
80 }
81
StopTimer()82 void CommandSendLimit::StopTimer()
83 {
84 SLOGD("CommandSendLimit StopTimer");
85 std::lock_guard lockGuard(commandLimitLock_);
86 if (timer_) {
87 timer_->Shutdown();
88 timer_->Unregister(timerId_);
89 timer_ = nullptr;
90 }
91 commandLimits_.clear();
92 }
93 } // namespace OHOS::AVSession