• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
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 #include "usb_connection_notifier.h"
16 
17 #include <parameters.h>
18 #include <param_wrapper.h>
19 #include "hilog_wrapper.h"
20 #include "want_agent_info.h"
21 #include "want_agent_helper.h"
22 #include "notification_normal_content.h"
23 #include "resource_manager.h"
24 #include "locale_config.h"
25 #include "locale_info.h"
26 #include "string_wrapper.h"
27 #include "iservice_registry.h"
28 #include "system_ability_definition.h"
29 #include "image_source.h"
30 #include "usb_errors.h"
31 #include "bundle_mgr_interface.h"
32 #include "os_account_manager.h"
33 #include "usb_trace.h"
34 
35 #define DEFAULT_PARAM_VALUE "charge,mtp,ptp"
36 using namespace OHOS::AAFwk;
37 using namespace OHOS::AppExecFwk;
38 
39 static const std::string NOTIFICATION_NAME = "usb_service";
40 static const std::string NOTIFICATION_NAME_ONE = "usb_service1";
41 static int32_t g_uid = 1018;
42 constexpr int32_t USER_ID = 100;
43 static const std::string BUNDLE_NAME = "com.usb.right";
44 static const std::string SET_BUNDLE_NAME = "com.usb.right";
45 static const std::string SETTING_BUNDLE_NAME = "com.ohos.settings";
46 static const std::string SETTING_BUNDLE_NAME_ABILITY = "com.ohos.settings.MainAbility";
47 static const std::string SETTING_BUNDLE_NAME_URL = "developer_options_settings";
48 static const std::string BUNDLE_NAME_KEY = "EntryAbility";
49 static const std::string URI = "";
50 static const std::string HAP_PATH = "system/app/com.usb.right/usb_right_dialog.hap";
51 static const std::string ICON_NAME = "icon";
52 constexpr std::int32_t BUNDLE_MGR_SERVICE_SA_ID = 401;
53 constexpr std::int32_t NOTIFICATION_ID_ZERO = 0;
54 constexpr std::int32_t NOTIFICATION_ID_ONE = 1;
55 constexpr std::uint32_t NOTIFICATION_STATUS_CLOSE_SOUND = 1 << 0;
56 constexpr std::uint32_t NOTIFICATION_STATUS_CLOSE_LOCKSCREEN = 1 << 1;
57 constexpr std::uint32_t NOTIFICATION_STATUS_CLOSE_BANNER = 1 << 2;
58 constexpr std::uint32_t NOTIFICATION_STATUS_CLOSE_LIGHT_SCREEN = 1 << 3;
59 constexpr std::uint32_t NOTIFICATION_STATUS_CLOSE_VIBRATION = 1 << 4;
60 
61 enum SUPPORTED_FUNC : int32_t {
62     SUPPORTED_FUNC_NONE = -1,
63     SUPPORTED_FUNC_CHARGE = 0,
64     SUPPORTED_FUNC_MTP = 8,
65     SUPPORTED_FUNC_PTP = 16,
66     SUPPORTED_FUNC_REVERSECHARGE = 1 << 30,
67 };
68 
69 namespace OHOS {
70 namespace USB {
71 class NfcNotificationSubscriber : public Notification::NotificationSubscriber {
72     // LCOV_EXCL_START
OnConnected()73     void OnConnected()
74     {
75         USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
76     }
OnDisconnected()77     void OnDisconnected()
78     {
79         USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
80     }
OnUpdate(const std::shared_ptr<Notification::NotificationSortingMap> & sortingMap)81     void OnUpdate(const std::shared_ptr<Notification::NotificationSortingMap> &sortingMap)
82     {
83         USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
84     }
OnDoNotDisturbDateChange(const std::shared_ptr<Notification::NotificationDoNotDisturbDate> & date)85     void OnDoNotDisturbDateChange(const std::shared_ptr<Notification::NotificationDoNotDisturbDate> &date)
86     {
87         USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
88     }
OnEnabledNotificationChanged(const std::shared_ptr<Notification::EnabledNotificationCallbackData> & callbackData)89     void OnEnabledNotificationChanged(
90         const std::shared_ptr<Notification::EnabledNotificationCallbackData> &callbackData)
91     {
92         USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
93     }
OnDied()94     void OnDied()
95     {
96         USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
97     }
OnCanceled(const std::shared_ptr<OHOS::Notification::Notification> & request,const std::shared_ptr<Notification::NotificationSortingMap> & sortingMap,int deleteReason)98     void OnCanceled(const std::shared_ptr<OHOS::Notification::Notification> &request,
99         const std::shared_ptr<Notification::NotificationSortingMap> &sortingMap, int deleteReason)
100     {
101         USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
102     }
OnConsumed(const std::shared_ptr<OHOS::Notification::Notification> & notification,const std::shared_ptr<Notification::NotificationSortingMap> & sortingMap)103     void OnConsumed(const std::shared_ptr<OHOS::Notification::Notification> &notification,
104         const std::shared_ptr<Notification::NotificationSortingMap> &sortingMap)
105     {
106         USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
107     }
OnBadgeChanged(const std::shared_ptr<Notification::BadgeNumberCallbackData> & badgeData)108     void OnBadgeChanged(const std::shared_ptr<Notification::BadgeNumberCallbackData> &badgeData)
109     {
110         USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
111     }
OnBadgeEnabledChanged(const sptr<Notification::EnabledNotificationCallbackData> & callbackData)112     void OnBadgeEnabledChanged(const sptr<Notification::EnabledNotificationCallbackData> &callbackData)
113     {
114         USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
115     }
OnBatchCanceled(const std::vector<std::shared_ptr<OHOS::Notification::Notification>> & requestList,const std::shared_ptr<Notification::NotificationSortingMap> & sortingMap,int32_t deleteReason)116     void OnBatchCanceled(const std::vector<std::shared_ptr<OHOS::Notification::Notification>> &requestList,
117         const std::shared_ptr<Notification::NotificationSortingMap> &sortingMap, int32_t deleteReason)
118     {
119         USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
120     }
121     // LCOV_EXCL_STOP
122 };
123 
124 static std::shared_ptr<NfcNotificationSubscriber> g_notificationSubscriber
125     = std::make_shared<NfcNotificationSubscriber>();
126 
127 std::mutex UsbConnectionNotifier::insMutex_;
128 std::shared_ptr<UsbConnectionNotifier> UsbConnectionNotifier::instance_;
129 
GetInstance()130 std::shared_ptr<UsbConnectionNotifier> UsbConnectionNotifier::GetInstance()
131 {
132     std::lock_guard<std::mutex> guard(insMutex_);
133     if (instance_ == nullptr) {
134         USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: reset to new instance", __func__);
135         instance_.reset(new UsbConnectionNotifier());
136     }
137     return instance_;
138 }
139 
140 // LCOV_EXCL_START
GetBundleMgr(void)141 sptr<IBundleMgr> UsbConnectionNotifier::GetBundleMgr(void)
142 {
143     USB_TRACE;
144     sptr<ISystemAbilityManager> systemAbilityManager =
145         SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
146     if (systemAbilityManager == nullptr) {
147         USB_HILOGE(MODULE_USB_SERVICE, "%{public}s get systemAbilityManager failed", __func__);
148         return nullptr;
149     }
150     sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SA_ID);
151     if (remoteObject == nullptr) {
152         USB_HILOGE(MODULE_USB_SERVICE, "%{public}s get remoteObject failed", __func__);
153         return nullptr;
154     }
155     sptr<IBundleMgr> bundleMgr = iface_cast<IBundleMgr>(remoteObject);
156     if (bundleMgr == nullptr) {
157         USB_HILOGE(MODULE_USB_SERVICE, "%{public}s get bundleMgr failed", __func__);
158         return nullptr;
159     }
160     return bundleMgr;
161 }
162 
GetSetUid()163 void UsbConnectionNotifier::GetSetUid()
164 {
165     USB_TRACE;
166     int32_t userId = -1;
167     int32_t ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromProcess(userId);
168     if (ret != 0) {
169         USB_HILOGE(MODULE_USB_SERVICE, "%{public}s GetOsAccountLocalIdFromProcess ret:%{public}d", __func__, ret);
170         return;
171     }
172     sptr<AppExecFwk::IBundleMgr> bundleMgr = GetBundleMgr();
173     if (bundleMgr == nullptr) {
174         USB_HILOGE(MODULE_USB_SERVICE, "%{public}s GetBundleMgr failed", __func__);
175         return;
176     }
177     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s GetUidByBundleName", __func__);
178     g_uid = bundleMgr->GetUidByBundleName(SET_BUNDLE_NAME, USER_ID);
179     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s userId %{public}d, g_uid %{public}d", __func__, userId, g_uid);
180 }
181 
UsbConnectionNotifier()182 UsbConnectionNotifier::UsbConnectionNotifier()
183 {
184     USB_TRACE;
185     GetHapIcon();
186 
187     int32_t result = Notification::NotificationHelper::SubscribeNotification(*g_notificationSubscriber);
188     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: result %{public}d", __func__, result);
189 }
190 
~UsbConnectionNotifier()191 UsbConnectionNotifier::~UsbConnectionNotifier() {}
192 
GetHapIcon()193 void UsbConnectionNotifier::GetHapIcon()
194 {
195     USB_TRACE;
196     std::shared_ptr<Global::Resource::ResourceManager> resourceManager(Global::Resource::CreateResourceManager());
197     if (resourceManager == nullptr) {
198         USB_HILOGE(MODULE_USB_SERVICE, "resourceManager is null");
199         return;
200     }
201     if (!resourceManager->AddResource(HAP_PATH.c_str())) {
202         USB_HILOGE(MODULE_USB_SERVICE, "AddResource failed");
203         return;
204     }
205     size_t len = 0;
206     std::unique_ptr<uint8_t[]> data;
207     resourceManager->GetMediaDataByName(ICON_NAME.c_str(), len, data);
208     Media::SourceOptions opts;
209     uint32_t errorCode = 0;
210     std::unique_ptr<Media::ImageSource> imageSource =
211         Media::ImageSource::CreateImageSource(data.get(), len, opts, errorCode);
212     Media::DecodeOptions decodeOpts;
213     decodeOpts.desiredPixelFormat = Media::PixelFormat::BGRA_8888;
214     if (imageSource) {
215         auto pixelMapPtr = imageSource->CreatePixelMap(decodeOpts, errorCode);
216         icon_ = std::shared_ptr<Media::PixelMap>(pixelMapPtr.release());
217     }
218     if (errorCode != 0 || !icon_) {
219         USB_HILOGE(MODULE_USB_SERVICE, "Get icon failed");
220     }
221     return;
222 }
223 
GetHapString()224 void UsbConnectionNotifier::GetHapString()
225 {
226     USB_TRACE;
227     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
228     std::shared_ptr<Global::Resource::ResourceManager> resourceManager(Global::Resource::CreateResourceManager());
229     if (resourceManager == nullptr) {
230         USB_HILOGE(MODULE_USB_SERVICE, "%{public}s resourceManager is null", __func__);
231         return;
232     }
233     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
234     if (resConfig == nullptr) {
235         USB_HILOGE(MODULE_USB_SERVICE, "%{public}s resConfig is null", __func__);
236         return;
237     }
238     std::map<std::string, std::string> configs;
239     OHOS::Global::I18n::LocaleInfo locale(Global::I18n::LocaleConfig::GetEffectiveLanguage(), configs);
240     resConfig->SetLocaleInfo(locale.GetLanguage().c_str(), locale.GetScript().c_str(), locale.GetRegion().c_str());
241     resourceManager->UpdateResConfig(*resConfig);
242     if (!resourceManager->AddResource(HAP_PATH.c_str())) {
243         USB_HILOGE(MODULE_USB_SERVICE, "%{public}s AddResource failed", __func__);
244         return;
245     }
246     for (auto it : notifierMap) {
247         std::string outValue;
248         resourceManager->GetStringByName(it.first.c_str(), outValue);
249         notifierMap[it.first] = outValue;
250     }
251     return;
252 }
253 
SetWantAgent(OHOS::Notification::NotificationRequest & request)254 void UsbConnectionNotifier::SetWantAgent(OHOS::Notification::NotificationRequest &request)
255 {
256     USB_TRACE;
257     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
258     auto want = std::make_shared<AAFwk::Want>();
259     want->SetElementName(BUNDLE_NAME, BUNDLE_NAME_KEY);
260     want->SetUri(URI);
261     want->SetParam("usbSupportedFunctions", usbSupportedFunctions_);
262     std::vector<std::shared_ptr<AAFwk::Want>> wants;
263     wants.push_back(want);
264 
265     std::vector<AbilityRuntime::WantAgent::WantAgentConstant::Flags> flags;
266     flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::CONSTANT_FLAG);
267 
268     AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo(
269         0, AbilityRuntime::WantAgent::WantAgentConstant::OperationType::START_ABILITY, flags, wants, nullptr);
270     auto wantAgent = AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo);
271     request.SetWantAgent(wantAgent);
272 }
273 
SetWantAgentHdc(OHOS::Notification::NotificationRequest & request)274 void UsbConnectionNotifier::SetWantAgentHdc(OHOS::Notification::NotificationRequest &request)
275 {
276     USB_TRACE;
277     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
278     auto want = std::make_shared<AAFwk::Want>();
279     want->SetElementName(SETTING_BUNDLE_NAME, SETTING_BUNDLE_NAME_ABILITY);
280     want->SetUri(SETTING_BUNDLE_NAME_URL);
281     std::vector<std::shared_ptr<AAFwk::Want>> wants;
282     wants.push_back(want);
283 
284     std::vector<AbilityRuntime::WantAgent::WantAgentConstant::Flags> flags;
285     flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::CONSTANT_FLAG);
286 
287     AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo(
288         0, AbilityRuntime::WantAgent::WantAgentConstant::OperationType::START_ABILITY, flags, wants, nullptr);
289     auto wantAgent = AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo);
290     request.SetWantAgent(wantAgent);
291 }
292 
SendNotification(std::string func)293 void UsbConnectionNotifier::SendNotification(std::string func)
294 {
295     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: func %{public}s", __func__, func.c_str());
296 
297     usbSupportedFunctions_ = GetSupportedFunctions();
298     HITRACE_METER_FMT(HITRACE_TAG_HDF, "%s func %s usbSupportedFunctions_ %d", __func__, func.c_str(),
299         usbSupportedFunctions_);
300 
301     if (usbSupportedFunctions_ <= 0) {
302         return;
303     }
304 
305     GetHapString();
306     std::shared_ptr<OHOS::Notification::NotificationNormalContent> normalContent =
307         std::make_shared<OHOS::Notification::NotificationNormalContent>();
308     normalContent->SetTitle(notifierMap[func]);
309     normalContent->SetText(notifierMap[USB_FUNC_MORE]);
310     std::shared_ptr<OHOS::Notification::NotificationContent> content =
311         std::make_shared<OHOS::Notification::NotificationContent>(normalContent);
312 
313     request_.SetNotificationId(NOTIFICATION_ID_ZERO);
314     request_.SetContent(content);
315     request_.SetCreatorUid(g_uid);
316     request_.SetUnremovable(true);
317     request_.SetRemoveAllowed(true);
318     request_.SetTapDismissed(false);
319     request_.SetGroupName(NOTIFICATION_NAME);
320     if (icon_.has_value()) {
321         request_.SetLittleIcon(icon_.value());
322     }
323     SetWantAgent(request_);
324     StartTraceEx(HITRACE_LEVEL_INFO, HITRACE_TAG_HDF, "Helper::PublishNotification");
325     int32_t result = OHOS::Notification::NotificationHelper::PublishNotification(request_);
326     FinishTraceEx(HITRACE_LEVEL_INFO, HITRACE_TAG_HDF);
327     USB_HILOGI(MODULE_USB_SERVICE, "PublishNotification result : %{public}d", result);
328 }
329 
CancelNotification()330 void UsbConnectionNotifier::CancelNotification()
331 {
332     USB_TRACE;
333     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
334     int32_t notificationId = request_.GetNotificationId();
335     int32_t result = OHOS::Notification::NotificationHelper::CancelNotification(notificationId);
336     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: notificationId %{public}d, result %{public}d", __func__,
337         notificationId, result);
338 }
339 
GetSupportedFunctions()340 int32_t UsbConnectionNotifier::GetSupportedFunctions()
341 {
342     USB_TRACE;
343     std::string supportedFuncStr = "";
344     (void)OHOS::system::GetStringParameter("const.usb_manager.supported_functions",
345         supportedFuncStr, DEFAULT_PARAM_VALUE);
346     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: supportedFuncStr %{public}s", __func__, supportedFuncStr.c_str());
347 
348     if (supportedFuncStr.find("none") != std::string::npos) {
349         return SUPPORTED_FUNC_NONE;
350     }
351     uint32_t mtp = supportedFuncStr.find("mtp") != std::string::npos ? SUPPORTED_FUNC_MTP : 0;
352     uint32_t ptp = supportedFuncStr.find("ptp") != std::string::npos ? SUPPORTED_FUNC_PTP : 0;
353     uint32_t reverseCharge =
354         supportedFuncStr.find("reverseCharge") != std::string::npos ? SUPPORTED_FUNC_REVERSECHARGE : 0;
355 
356     return static_cast<int32_t>(mtp | ptp | reverseCharge);
357 }
358 
SendHdcNotification()359 void UsbConnectionNotifier::SendHdcNotification()
360 {
361     USB_TRACE;
362     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
363 
364     GetHapString();
365     std::shared_ptr<OHOS::Notification::NotificationNormalContent> normalContent =
366             std::make_shared<OHOS::Notification::NotificationNormalContent>();
367     normalContent->SetTitle(notifierMap[USB_HDC_NOTIFIER_TITLE]);
368     normalContent->SetText(notifierMap[USB_HDC_NOTIFIER_CONTENT]);
369     std::shared_ptr<OHOS::Notification::NotificationContent> content =
370             std::make_shared<OHOS::Notification::NotificationContent>(normalContent);
371 
372     requestHdc_.SetNotificationId(NOTIFICATION_ID_ONE);
373     requestHdc_.SetContent(content);
374     requestHdc_.SetCreatorUid(g_uid);
375     requestHdc_.SetUnremovable(true);
376     requestHdc_.SetRemoveAllowed(true);
377     requestHdc_.SetTapDismissed(false);
378     requestHdc_.SetGroupName(NOTIFICATION_NAME_ONE);
379     requestHdc_.SetSlotType(OHOS::Notification::NotificationConstant::SlotType::SERVICE_REMINDER);
380     requestHdc_.SetNotificationControlFlags(NOTIFICATION_STATUS_CLOSE_SOUND |
381                                             NOTIFICATION_STATUS_CLOSE_LOCKSCREEN |
382                                             NOTIFICATION_STATUS_CLOSE_BANNER |
383                                             NOTIFICATION_STATUS_CLOSE_LIGHT_SCREEN |
384                                             NOTIFICATION_STATUS_CLOSE_VIBRATION);
385     if (icon_.has_value()) {
386         requestHdc_.SetLittleIcon(icon_.value());
387     }
388     SetWantAgentHdc(requestHdc_);
389     StartTraceEx(HITRACE_LEVEL_INFO, HITRACE_TAG_HDF, "Helper::PublishNotification");
390     int32_t result = OHOS::Notification::NotificationHelper::PublishNotification(requestHdc_);
391     FinishTraceEx(HITRACE_LEVEL_INFO, HITRACE_TAG_HDF);
392     USB_HILOGI(MODULE_USB_SERVICE, "PublishNotification result : %{public}d", result);
393 }
394 
CancelHdcNotification()395 void UsbConnectionNotifier::CancelHdcNotification()
396 {
397     USB_TRACE;
398     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s", __func__);
399     int32_t notificationId = requestHdc_.GetNotificationId();
400     int32_t result = OHOS::Notification::NotificationHelper::CancelNotification(notificationId);
401     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: notificationId %{public}d, result %{public}d", __func__,
402                notificationId, result);
403 }
404 // LCOV_EXCL_STOP
405 
406 } // namespace USB
407 } // namespace OHOS