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