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 "notifier_impl.h"
17
18 #include "anonymous.h"
19 #include "logger.h"
20 #include "objectstore_errors.h"
21
22 namespace OHOS::ObjectStore {
GetInstance()23 std::shared_ptr<NotifierImpl> NotifierImpl::GetInstance()
24 {
25 static std::shared_ptr<NotifierImpl> instance;
26 static std::mutex instanceLock;
27 if (instance == nullptr) {
28 std::lock_guard<std::mutex> lockGuard(instanceLock);
29 if (instance == nullptr) {
30 instance = std::make_shared<NotifierImpl>();
31 uint32_t ret = DistributedObjectStore::GetInstance()->SetStatusNotifier(instance);
32 if (ret != SUCCESS) {
33 LOG_ERROR("SetStatusNotifier %{public}d error", ret);
34 } else {
35 LOG_INFO("SetStatusNotifier success");
36 }
37 }
38 }
39 return instance;
40 }
41
AddWatcher(std::string & sessionId,std::weak_ptr<JSWatcher> watcher)42 void NotifierImpl::AddWatcher(std::string &sessionId, std::weak_ptr<JSWatcher> watcher)
43 {
44 std::lock_guard<std::mutex> lock(mutex_);
45 watchers_.insert_or_assign(sessionId, watcher);
46 }
47
DelWatcher(std::string & sessionId)48 void NotifierImpl::DelWatcher(std::string &sessionId)
49 {
50 std::lock_guard<std::mutex> lock(mutex_);
51 watchers_.erase(sessionId);
52 }
53
OnChanged(const std::string & sessionId,const std::string & networkId,const std::string & onlineStatus)54 void NotifierImpl::OnChanged(
55 const std::string &sessionId, const std::string &networkId, const std::string &onlineStatus)
56 {
57 LOG_INFO("status changed %{public}s %{public}s %{public}s", sessionId.c_str(), Anonymous::Change(networkId).c_str(),
58 onlineStatus.c_str());
59 std::lock_guard<std::mutex> lock(mutex_);
60 if (watchers_.count(sessionId) != 0) {
61 LOG_INFO("start emit %{public}s %{public}s %{public}s", sessionId.c_str(), Anonymous::Change(networkId).c_str(),
62 onlineStatus.c_str());
63 std::shared_ptr<JSWatcher> lockedWatcher = watchers_.at(sessionId).lock();
64 if (lockedWatcher) {
65 lockedWatcher->Emit("status", sessionId, networkId, onlineStatus);
66 LOG_INFO("end emit %{public}s %{public}s %{public}s", sessionId.c_str(),
67 Anonymous::Change(networkId).c_str(), onlineStatus.c_str());
68 } else {
69 LOG_ERROR("watcher expired");
70 }
71 }
72 }
~NotifierImpl()73 NotifierImpl::~NotifierImpl()
74 {
75 }
76 } // namespace OHOS::ObjectStore
77