• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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 <cinttypes>
17 #include <regex>
18 
19 #include "ability_manager_errors.h"
20 #include "appexecfwk_errors.h"
21 #include "form_acquire_connection.h"
22 #include "form_acquire_state_connection.h"
23 #include "form_ams_helper.h"
24 #include "form_bms_helper.h"
25 #include "form_cache_mgr.h"
26 #include "form_cast_temp_connection.h"
27 #include "form_constants.h"
28 #include "form_data_mgr.h"
29 #include "form_db_cache.h"
30 #include "form_db_info.h"
31 #include "form_delete_connection.h"
32 #include "form_dump_mgr.h"
33 #include "form_event_notify_connection.h"
34 #include "form_info_mgr.h"
35 #include "form_mgr_adapter.h"
36 #include "form_provider_info.h"
37 #include "form_provider_interface.h"
38 #include "form_provider_mgr.h"
39 #include "form_refresh_connection.h"
40 #include "form_supply_callback.h"
41 #include "form_timer_mgr.h"
42 #include "form_util.h"
43 #include "hilog_wrapper.h"
44 #include "if_system_ability_manager.h"
45 #include "in_process_call_wrapper.h"
46 #include "ipc_skeleton.h"
47 #include "iservice_registry.h"
48 #include "ohos_account_kits.h"
49 #include "power_mgr_client.h"
50 #include "system_ability_definition.h"
51 
52 namespace OHOS {
53 namespace AppExecFwk {
54 const int HUNDRED = 100;
55 constexpr int32_t UID_CALLINGUID_TRANSFORM_DIVISOR = 200000;
56 
FormMgrAdapter()57 FormMgrAdapter::FormMgrAdapter()
58 {
59 };
~FormMgrAdapter()60 FormMgrAdapter::~FormMgrAdapter()
61 {
62 };
63 /**
64  * @brief Add form with want, send want to form manager service.
65  * @param formId The Id of the forms to add.
66  * @param want The want of the form to add.
67  * @param callerToken Caller ability token.
68  * @param formInfo Form info.
69  * @return Returns ERR_OK on success, others on failure.
70  */
AddForm(const int64_t formId,const Want & want,const sptr<IRemoteObject> & callerToken,FormJsInfo & formInfo)71 int FormMgrAdapter::AddForm(const int64_t formId, const Want &want,
72     const sptr<IRemoteObject> &callerToken, FormJsInfo &formInfo)
73 {
74     if (formId < 0 || callerToken == nullptr) {
75         HILOG_ERROR("%{public}s fail, callerToken can not be NULL", __func__);
76         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
77     }
78 
79     // check form count limit
80     bool tempFormFlag = want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false);
81     int callingUid = IPCSkeleton::GetCallingUid();
82     int checkCode = 0;
83     if (tempFormFlag) {
84         if (formId > 0) {
85             HILOG_ERROR("%{public}s fail, temp form id is invalid, formId:%{public}" PRId64 "", __func__, formId);
86             return ERR_APPEXECFWK_FORM_INVALID_PARAM;
87         }
88         checkCode = FormDataMgr::GetInstance().CheckTempEnoughForm();
89     } else {
90         if (formId == 0) {
91             // get current userId
92             int32_t currentUserId = GetCurrentUserId(callingUid);
93             checkCode = FormDataMgr::GetInstance().CheckEnoughForm(callingUid, currentUserId);
94         }
95     }
96     if (checkCode != 0) {
97         HILOG_ERROR("%{public}s fail, too much forms in system", __func__);
98         return checkCode;
99     }
100 
101     // get from config info
102     FormItemInfo formItemInfo;
103     int32_t errCode = GetFormConfigInfo(want, formItemInfo);
104     formItemInfo.SetFormId(formId);
105     if (errCode != ERR_OK) {
106         HILOG_ERROR("%{public}s fail, get form config info failed.", __func__);
107         return errCode;
108     }
109     if (!formItemInfo.IsValidItem()) {
110         HILOG_ERROR("%{public}s fail, input param itemInfo is invalid", __func__);
111         return ERR_APPEXECFWK_FORM_GET_INFO_FAILED;
112     }
113     if (!FormDataMgr::GetInstance().GenerateUdidHash()) {
114         HILOG_ERROR("%{public}s fail, generate udid hash failed", __func__);
115         return ERR_APPEXECFWK_FORM_COMMON_CODE;
116     }
117     formItemInfo.SetDeviceId(want.GetElement().GetDeviceID());
118     WantParams wantParams = want.GetParams();
119     if (formId > 0) {
120         return AllotFormById(formItemInfo, callerToken, wantParams, formInfo);
121     } else {
122         return AllotFormByInfo(formItemInfo, callerToken, wantParams, formInfo);
123     }
124 }
125 
126 /**
127  * @brief Delete forms with formIds, send formIds to form manager service.
128  * @param formId The Id of the forms to delete.
129  * @param callerToken Caller ability token.
130  * @return Returns ERR_OK on success, others on failure.
131  */
DeleteForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)132 int FormMgrAdapter::DeleteForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
133 {
134     if (formId <= 0 || callerToken == nullptr) {
135         HILOG_ERROR("%{public}s, deleteForm invalid param", __func__);
136         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
137     }
138     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
139     if (FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) {
140         // delete temp form if receive delete form call
141         return HandleDeleteTempForm(matchedFormId, callerToken);
142     }
143     return HandleDeleteForm(matchedFormId, callerToken);
144 }
145 
146 /**
147  * @brief Release forms with formIds, send formIds to form Mgr service.
148  * @param formId The Id of the forms to release.
149  * @param callerToken Caller ability token.
150  * @param delCache Delete Cache or not.
151  * @return Returns ERR_OK on success, others on failure.
152  */
ReleaseForm(const int64_t formId,const sptr<IRemoteObject> & callerToken,const bool delCache)153 int FormMgrAdapter::ReleaseForm(const int64_t formId, const sptr<IRemoteObject> &callerToken, const bool delCache)
154 {
155     HILOG_INFO("%{public}s called.", __func__);
156 
157     if (formId <= 0 || callerToken == nullptr) {
158         HILOG_ERROR("%{public}s, releaseForm invalid param", __func__);
159         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
160     }
161     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
162     if (FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) {
163         // delete temp form if receive release form call
164         return HandleDeleteTempForm(matchedFormId, callerToken);
165     }
166     FormRecord dbRecord;
167     if (FormDbCache::GetInstance().GetDBRecord(matchedFormId, dbRecord) != ERR_OK) {
168         HILOG_ERROR("%{public}s, not exist such db form:%{public}" PRId64 "", __func__, formId);
169         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
170     }
171     int callingUid = IPCSkeleton::GetCallingUid();
172     int32_t userId = GetCurrentUserId(callingUid);
173     bool isSelfDbFormId = (userId == dbRecord.userId) && ((std::find(dbRecord.formUserUids.begin(),
174     dbRecord.formUserUids.end(), callingUid) != dbRecord.formUserUids.end()) ? true : false);
175     if (!isSelfDbFormId) {
176         HILOG_ERROR("%{public}s, not self form:%{public}" PRId64 "", __func__, formId);
177         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
178     }
179     if (delCache) {
180         if (ErrCode result = HandleReleaseForm(matchedFormId, callerToken); result != ERR_OK) {
181             HILOG_ERROR("%{public}s, release form error.", __func__);
182             return result;
183         }
184     }
185 
186     if (!FormDataMgr::GetInstance().DeleteHostRecord(callerToken, matchedFormId)) {
187         HILOG_ERROR("%{public}s, failed to remove host record", __func__);
188         return ERR_APPEXECFWK_FORM_COMMON_CODE;
189     }
190     if (!FormTimerMgr::GetInstance().RemoveFormTimer(matchedFormId)) {
191         HILOG_ERROR("%{public}s, remove timer error", __func__);
192         return ERR_APPEXECFWK_FORM_COMMON_CODE;
193     }
194     return ERR_OK;
195 }
196 
197 /**
198  * @brief Handle release form.
199  * @param formId The form id.
200  * @param callerToken Caller ability token.
201  * @return Returns ERR_OK on success, others on failure.
202  */
HandleReleaseForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)203 ErrCode FormMgrAdapter::HandleReleaseForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
204 {
205     HILOG_INFO("%{public}s called.", __func__);
206     if (!FormDataMgr::GetInstance().ExistFormRecord(formId)) {
207         HILOG_ERROR("%{public}s, not exist such db or temp form:%{public}" PRId64 "", __func__, formId);
208         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
209     }
210 
211     FormHostRecord hostRecord;
212     bool hasHostRec = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, hostRecord);
213     bool isSelfId = hasHostRec && hostRecord.Contains(formId);
214     if (!isSelfId) {
215         HILOG_ERROR("%{public}s, not self form:%{public}" PRId64 "", __func__, formId);
216         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
217     }
218 
219     HILOG_DEBUG("%{public}s, release formRecords, formId: %{public}" PRId64 "", __func__, formId);
220     FormDataMgr::GetInstance().DeleteFormUserUid(formId, IPCSkeleton::GetCallingUid());
221     if (!FormDataMgr::GetInstance().HasFormUserUids(formId)) {
222         FormDataMgr::GetInstance().DeleteFormRecord(formId);
223         if (!FormTimerMgr::GetInstance().RemoveFormTimer(formId)) {
224             HILOG_ERROR("%{public}s, remove timer error", __func__);
225             return ERR_APPEXECFWK_FORM_COMMON_CODE;
226         }
227     }
228     return ERR_OK;
229 }
230 
231 /**
232  * @brief Handle delete form.
233  * @param formId The form id.
234  * @param callerToken Caller ability token.
235  * @return Returns ERR_OK on success, others on failure.
236  */
HandleDeleteForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)237 ErrCode FormMgrAdapter::HandleDeleteForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
238 {
239     FormRecord dbRecord;
240     if (FormDbCache::GetInstance().GetDBRecord(formId, dbRecord) != ERR_OK) {
241         HILOG_ERROR("%{public}s, not exist such db form:%{public}" PRId64 "", __func__, formId);
242         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
243     }
244 
245     int callingUid = IPCSkeleton::GetCallingUid();
246     int32_t userId = GetCurrentUserId(callingUid);
247     bool isSelfDbFormId = (userId == dbRecord.userId) && ((std::find(dbRecord.formUserUids.begin(),
248     dbRecord.formUserUids.end(), callingUid) != dbRecord.formUserUids.end()) ? true : false);
249     if (!isSelfDbFormId) {
250         HILOG_ERROR(
251             "%{public}s, not self form:%{public}" PRId64 ", callingUid:%{public}d", __func__, formId, callingUid);
252         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
253     }
254 
255     if (ErrCode result = HandleDeleteFormCache(dbRecord, callingUid, formId); result != ERR_OK) {
256         return result;
257     }
258 
259     if (!FormDataMgr::GetInstance().DeleteHostRecord(callerToken, formId)) {
260         HILOG_ERROR("%{public}s, failed to remove host record", __func__);
261         return ERR_APPEXECFWK_FORM_COMMON_CODE;
262     }
263 
264     return ERR_OK;
265 }
266 
267 /**
268  * @brief Handle delete temp form.
269  * @param formId The form id.
270  * @param callerToken Caller ability token.
271  * @return Returns ERR_OK on success, others on failure.
272  */
HandleDeleteTempForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)273 ErrCode FormMgrAdapter::HandleDeleteTempForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
274 {
275     HILOG_INFO("%{public}s called.", __func__);
276 
277     int uid = IPCSkeleton::GetCallingUid();
278     FormRecord record;
279     bool isFormRecExist = FormDataMgr::GetInstance().GetFormRecord(formId, record);
280     bool isSelfTempFormId = false;
281     if (isFormRecExist && record.formTempFlg) {
282         int32_t userId = GetCurrentUserId(uid);
283         isSelfTempFormId = (userId == record.userId) && ((std::find(record.formUserUids.begin(),
284         record.formUserUids.end(), uid) != record.formUserUids.end()) ? true : false);
285     }
286     if (!isSelfTempFormId) {
287         HILOG_ERROR("%{public}s, not self form:%{public}" PRId64 "", __func__, formId);
288         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
289     }
290 
291     FormDataMgr::GetInstance().DeleteFormUserUid(formId, uid);
292     if (!FormDataMgr::GetInstance().HasFormUserUids(formId)) {
293         int result = FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, record);
294         if (result != ERR_OK) {
295             HILOG_ERROR("%{public}s, failed!", __func__);
296             FormDataMgr::GetInstance().AddFormUserUid(formId, uid);
297             return result;
298         }
299         FormDataMgr::GetInstance().DeleteTempForm(formId);
300         FormDataMgr::GetInstance().DeleteFormRecord(formId);
301         if (!FormCacheMgr::GetInstance().DeleteData(formId)) {
302             HILOG_ERROR("%{public}s, failed to remove cache data", __func__);
303             return ERR_APPEXECFWK_FORM_COMMON_CODE;
304         }
305     }
306 
307     if (!FormDataMgr::GetInstance().DeleteHostRecord(callerToken, formId)) {
308         HILOG_ERROR("%{public}s, failed to remove host record", __func__);
309         return ERR_APPEXECFWK_FORM_COMMON_CODE;
310     }
311 
312     HILOG_DEBUG("%{public}s, record.formUserUids size: %{public}zu", __func__, record.formUserUids.size());
313     return ERR_OK;
314 }
315 
316 /**
317  * @brief Handle delete form cache.
318  * @param dbRecord Form storage information.
319  * @param uid calling user id.
320  * @param formId The form id.
321  * @return Returns ERR_OK on success, others on failure.
322  */
HandleDeleteFormCache(FormRecord & dbRecord,const int uid,const int64_t formId)323 ErrCode FormMgrAdapter::HandleDeleteFormCache(FormRecord &dbRecord, const int uid, const int64_t formId)
324 {
325     HILOG_DEBUG("%{public}s, delete formDBRecords, formId: %{public}" PRId64 "", __func__, formId);
326     auto iter = std::find(dbRecord.formUserUids.begin(), dbRecord.formUserUids.end(), uid);
327     if (iter != dbRecord.formUserUids.end()) {
328         dbRecord.formUserUids.erase(iter);
329     }
330 
331     ErrCode result = ERR_OK;
332     if (dbRecord.formUserUids.empty()) {
333         result = FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, dbRecord);
334         if (result != ERR_OK) {
335             HILOG_ERROR("%{public}s, failed to notify provider form delete", __func__);
336             return result;
337         }
338         if (!FormDataMgr::GetInstance().DeleteFormRecord(formId)) {
339             HILOG_ERROR("%{public}s, failed to remove cache data", __func__);
340             return ERR_APPEXECFWK_FORM_COMMON_CODE;
341         }
342         if (result = FormDbCache::GetInstance().DeleteFormInfo(formId); result != ERR_OK) {
343             HILOG_ERROR("%{public}s, failed to remove db data", __func__);
344             return result;
345         }
346 
347         int32_t matchCount = FormDbCache::GetInstance().GetMatchCount(dbRecord.bundleName, dbRecord.moduleName);
348         if (matchCount == 0) {
349             FormBmsHelper::GetInstance().NotifyModuleRemovable(dbRecord.bundleName, dbRecord.moduleName);
350         }
351 
352         if (!FormCacheMgr::GetInstance().DeleteData(formId)) {
353             HILOG_ERROR("%{public}s, failed to remove cache data", __func__);
354             return ERR_APPEXECFWK_FORM_COMMON_CODE;
355         }
356         if (!FormTimerMgr::GetInstance().RemoveFormTimer(formId)) {
357             HILOG_ERROR("%{public}s, remove timer error", __func__);
358             return ERR_APPEXECFWK_FORM_COMMON_CODE;
359         }
360         return ERR_OK;
361     }
362 
363     if (result = FormDbCache::GetInstance().UpdateDBRecord(formId, dbRecord); result != ERR_OK) {
364         return result;
365     }
366 
367     HILOG_DEBUG("%{public}s, dbRecord.formUserUids size: %{public}zu", __func__, dbRecord.formUserUids.size());
368     FormBmsHelper::GetInstance().NotifyModuleNotRemovable(dbRecord.bundleName, dbRecord.moduleName);
369     FormDataMgr::GetInstance().DeleteFormUserUid(formId, uid);
370     return result;
371 }
372 
373 /**
374  * @brief Update form with formId, send formId to form manager service.
375  * @param formId The Id of the form to update.
376  * @param bundleName Provider ability bundleName.
377  * @param formProviderData form provider data.
378  * @return Returns ERR_OK on success, others on failure.
379  */
UpdateForm(const int64_t formId,const std::string & bundleName,const FormProviderData & formProviderData)380 int FormMgrAdapter::UpdateForm(const int64_t formId,
381     const std::string &bundleName, const FormProviderData &formProviderData)
382 {
383     HILOG_INFO("%{public}s start.", __func__);
384 
385     // check formId and bundleName
386     if (formId <= 0 || bundleName.empty()) {
387         HILOG_ERROR("%{public}s error, the passed in formId can't be negative or zero, bundleName is not empty.",
388             __func__);
389         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
390     }
391 
392     // get IBundleMgr
393     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
394     if (iBundleMgr == nullptr) {
395         HILOG_ERROR("%{public}s error, failed to get IBundleMgr.", __func__);
396         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
397     }
398 
399     // check bundle uid for permission
400     int callingUid = IPCSkeleton::GetCallingUid();
401     int32_t userId = GetCurrentUserId(callingUid);
402     int32_t bundleUid = IN_PROCESS_CALL(iBundleMgr->GetUidByBundleName(bundleName, userId));
403     if (bundleUid != callingUid) {
404         HILOG_ERROR("%{public}s error, permission denied, the updated form is not your own.", __func__);
405         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
406     }
407 
408     // find matched formId
409     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
410 
411     // check exist and get the formRecord
412     FormRecord formRecord;
413     if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) {
414         HILOG_ERROR("%{public}s error, not exist such form:%{public}" PRId64 ".", __func__, matchedFormId);
415         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
416     }
417 
418     if (userId != formRecord.userId) {
419         HILOG_ERROR("%{public}s error, not under current user, formId:%{public}" PRId64 ".", __func__, matchedFormId);
420         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
421     }
422 
423     // check bundleName match
424     if (formRecord.bundleName.compare(bundleName) != 0) {
425         HILOG_ERROR("%{public}s error, not match bundleName:%{public}s.", __func__, bundleName.c_str());
426         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
427     }
428 
429     // update Form
430     return FormProviderMgr::GetInstance().UpdateForm(matchedFormId, formRecord, formProviderData);
431 }
432 
433 /**
434  * @brief Request form with formId and want, send formId and want to form manager service.
435  * @param formId The Id of the form to update.
436  * @param callerToken Caller ability token.
437  * @param want The want of the form to request.
438  * @return Returns ERR_OK on success, others on failure.
439  */
RequestForm(const int64_t formId,const sptr<IRemoteObject> & callerToken,const Want & want)440 int FormMgrAdapter::RequestForm(const int64_t formId, const sptr<IRemoteObject> &callerToken, const Want &want)
441 {
442     HILOG_INFO("%{public}s called.", __func__);
443 
444     if (formId <= 0 || callerToken == nullptr) {
445         HILOG_ERROR("%{public}s fail, callerToken can not be NULL.", __func__);
446         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
447     }
448 
449     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
450     if (!FormDataMgr::GetInstance().ExistFormRecord(matchedFormId)) {
451         HILOG_ERROR("%{public}s fail, not exist such formId:%{public}" PRId64 ".", __func__, matchedFormId);
452         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
453     }
454 
455     FormHostRecord formHostRecord;
456     bool isHostExist = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord);
457     if (!isHostExist) {
458         HILOG_ERROR("%{public}s fail, cannot find target client.", __func__);
459         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
460     }
461 
462     if (!formHostRecord.Contains(matchedFormId)) {
463         HILOG_ERROR("%{public}s fail, form is not self-owned.", __func__);
464         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
465     }
466 
467     HILOG_INFO("%{public}s, find target client.", __func__);
468     Want reqWant(want);
469     int callingUid = IPCSkeleton::GetCallingUid();
470     int32_t userId = GetCurrentUserId(callingUid);
471     reqWant.SetParam(Constants::PARAM_FORM_USER_ID, userId);
472     return FormProviderMgr::GetInstance().RefreshForm(matchedFormId, reqWant, true);
473 }
474 
475 /**
476  * @brief Form visible/invisible notify, send formIds to form manager service.
477  * @param formIds The vector of form Ids.
478  * @param callerToken Caller ability token.
479  * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE.
480  * @return Returns ERR_OK on success, others on failure.
481  */
NotifyWhetherVisibleForms(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,const int32_t formVisibleType)482 ErrCode FormMgrAdapter::NotifyWhetherVisibleForms(const std::vector<int64_t> &formIds,
483     const sptr<IRemoteObject> &callerToken, const int32_t formVisibleType)
484 {
485     HILOG_INFO("%{public}s called.", __func__);
486 
487     if (callerToken == nullptr) {
488         HILOG_ERROR("%{public}s fail, callerToken can not be NULL.", __func__);
489         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
490     }
491 
492     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
493     if (iBundleMgr == nullptr) {
494         HILOG_ERROR("%{public}s fail, failed to get IBundleMgr.", __func__);
495         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
496     }
497 
498     int64_t matchedFormId;
499     std::map<std::string, std::vector<int64_t>> eventMaps;
500     for (int64_t formId : formIds) {
501         if (formId <= 0) {
502             HILOG_WARN("%{public}s, formId %{public}" PRId64 " is less than 0", __func__, formId);
503             continue;
504         }
505         matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
506         FormRecord formRecord;
507         // Update provider info to host
508         if (!UpdateProviderInfoToHost(matchedFormId, callerToken, formVisibleType, formRecord)) {
509             continue;
510         }
511 
512         // Check if the form provider is system app
513         if (!CheckIsSystemAppByBundleName(iBundleMgr, formRecord.bundleName)) {
514             continue;
515         }
516 
517         // Create eventMaps
518         if (!CreateHandleEventMap(matchedFormId, formRecord, eventMaps)) {
519             continue;
520         }
521     }
522 
523     for (auto iter = eventMaps.begin(); iter != eventMaps.end(); iter++) {
524         if (HandleEventNotify(iter->first, iter->second, formVisibleType) != ERR_OK) {
525             HILOG_WARN("%{public}s fail, HandleEventNotify error, key is %{public}s.", __func__, iter->first.c_str());
526         }
527     }
528 
529     return ERR_OK;
530 }
531 
532 /**
533  * @brief Temp form to normal form.
534  * @param formId The Id of the form.
535  * @return Returns ERR_OK on success, others on failure.
536  */
CastTempForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)537 int FormMgrAdapter::CastTempForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
538 {
539     if (formId <= 0 || callerToken == nullptr) {
540         HILOG_ERROR("%{public}s, invalid param", __func__);
541         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
542     }
543 
544     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
545     if (!FormDataMgr::GetInstance().ExistFormRecord(matchedFormId) ||
546         !FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) {
547         HILOG_ERROR("%{public}s, not exist such temp form:%{public}" PRId64 "", __func__, matchedFormId);
548         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
549     }
550 
551     FormHostRecord record;
552     bool hasHostRec = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, record);
553     if (!hasHostRec || !record.Contains(matchedFormId)) {
554         HILOG_ERROR("%{public}s, not self form:%{public}" PRId64 "", __func__, matchedFormId);
555         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
556     }
557 
558     int callingUid = IPCSkeleton::GetCallingUid();
559     int32_t userId = GetCurrentUserId(callingUid);
560     int checkCode = FormDataMgr::GetInstance().CheckEnoughForm(callingUid, userId);
561     if (checkCode != 0) {
562         HILOG_ERROR("%{public}s, %{public}" PRId64 " failed,because if too mush forms", __func__, matchedFormId);
563         return checkCode;
564     }
565 
566     FormRecord formRecord;
567     if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) {
568         HILOG_ERROR("%{public}s fail, not exist such form:%{public}" PRId64 ".", __func__, matchedFormId);
569         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
570     }
571     int bindSupplierCheckCode = HandleCastTempForm(matchedFormId, formRecord);
572     if (bindSupplierCheckCode != 0) {
573         HILOG_ERROR("%{public}s, cast temp form bindSupplier failed", __func__);
574         return bindSupplierCheckCode;
575     }
576 
577     if (!FormDataMgr::GetInstance().DeleteTempForm(matchedFormId)) {
578         HILOG_ERROR("%{public}s fail, delete temp form error, formId:%{public}" PRId64 ".", __func__, matchedFormId);
579         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
580     }
581     if (!FormDataMgr::GetInstance().ModifyFormTempFlg(matchedFormId, false)) {
582         HILOG_ERROR(
583             "%{public}s fail, modify form temp flag error, formId:%{public}" PRId64 ".", __func__, matchedFormId);
584         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
585     }
586     if (!FormDataMgr::GetInstance().AddFormUserUid(matchedFormId, callingUid)) {
587         HILOG_ERROR("%{public}s fail, add form user uid error, formId:%{public}" PRId64 ".", __func__, matchedFormId);
588         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
589     }
590 
591     if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) {
592         HILOG_ERROR("%{public}s fail, not exist such form:%{public}" PRId64 ".", __func__, matchedFormId);
593         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
594     }
595 
596     if (ErrCode errorCode = FormDbCache::GetInstance().UpdateDBRecord(matchedFormId, formRecord); errorCode != ERR_OK) {
597         HILOG_ERROR("%{public}s fail, update db record error, formId:%{public}" PRId64 ".", __func__, matchedFormId);
598         return errorCode;
599     }
600 
601     // start timer
602     return AddFormTimer(formRecord);
603 }
604 /**
605  * @brief Handle cast temp form.
606  * @param formId The form id.
607  * @param record Form information.
608  * @return Returns ERR_OK on success, others on failure.
609  */
HandleCastTempForm(const int64_t formId,const FormRecord & record)610 ErrCode FormMgrAdapter::HandleCastTempForm(const int64_t formId, const FormRecord &record)
611 {
612     HILOG_DEBUG("%{public}s, cast temp form to normal form, notify supplier, package:%{public}s, class:%{public}s",
613         __func__, record.bundleName.c_str(), record.abilityName.c_str());
614     sptr<IAbilityConnection> castTempConnection = new FormCastTempConnection(formId,
615         record.bundleName, record.abilityName);
616 
617     Want want;
618     want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED);
619     want.SetElementName(record.bundleName, record.abilityName);
620     ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, castTempConnection);
621     if (errorCode != ERR_OK) {
622         HILOG_ERROR("%{public}s fail, ConnectServiceAbility failed.", __func__);
623         return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED;
624     }
625     return ERR_OK;
626 }
627 /**
628  * @brief Dump all of form storage infos.
629  * @param formInfos All of form storage infos.
630  * @return Returns ERR_OK on success, others on failure.
631  */
DumpStorageFormInfos(std::string & formInfos) const632 int FormMgrAdapter::DumpStorageFormInfos(std::string &formInfos) const
633 {
634     std::vector<FormDBInfo> formDBInfos;
635     FormDbCache::GetInstance().GetAllFormInfo(formDBInfos);
636     if (formDBInfos.size() > 0) {
637         std::sort(formDBInfos.begin(), formDBInfos.end(),
638         [] (FormDBInfo &formDBInfoA, FormDBInfo &formDBInfoB) -> bool {
639             return formDBInfoA.formId < formDBInfoB.formId;
640         });
641         FormDumpMgr::GetInstance().DumpStorageFormInfos(formDBInfos, formInfos);
642         return ERR_OK;
643     } else {
644         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
645     }
646 }
647 /**
648  * @brief Dump form info by a bundle name.
649  * @param bundleName The bundle name of form provider.
650  * @param formInfos Form infos.
651  * @return Returns ERR_OK on success, others on failure.
652  */
DumpFormInfoByBundleName(const std::string & bundleName,std::string & formInfos) const653 int FormMgrAdapter::DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) const
654 {
655     HILOG_INFO("%{public}s called.", __func__);
656     std::vector<FormRecord> formRecordInfos;
657     if (FormDataMgr::GetInstance().GetFormRecord(bundleName, formRecordInfos)) {
658         FormDumpMgr::GetInstance().DumpFormInfos(formRecordInfos, formInfos);
659         return ERR_OK;
660     } else {
661         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
662     }
663 }
664 /**
665  * @brief Dump form info by a bundle name.
666  * @param formId The id of the form.
667  * @param formInfo Form info.
668  * @return Returns ERR_OK on success, others on failure.
669  */
DumpFormInfoByFormId(const std::int64_t formId,std::string & formInfo) const670 int FormMgrAdapter::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) const
671 {
672     HILOG_INFO("%{public}s called.", __func__);
673     int reply = ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
674 
675     FormRecord formRecord;
676     if (FormDataMgr::GetInstance().GetFormRecord(formId, formRecord)) {
677         FormDumpMgr::GetInstance().DumpFormInfo(formRecord, formInfo);
678         reply = ERR_OK;
679     }
680 
681     FormHostRecord formHostRecord;
682     if (FormDataMgr::GetInstance().GetFormHostRecord(formId, formHostRecord)) {
683         FormDumpMgr::GetInstance().DumpFormHostInfo(formHostRecord, formInfo);
684         reply = ERR_OK;
685     }
686 
687     return reply;
688 }
689 /**
690  * @brief Dump form timer by form id.
691  * @param formId The id of the form.
692  * @param formInfo Form timer.
693  * @return Returns ERR_OK on success, others on failure.
694  */
DumpFormTimerByFormId(const std::int64_t formId,std::string & isTimingService) const695 int FormMgrAdapter::DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService) const
696 {
697     HILOG_INFO("%{public}s called.", __func__);
698     FormTimer formTimer;
699     UpdateAtItem updateAtItem;
700     DynamicRefreshItem dynamicItem;
701     bool result_inter = FormTimerMgr::GetInstance().GetIntervalTimer(formId, formTimer);
702     bool result_update = FormTimerMgr::GetInstance().GetUpdateAtTimer(formId, updateAtItem);
703     bool result_dynamic = FormTimerMgr::GetInstance().GetDynamicItem(formId, dynamicItem);
704     HILOG_INFO("%{public}s result_inter:%{public}d,result_update:%{public}d,result_dynamic:%{public}d",
705         __func__, result_inter, result_update, result_dynamic);
706     if (result_inter || result_update || result_dynamic) {
707         isTimingService = "true";
708     } else {
709         isTimingService = "false";
710     }
711     return ERR_OK;
712 }
713 /**
714  * @brief Get form configure info.
715  * @param want The want of the request.
716  * @param formItemInfo Form configure info.
717  * @return Returns ERR_OK on success, others on failure.
718  */
GetFormConfigInfo(const Want & want,FormItemInfo & formConfigInfo)719 ErrCode FormMgrAdapter::GetFormConfigInfo(const Want &want, FormItemInfo &formConfigInfo)
720 {
721     HILOG_DEBUG("GetFormConfigInfo start.");
722     BundleInfo bundleInfo;
723     std::string packageName;
724 
725     ErrCode errCode = GetBundleInfo(want, bundleInfo, packageName);
726     if (errCode != ERR_OK) {
727         HILOG_ERROR("addForm find bundle info failed");
728         return errCode;
729     }
730 
731     FormInfo formInfo;
732     errCode = GetFormInfo(want, formInfo);
733     if (errCode != ERR_OK) {
734         HILOG_ERROR("addForm can not find target form info");
735         return errCode;
736     }
737     if (!formInfo.IsValid()) {
738         HILOG_ERROR("The form info is invalid");
739         return ERR_APPEXECFWK_FORM_GET_INFO_FAILED;
740     }
741 
742     errCode = GetFormItemInfo(want, bundleInfo, formInfo, formConfigInfo);
743     if (errCode != ERR_OK) {
744         HILOG_ERROR("get form item info failed.");
745         return errCode;
746     }
747     formConfigInfo.SetPackageName(packageName);
748 
749     HILOG_DEBUG("GetFormConfigInfo end.");
750     return ERR_OK;
751 }
752 /**
753  * @brief Allocate form by formId.
754  * @param info Form configure info.
755  * @param callerToken Caller ability token.
756  * @param wantParams WantParams of the request.
757  * @param formInfo Form info for form host.
758  * @return Returns ERR_OK on success, others on failure.
759  */
AllotFormById(const FormItemInfo & info,const sptr<IRemoteObject> & callerToken,const WantParams & wantParams,FormJsInfo & formInfo)760 ErrCode FormMgrAdapter::AllotFormById(const FormItemInfo &info,
761     const sptr<IRemoteObject> &callerToken, const WantParams &wantParams, FormJsInfo &formInfo)
762 {
763     int64_t formId = PaddingUDIDHash(info.GetFormId());
764     FormRecord record;
765     bool hasRecord = FormDataMgr::GetInstance().GetFormRecord(formId, record);
766     if (hasRecord && record.formTempFlg) {
767         HILOG_ERROR("%{public}s, addForm can not acquire temp form when select form id", __func__);
768         return ERR_APPEXECFWK_FORM_COMMON_CODE;
769     }
770 
771     // get current userId
772     int callingUid = IPCSkeleton::GetCallingUid();
773     int32_t currentUserId = GetCurrentUserId(callingUid);
774     if (hasRecord && (record.userId == currentUserId
775         || FormDataMgr::GetInstance().IsCallingUidValid(record.formUserUids))) {
776         if (!info.IsMatch(record)) {
777             HILOG_ERROR("%{public}s, formId and item info not match:%{public}" PRId64 "", __func__, formId);
778             return ERR_APPEXECFWK_FORM_CFG_NOT_MATCH_ID;
779         }
780         return AddExistFormRecord(info, callerToken, record, formId, wantParams, formInfo);
781     }
782 
783     // find in db but not in cache
784     FormRecord dbRecord;
785     ErrCode getDbRet = FormDbCache::GetInstance().GetDBRecord(formId, dbRecord);
786     if (getDbRet == ERR_OK && (dbRecord.userId == currentUserId
787         || FormDataMgr::GetInstance().IsCallingUidValid(dbRecord.formUserUids))) {
788         return AddNewFormRecord(info, formId, callerToken, wantParams, formInfo);
789     }
790 
791     HILOG_INFO("%{public}s, addForm no such form %{public}" PRId64 "", __func__, formId);
792 
793     // delete form data in provider
794     FormRecord delRecord;
795     delRecord.bundleName = info.GetProviderBundleName();
796     delRecord.abilityName = info.GetAbilityName();
797     FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, delRecord);
798 
799     return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
800 }
PaddingUDIDHash(const int64_t formId) const801 int64_t FormMgrAdapter::PaddingUDIDHash(const int64_t formId) const
802 {
803     // Compatible with int form id.
804     uint64_t unsignedFormId = static_cast<uint64_t>(formId);
805     if ((unsignedFormId & 0xffffffff00000000L) == 0) {
806         int64_t udidHash = FormDataMgr::GetInstance().GetUdidHash();
807         uint64_t unsignUdidHash  = static_cast<uint64_t>(udidHash);
808         uint64_t unsignUdidHashFormId = unsignUdidHash | unsignedFormId;
809         int64_t udidHashFormId = static_cast<int64_t>(unsignUdidHashFormId);
810         return udidHashFormId;
811     }
812     return formId;
813 }
AddExistFormRecord(const FormItemInfo & info,const sptr<IRemoteObject> & callerToken,const FormRecord & record,const int64_t formId,const WantParams & wantParams,FormJsInfo & formInfo)814 ErrCode FormMgrAdapter::AddExistFormRecord(const FormItemInfo &info, const sptr<IRemoteObject> &callerToken,
815                                            const FormRecord &record, const int64_t formId, const WantParams &wantParams,
816                                            FormJsInfo &formInfo)
817 {
818     HILOG_INFO("%{public}s call, formId:%{public}" PRId64 "", __func__, formId);
819     // allot form host record
820     int callingUid = IPCSkeleton::GetCallingUid();
821     bool isCreated = FormDataMgr::GetInstance().AllotFormHostRecord(info, callerToken, formId, callingUid);
822     if (!isCreated) {
823         HILOG_ERROR("%{public}s fail, AllotFormHostRecord failed when no matched formRecord", __func__);
824         return ERR_APPEXECFWK_FORM_COMMON_CODE;
825     }
826 
827     FormRecord newRecord(record);
828 
829     if (newRecord.needRefresh || !FormCacheMgr::GetInstance().IsExist(newRecord.formId)) {
830         newRecord.isInited = false;
831         FormDataMgr::GetInstance().SetFormCacheInited(formId, false);
832         // acquire formInfo from provider
833         ErrCode errorCode = AcquireProviderFormInfoAsync(formId, info, wantParams);
834         if (errorCode != ERR_OK) {
835             HILOG_ERROR("%{public}s fail, AcquireProviderFormInfoAsync failed", __func__);
836             return errorCode;
837         }
838     }
839 
840     // Add new form user uid.
841     FormDataMgr::GetInstance().AddFormUserUid(formId, callingUid);
842     if (std::find(newRecord.formUserUids.begin(), newRecord.formUserUids.end(), callingUid) ==
843         newRecord.formUserUids.end()) {
844         newRecord.formUserUids.emplace_back(callingUid);
845     }
846 
847     // create form info for js
848     std::string cacheData;
849     std::map<std::string, std::pair<sptr<FormAshmem>, int32_t>> imageMap;
850     if (FormCacheMgr::GetInstance().GetData(formId, cacheData, imageMap)) {
851         formInfo.formData = cacheData;
852         formInfo.formProviderData.SetImageDataMap(imageMap);
853     }
854     FormDataMgr::GetInstance().CreateFormInfo(formId, record, formInfo);
855 
856     // start update timer
857     if (ErrCode errorCode = AddFormTimer(newRecord); errorCode != ERR_OK) {
858         return errorCode;
859     }
860 
861     if (!newRecord.formTempFlg) {
862         return FormDbCache::GetInstance().UpdateDBRecord(formId, newRecord);
863     }
864     return ERR_OK;
865 }
866 /**
867  * @brief Allocate form by form configure info.
868  * @param info Form configure info.
869  * @param callerToken Caller ability token.
870  * @param wantParams WantParams of the request.
871  * @param formInfo Form info for form host.
872  * @return Returns ERR_OK on success, others on failure.
873  */
AllotFormByInfo(const FormItemInfo & info,const sptr<IRemoteObject> & callerToken,const WantParams & wantParams,FormJsInfo & formInfo)874 ErrCode FormMgrAdapter::AllotFormByInfo(const FormItemInfo &info,
875     const sptr<IRemoteObject> &callerToken, const WantParams &wantParams, FormJsInfo &formInfo)
876 {
877     // generate formId
878     int64_t newFormId = FormDataMgr::GetInstance().GenerateFormId();
879     if (newFormId < 0) {
880         HILOG_ERROR("%{public}s fail, generateFormId no invalid formId", __func__);
881         return ERR_APPEXECFWK_FORM_COMMON_CODE;
882     }
883     HILOG_DEBUG("newFormId:%{public}" PRId64 "", newFormId);
884 
885     return AddNewFormRecord(info, newFormId, callerToken, wantParams, formInfo);
886 }
887 
888 /**
889  * @brief Add new form record.
890  * @param info Form configure info.
891  * @param formId The form id.
892  * @param callerToken Caller ability token.
893  * @param wantParams WantParams of the request.
894  * @param formInfo Form info for form host.
895  * @return Returns ERR_OK on success, others on failure.
896  */
AddNewFormRecord(const FormItemInfo & info,const int64_t formId,const sptr<IRemoteObject> & callerToken,const WantParams & wantParams,FormJsInfo & formInfo)897 ErrCode FormMgrAdapter::AddNewFormRecord(const FormItemInfo &info, const int64_t formId,
898     const sptr<IRemoteObject> &callerToken, const WantParams &wantParams, FormJsInfo &formInfo)
899 {
900     HILOG_INFO("%{public}s start", __func__);
901     FormItemInfo newInfo(info);
902     newInfo.SetFormId(formId);
903     // allot form host record
904     int callingUid = IPCSkeleton::GetCallingUid();
905     if (!FormDataMgr::GetInstance().AllotFormHostRecord(newInfo, callerToken, formId, callingUid)) {
906         HILOG_ERROR("%{public}s fail, AllotFormHostRecord failed when no matched formRecord", __func__);
907         return ERR_APPEXECFWK_FORM_COMMON_CODE;
908     }
909 
910     // get current userId
911     int32_t currentUserId = GetCurrentUserId(callingUid);
912     // allot form record
913     FormRecord formRecord = FormDataMgr::GetInstance().AllotFormRecord(newInfo, callingUid, currentUserId);
914 
915     // acquire formInfo from provider
916     if (ErrCode errorCode = AcquireProviderFormInfoAsync(formId, newInfo, wantParams); errorCode != ERR_OK) {
917         HILOG_ERROR("%{public}s fail, AcquireProviderFormInfoAsync failed", __func__);
918         return errorCode;
919     }
920 
921     // create form info for js
922     FormDataMgr::GetInstance().CreateFormInfo(formId, formRecord, formInfo);
923 
924     // storage info
925     if (!newInfo.IsTemporaryForm()) {
926         if (ErrCode errorCode = FormDbCache::GetInstance().UpdateDBRecord(formId, formRecord); errorCode != ERR_OK) {
927             HILOG_ERROR("%{public}s fail, UpdateDBRecord failed", __func__);
928             return errorCode;
929         }
930     }
931 
932     // start update timer
933     return AddFormTimer(formRecord);
934 }
935 
936 /**
937  * @brief Add form timer.
938  * @param formRecord Form information.
939  * @return Returns ERR_OK on success, others on failure.
940  */
AddFormTimer(const FormRecord & formRecord)941 ErrCode FormMgrAdapter::AddFormTimer(const FormRecord &formRecord)
942 {
943     HILOG_INFO("%{public}s start", __func__);
944     if (!formRecord.isEnableUpdate || formRecord.formTempFlg) {
945         HILOG_INFO("%{public}s isEnableUpdate:%{public}d formTempFlg:%{public}d.",
946             __func__, formRecord.isEnableUpdate, formRecord.formTempFlg);
947         return ERR_OK;
948     }
949     if (formRecord.updateDuration > 0) {
950         bool ret = FormTimerMgr::GetInstance().AddFormTimer(formRecord.formId,
951             formRecord.updateDuration, formRecord.userId);
952         return ret ? ERR_OK : ERR_APPEXECFWK_FORM_COMMON_CODE;
953     }
954     if (formRecord.updateAtHour >= 0 && formRecord.updateAtMin >= 0) {
955         bool ret = FormTimerMgr::GetInstance().AddFormTimer(formRecord.formId,
956             formRecord.updateAtHour, formRecord.updateAtMin, formRecord.userId);
957         return ret ? ERR_OK : ERR_APPEXECFWK_FORM_COMMON_CODE;
958     }
959     HILOG_INFO("%{public}s no need add form timer.", __func__);
960     return ERR_OK;
961 }
962 
963 /**
964  * @brief Send event notify to form provider. The event notify type include FORM_VISIBLE and FORM_INVISIBLE.
965  *
966  * @param providerKey The provider key string which consists of the provider bundle name and ability name.
967  * @param formIdsByProvider The vector of form Ids which have the same provider.
968  * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE.
969  * @return Returns ERR_OK on success, others on failure.
970  */
HandleEventNotify(const std::string & providerKey,const std::vector<int64_t> & formIdsByProvider,const int32_t formVisibleType)971 ErrCode FormMgrAdapter::HandleEventNotify(const std::string &providerKey, const std::vector<int64_t> &formIdsByProvider,
972     const int32_t formVisibleType)
973 {
974     HILOG_INFO("%{public}s called.", __func__);
975     size_t position = providerKey.find(Constants::NAME_DELIMITER);
976     std::string bundleName = providerKey.substr(0, position);
977     std::string abilityName = providerKey.substr(position + Constants::NAME_DELIMITER.size());
978     sptr<IAbilityConnection> formEventNotifyConnection = new FormEventNotifyConnection(formIdsByProvider,
979         formVisibleType, bundleName, abilityName);
980     Want connectWant;
981     connectWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED);
982 
983     connectWant.SetElementName(bundleName, abilityName);
984 
985     ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formEventNotifyConnection);
986     if (errorCode != ERR_OK) {
987         HILOG_ERROR("%{public}s fail, ConnectServiceAbility failed.", __func__);
988         return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED;
989     }
990 
991     return ERR_OK;
992 }
993 
994 /**
995  * @brief Acquire form data from form provider.
996  * @param formId The Id of the form.
997  * @param info Form configure info.
998  * @param wantParams WantParams of the request.
999  * @return Returns ERR_OK on success, others on failure.
1000  */
AcquireProviderFormInfoAsync(const int64_t formId,const FormItemInfo & info,const WantParams & wantParams)1001 ErrCode FormMgrAdapter::AcquireProviderFormInfoAsync(const int64_t formId,
1002     const FormItemInfo &info, const WantParams &wantParams)
1003 {
1004     if (formId <= 0) {
1005         HILOG_ERROR("%{public}s fail, formId should be greater than 0", __func__);
1006         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1007     }
1008 
1009     sptr<IAbilityConnection> formAcquireConnection
1010         = new FormAcquireConnection(formId, info, wantParams);
1011     Want want;
1012     want.SetElementName(info.GetProviderBundleName(), info.GetAbilityName());
1013     want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED);
1014     ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, formAcquireConnection);
1015     if (errorCode != ERR_OK) {
1016         HILOG_ERROR("%{public}s fail, ConnectServiceAbility failed.", __func__);
1017         return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED;
1018     }
1019     return ERR_OK;
1020 }
1021 
1022 /**
1023  * @brief Get bundle info.
1024  * @param want The want of the request.
1025  * @param bundleInfo Bundle info.
1026  * @param packageName Package name.
1027  * @return Returns ERR_OK on success, others on failure.
1028  */
GetBundleInfo(const AAFwk::Want & want,BundleInfo & bundleInfo,std::string & packageName)1029 ErrCode FormMgrAdapter::GetBundleInfo(const AAFwk::Want &want, BundleInfo &bundleInfo, std::string &packageName)
1030 {
1031     HILOG_DEBUG("GetBundleMgr start.");
1032     std::string bundleName = want.GetElement().GetBundleName();
1033     std::string abilityName = want.GetElement().GetAbilityName();
1034     std::string deviceId = want.GetElement().GetDeviceID();
1035     std::string moduleName = want.GetStringParam(Constants::PARAM_MODULE_NAME_KEY);
1036     if (bundleName.empty() || abilityName.empty() || moduleName.empty()) {
1037         HILOG_ERROR("GetBundleInfo bundleName or abilityName or moduleName is invalid");
1038         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1039     }
1040 
1041     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1042     if (iBundleMgr == nullptr) {
1043         HILOG_ERROR("GetBundleMgr, failed to get IBundleMgr.");
1044         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
1045     }
1046 
1047     if (!IN_PROCESS_CALL(iBundleMgr->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES,
1048         bundleInfo, FormUtil::GetCurrentAccountId()))) {
1049         HILOG_ERROR("GetBundleInfo, failed to get bundle info.");
1050         return ERR_APPEXECFWK_FORM_GET_INFO_FAILED;
1051     }
1052 
1053     bool moduleExist = false;
1054     for (const auto &moduleInfo : bundleInfo.moduleNames) {
1055         HILOG_DEBUG("bundleInfo.moduleNames, module name:%{public}s", moduleInfo.c_str());
1056         if (moduleInfo.compare(moduleName) == 0) {
1057             moduleExist = true;
1058             break;
1059         }
1060     }
1061     if (!moduleExist) {
1062         HILOG_ERROR("GetBundleInfo no such module, name:%{public}s", moduleName.c_str());
1063         return ERR_APPEXECFWK_FORM_NO_SUCH_MODULE;
1064     }
1065 
1066     packageName = bundleName + moduleName;
1067     HILOG_DEBUG("GetBundleMgr end.");
1068     return ERR_OK;
1069 }
1070 /**
1071  * @brief Get form info.
1072  * @param want The want of the request.
1073  * @param packageName Package name.
1074  * @param formInfo Form info.
1075  * @return Returns ERR_OK on success, others on failure.
1076  */
GetFormInfo(const AAFwk::Want & want,FormInfo & formInfo)1077 ErrCode FormMgrAdapter::GetFormInfo(const AAFwk::Want &want, FormInfo &formInfo)
1078 {
1079     HILOG_DEBUG("GetFormInfo start.");
1080     std::string bundleName = want.GetElement().GetBundleName();
1081     std::string abilityName = want.GetElement().GetAbilityName();
1082     std::string moduleName = want.GetStringParam(Constants::PARAM_MODULE_NAME_KEY);
1083     if (bundleName.empty() || abilityName.empty() || moduleName.empty()) {
1084         HILOG_ERROR("addForm bundleName or abilityName or moduleName is invalid");
1085         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1086     }
1087 
1088     std::vector<FormInfo> formInfos {};
1089     ErrCode errCode = FormInfoMgr::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos);
1090     if (errCode != ERR_OK) {
1091         HILOG_ERROR("GetFormsInfoByModule, failed to get form config info.");
1092         return ERR_APPEXECFWK_FORM_GET_INFO_FAILED;
1093     }
1094 
1095     std::string formName = want.GetStringParam(Constants::PARAM_FORM_NAME_KEY);
1096     if (formName.empty()) {
1097         for (const auto &form : formInfos) {
1098             if (form.defaultFlag) {
1099                 formInfo = form;
1100                 formInfo.moduleName = moduleName;
1101                 HILOG_DEBUG("GetFormInfo end.");
1102                 return ERR_OK;
1103             }
1104         }
1105     } else  {
1106         for (const auto &form : formInfos) {
1107             if (form.name == formName) {
1108                 formInfo = form;
1109                 formInfo.moduleName = moduleName;
1110                 HILOG_DEBUG("GetFormInfo end.");
1111                 return ERR_OK;
1112             }
1113         }
1114     }
1115     HILOG_ERROR("failed to get form info failed.");
1116     return ERR_APPEXECFWK_FORM_GET_INFO_FAILED;
1117 }
1118 /**
1119  * @brief Get form configure info.
1120  * @param want The want of the request.
1121  * @param bundleInfo Bundle info.
1122  * @param formInfo Form info.
1123  * @param formItemInfo Form configure info.
1124  * @return Returns ERR_OK on success, others on failure.
1125  */
GetFormItemInfo(const AAFwk::Want & want,const BundleInfo & bundleInfo,const FormInfo & formInfo,FormItemInfo & formItemInfo)1126 ErrCode FormMgrAdapter::GetFormItemInfo(const AAFwk::Want &want, const BundleInfo &bundleInfo,
1127     const FormInfo &formInfo, FormItemInfo &formItemInfo)
1128 {
1129     HILOG_DEBUG("GetFormItemInfo start.");
1130     int32_t dimensionId = want.GetIntParam(Constants::PARAM_FORM_DIMENSION_KEY, formInfo.defaultDimension);
1131     if (!IsDimensionValid(formInfo, dimensionId)) {
1132         HILOG_ERROR("addForm, dimension is not valid");
1133         return ERR_APPEXECFWK_FORM_NO_SUCH_DIMENSION;
1134     }
1135 
1136     if (ErrCode ret = CreateFormItemInfo(bundleInfo, formInfo, formItemInfo); ret != ERR_OK) {
1137         return ret;
1138     }
1139     formItemInfo.SetSpecificationId(dimensionId);
1140     formItemInfo.SetTemporaryFlag(want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false));
1141 
1142     HILOG_DEBUG("GetFormItemInfo end.");
1143     return ERR_OK;
1144 }
1145 /**
1146  * @brief Dimension valid check.
1147  * @param formInfo Form info.
1148  * @param dimensionId Dimension id.
1149  * @return Returns true on success, false on failure.
1150  */
IsDimensionValid(const FormInfo & formInfo,int dimensionId) const1151 bool FormMgrAdapter::IsDimensionValid(const FormInfo &formInfo, int dimensionId) const
1152 {
1153     if (formInfo.supportDimensions.empty()) {
1154         HILOG_ERROR("Js form, no support dimension.");
1155         return false;
1156     }
1157 
1158     for (size_t i = 0; i < formInfo.supportDimensions.size() && i < Constants::MAX_LAYOUT; i++) {
1159         int supportDimensionId = formInfo.supportDimensions[i];
1160         if (supportDimensionId == dimensionId) {
1161             return true;
1162         }
1163     }
1164 
1165     HILOG_ERROR("No matched dimension found.");
1166     return false;
1167 }
1168 /**
1169  * @brief Create form configure info.
1170  * @param bundleInfo Bundle info.
1171  * @param formInfo Form info.
1172  * @param itemInfo Form configure info.
1173  */
CreateFormItemInfo(const BundleInfo & bundleInfo,const FormInfo & formInfo,FormItemInfo & itemInfo)1174 ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo,
1175     const FormInfo &formInfo, FormItemInfo &itemInfo)
1176 {
1177     itemInfo.SetProviderBundleName(bundleInfo.name);
1178     itemInfo.SetVersionCode(bundleInfo.versionCode);
1179     itemInfo.SetVersionName(bundleInfo.versionName);
1180     itemInfo.SetCompatibleVersion(bundleInfo.compatibleVersion);
1181 
1182     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1183     if (iBundleMgr == nullptr) {
1184         HILOG_ERROR("GetFormInfo, failed to get IBundleMgr.");
1185         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
1186     }
1187     std::string hostBundleName {};
1188     auto callingUid = IPCSkeleton::GetCallingUid();
1189     if (!IN_PROCESS_CALL(iBundleMgr->GetBundleNameForUid(callingUid, hostBundleName))) {
1190         HILOG_ERROR("GetFormsInfoByModule, failed to get form config info.");
1191         return ERR_APPEXECFWK_FORM_GET_INFO_FAILED;
1192     }
1193     itemInfo.SetHostBundleName(hostBundleName);
1194     std::string icon = iBundleMgr->GetAbilityIcon(bundleInfo.name, formInfo.abilityName);
1195     itemInfo.SetIcon(icon);
1196 
1197     itemInfo.SetAbilityName(formInfo.abilityName);
1198     itemInfo.SetModuleName(formInfo.moduleName); // formInfo.moduleName: bundleMagr do not set
1199     itemInfo.SetFormName(formInfo.name);
1200     itemInfo.SetEnableUpdateFlag(formInfo.updateEnabled);
1201     itemInfo.SetUpdateDuration(formInfo.updateDuration);
1202     itemInfo.SetScheduledUpdateTime(formInfo.scheduledUpdateTime);
1203     itemInfo.SetJsComponentName(formInfo.jsComponentName);
1204     itemInfo.SetFormVisibleNotify(formInfo.formVisibleNotify);
1205     itemInfo.SetFormSrc(formInfo.src);
1206     itemInfo.SetFormWindow(formInfo.window);
1207 
1208     for (const auto &abilityInfo : bundleInfo.abilityInfos) {
1209         if (abilityInfo.name == formInfo.abilityName) {
1210             itemInfo.SetAbilityModuleName(abilityInfo.moduleName);
1211             if (!abilityInfo.isModuleJson) {
1212                 itemInfo.SetFormSrc("");
1213             }
1214         }
1215     }
1216 
1217     HILOG_INFO("%{public}s moduleInfos size: %{public}zu", __func__, bundleInfo.applicationInfo.moduleInfos.size());
1218     for (const auto &item : bundleInfo.applicationInfo.moduleInfos) {
1219         HILOG_INFO("%{public}s moduleInfos,  moduleName: %{public}s, moduleSourceDir: %{public}s", __func__,
1220             item.moduleName.c_str(), item.moduleSourceDir.c_str());
1221         if (formInfo.moduleName == item.moduleName) {
1222             itemInfo.AddHapSourceDirs(item.moduleSourceDir);
1223         }
1224         auto moduleSourceDir = std::regex_replace(item.moduleSourceDir, std::regex(Constants::ABS_CODE_PATH),
1225             Constants::LOCAL_BUNDLES);
1226         itemInfo.AddModuleInfo(item.moduleName, moduleSourceDir);
1227     }
1228     return ERR_OK;
1229 }
1230 
1231 /**
1232  * @brief set next refresh time.
1233  * @param formId The id of the form.
1234  * @param nextTime next refresh time.
1235  * @return Returns ERR_OK on success, others on failure.
1236  */
SetNextRefreshTime(const int64_t formId,const int64_t nextTime)1237 int FormMgrAdapter::SetNextRefreshTime(const int64_t formId, const int64_t nextTime)
1238 {
1239     HILOG_INFO(
1240         "%{public}s begin here, formId:%{public}" PRId64 ",nextTime:%{public}" PRId64 "", __func__, formId, nextTime);
1241     if (formId <= 0) {
1242         HILOG_ERROR("%{public}s form formId or bundleName is invalid", __func__);
1243         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1244     }
1245 
1246     std::string bundleName;
1247     if (!GetBundleName(bundleName)) {
1248         return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED;
1249     }
1250 
1251     // get IBundleMgr
1252     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1253     if (iBundleMgr == nullptr) {
1254         HILOG_ERROR("%{public}s error, failed to get IBundleMgr.", __func__);
1255         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
1256     }
1257 
1258     int callingUid = IPCSkeleton::GetCallingUid();
1259     int32_t userId = GetCurrentUserId(callingUid);
1260     HILOG_INFO("%{public}s, userId:%{public}d, callingUid:%{public}d.", __func__, userId, callingUid);
1261 
1262     int32_t bundleUid = IN_PROCESS_CALL(iBundleMgr->GetUidByBundleName(bundleName, userId));
1263     if (bundleUid != callingUid) {
1264         HILOG_ERROR("%{public}s error, permission denied, the form is not your own.", __func__);
1265         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1266     }
1267 
1268     FormRecord formRecord;
1269     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
1270     if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) {
1271         HILOG_ERROR("%{public}s, not found in formrecord.", __func__);
1272         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
1273     }
1274 
1275     bool isSelfFormId = (userId == formRecord.userId);
1276     if (!isSelfFormId) {
1277         HILOG_ERROR("%{public}s, not self form:%{public}" PRId64 "", __func__, formId);
1278         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
1279     }
1280 
1281     // check bundleName
1282     if (bundleName != formRecord.bundleName) {
1283         HILOG_ERROR("%{public}s, not match bundleName:%{public}s", __func__, bundleName.c_str());
1284         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
1285     }
1286 
1287     return SetNextRefreshtTimeLocked(matchedFormId, nextTime, userId);
1288 }
1289 
1290 /**
1291  * @brief get bundleName.
1292  * @param bundleName for output.
1293  * @return Returns true on success, others on failure.
1294  */
GetBundleName(std::string & bundleName)1295 bool FormMgrAdapter::GetBundleName(std::string &bundleName)
1296 {
1297     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1298     if (iBundleMgr == nullptr) {
1299         HILOG_ERROR("%{public}s, failed to get IBundleMgr.", __func__);
1300         return false;
1301     }
1302 
1303     int uid = IPCSkeleton::GetCallingUid();
1304     if (!IN_PROCESS_CALL(iBundleMgr->CheckIsSystemAppByUid(uid))) {
1305         HILOG_ERROR("%{public}s fail, form is not system app. uid:%{public}d", __func__, uid);
1306         return false;
1307     }
1308 
1309     bool result = IN_PROCESS_CALL(iBundleMgr->GetBundleNameForUid(uid, bundleName));
1310     if (!result || bundleName.empty()) {
1311         HILOG_ERROR("%{public}s failed, cannot get bundle name by uid:%{public}d", __func__, uid);
1312         return false;
1313     }
1314     return true;
1315 }
1316 
1317 /**
1318  * @brief set next refresht time locked.
1319  * @param formId The form's id.
1320  * @param nextTime next refresh time.
1321  * @param userId User ID.
1322  * @return Returns ERR_OK on success, others on failure.
1323  */
SetNextRefreshtTimeLocked(const int64_t formId,const int64_t nextTime,const int32_t userId)1324 int FormMgrAdapter::SetNextRefreshtTimeLocked(const int64_t formId, const int64_t nextTime, const int32_t userId)
1325 {
1326     HILOG_ERROR("SetNextRefreshtTimeLocked.");
1327     int32_t timerRefreshedCount = FormTimerMgr::GetInstance().GetRefreshCount(formId);
1328     if (timerRefreshedCount >= Constants::LIMIT_COUNT) {
1329         HILOG_ERROR("%{public}s, already refresh times:%{public}d", __func__, timerRefreshedCount);
1330         FormTimerMgr::GetInstance().MarkRemind(formId);
1331         return ERR_APPEXECFWK_FORM_MAX_REFRESH;
1332     }
1333 
1334     if (!FormTimerMgr::GetInstance().SetNextRefreshTime(formId, nextTime * Constants::SEC_PER_MIN, userId)) {
1335         HILOG_ERROR("%{public}s failed", __func__);
1336         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1337     }
1338 
1339     return ERR_OK;
1340 }
1341 
1342 /**
1343  * @brief set next refresht time locked.
1344  * @param formId The form's id.
1345  * @param bundleName Provider ability bundleName.
1346  * @return Returns true or false.
1347  */
IsUpdateValid(const int64_t formId,const std::string & bundleName)1348 bool FormMgrAdapter::IsUpdateValid(const int64_t formId, const std::string &bundleName)
1349 {
1350     if (formId <= 0 || bundleName.empty()) {
1351         return false;
1352     }
1353     return true;
1354 }
1355 
1356 /**
1357  * @brief enable update form.
1358  * @param formIDs The id of the forms.
1359  * @param callerToken Caller ability token.
1360  * @return Returns ERR_OK on success, others on failure.
1361  */
EnableUpdateForm(const std::vector<int64_t> formIDs,const sptr<IRemoteObject> & callerToken)1362 int FormMgrAdapter::EnableUpdateForm(const std::vector<int64_t> formIDs, const sptr<IRemoteObject> &callerToken)
1363 {
1364     HILOG_INFO("enableUpdateForm");
1365     return HandleUpdateFormFlag(formIDs, callerToken, true, false);
1366 }
1367 
1368 /**
1369  * @brief disable update form.
1370  * @param formIDs The id of the forms.
1371  * @param callerToken Caller ability token.
1372  * @return Returns ERR_OK on success, others on failure.
1373  */
DisableUpdateForm(const std::vector<int64_t> formIDs,const sptr<IRemoteObject> & callerToken)1374 int FormMgrAdapter::DisableUpdateForm(const std::vector<int64_t> formIDs, const sptr<IRemoteObject> &callerToken)
1375 {
1376     HILOG_INFO("disableUpdateForm");
1377     return HandleUpdateFormFlag(formIDs, callerToken, false, false);
1378 }
1379 
1380 /**
1381  * @brief Process js message event.
1382  * @param formId Indicates the unique id of form.
1383  * @param want information passed to supplier.
1384  * @param callerToken Caller ability token.
1385  * @return Returns true if execute success, false otherwise.
1386  */
MessageEvent(const int64_t formId,const Want & want,const sptr<IRemoteObject> & callerToken)1387 int FormMgrAdapter::MessageEvent(const int64_t formId, const Want &want, const sptr<IRemoteObject> &callerToken)
1388 {
1389     HILOG_INFO("%{public}s called.", __func__);
1390     if (formId <= 0) {
1391         HILOG_ERROR("%{public}s form formId or bundleName is invalid", __func__);
1392         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1393     }
1394 
1395     if (callerToken == nullptr) {
1396         HILOG_ERROR("%{public}s failed, callerToken can not be NULL", __func__);
1397         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1398     }
1399 
1400     if (!want.HasParameter(Constants::PARAM_MESSAGE_KEY)) {
1401         HILOG_ERROR("%{public}s failed, message info is not exist", __func__);
1402         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1403     }
1404 
1405     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
1406     FormRecord record;
1407     bool bGetRecord = FormDataMgr::GetInstance().GetFormRecord(matchedFormId, record);
1408     if (!bGetRecord) {
1409         HILOG_ERROR("%{public}s fail, not exist such form:%{public}" PRId64 "", __func__, matchedFormId);
1410         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
1411     }
1412 
1413     FormHostRecord formHostRecord;
1414     bool isHostExist = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord);
1415     if (!isHostExist) {
1416         HILOG_ERROR("%{public}s failed, cannot find target client.", __func__);
1417         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1418     }
1419 
1420     if (!formHostRecord.Contains(matchedFormId)) {
1421         HILOG_ERROR("%{public}s failed, form is not self-owned.", __func__);
1422         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
1423     }
1424 
1425     HILOG_INFO("%{public}s, find target client.", __func__);
1426     return FormProviderMgr::GetInstance().MessageEvent(matchedFormId, record, want);
1427 }
1428 
1429 
1430 /**
1431  * @brief Process js router event.
1432  * @param formId Indicates the unique id of form.
1433  * @param want the want of the ability to start.
1434  * @return Returns true if execute success, false otherwise.
1435  */
RouterEvent(const int64_t formId,Want & want)1436 int FormMgrAdapter::RouterEvent(const int64_t formId, Want &want)
1437 {
1438     HILOG_INFO("%{public}s called.", __func__);
1439     if (formId <= 0) {
1440         HILOG_ERROR("%{public}s form formId or bundleName is invalid", __func__);
1441         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1442     }
1443 
1444     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
1445     FormRecord record;
1446     bool bGetRecord = FormDataMgr::GetInstance().GetFormRecord(matchedFormId, record);
1447     if (!bGetRecord) {
1448         HILOG_ERROR("%{public}s fail, not exist such form:%{public}" PRId64 "", __func__, matchedFormId);
1449         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
1450     }
1451 
1452     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1453     if (iBundleMgr == nullptr) {
1454         HILOG_ERROR("%{public}s fail, failed to get IBundleMgr.", __func__);
1455         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
1456     }
1457 
1458     if (record.bundleName != want.GetBundle()) {
1459         if (!CheckIsSystemAppByBundleName(iBundleMgr, record.bundleName)) {
1460             HILOG_WARN("Only system apps can launch the ability of the other apps.");
1461             want.SetBundle(record.bundleName);
1462         }
1463     }
1464 
1465     int32_t result = FormAmsHelper::GetInstance().GetAbilityManager()->StartAbility(want);
1466     if (result != ERR_OK && result != START_ABILITY_WAITING) {
1467         HILOG_ERROR("Failed to StartAbility, result: %{public}d.", result);
1468         return result;
1469     }
1470 
1471     return ERR_OK;
1472 }
1473 
HandleUpdateFormFlag(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,bool flag,bool isOnlyEnableUpdate)1474 ErrCode FormMgrAdapter::HandleUpdateFormFlag(const std::vector<int64_t> &formIds,
1475                                              const sptr<IRemoteObject> &callerToken, bool flag, bool isOnlyEnableUpdate)
1476 {
1477     HILOG_INFO("%{public}s called.", __func__);
1478     if (formIds.empty() || callerToken == nullptr) {
1479         HILOG_ERROR("%{public}s, invalid param", __func__);
1480         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1481     }
1482     std::vector<int64_t> refreshForms;
1483     int errCode = FormDataMgr::GetInstance().UpdateHostFormFlag(formIds, callerToken, flag, isOnlyEnableUpdate,
1484         refreshForms);
1485     if (errCode == ERR_OK && !refreshForms.empty()) {
1486         for (const int64_t id : refreshForms) {
1487             HILOG_INFO("%{public}s, formRecord need refresh: %{public}" PRId64 "", __func__, id);
1488             Want want;
1489             int callingUid = IPCSkeleton::GetCallingUid();
1490             int32_t userId = GetCurrentUserId(callingUid);
1491             want.SetParam(Constants::PARAM_FORM_USER_ID, userId);
1492             FormProviderMgr::GetInstance().RefreshForm(id, want, false);
1493         }
1494     }
1495     return errCode;
1496 }
1497 
1498 /**
1499  * @brief handle update form flag.
1500  * @param formIDs The id of the forms.
1501  * @param callerToken Caller ability token.
1502  * @param flag form flag.
1503  * @return Returns true on success, false on failure.
1504  */
IsFormCached(const FormRecord record)1505 bool FormMgrAdapter::IsFormCached(const FormRecord record)
1506 {
1507     if (record.versionUpgrade) {
1508         return false;
1509     }
1510     return true;
1511 }
1512 
1513 /**
1514  * @brief Acquire form data from form provider.
1515  * @param formId The Id of the from.
1516  * @param want The want of the request.
1517  * @param remoteObject Form provider proxy object.
1518  */
AcquireProviderFormInfo(const int64_t formId,const Want & want,const sptr<IRemoteObject> & remoteObject)1519 void FormMgrAdapter::AcquireProviderFormInfo(const int64_t formId, const Want &want,
1520     const sptr<IRemoteObject> &remoteObject)
1521 {
1522     HILOG_INFO("%{public}s called.", __func__);
1523 
1524     long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0);
1525     sptr<IFormProvider> formProviderProxy = iface_cast<IFormProvider>(remoteObject);
1526     if (formProviderProxy == nullptr) {
1527         FormSupplyCallback::GetInstance()->RemoveConnection(connectId);
1528         HILOG_ERROR("%{public}s fail, Failed to get formProviderProxy", __func__);
1529         return;
1530     }
1531 
1532     int error = formProviderProxy->AcquireProviderFormInfo(formId, want, FormSupplyCallback::GetInstance());
1533     if (error != ERR_OK) {
1534         FormSupplyCallback::GetInstance()->RemoveConnection(connectId);
1535         HILOG_ERROR("%{public}s fail, Failed to get acquire provider form info", __func__);
1536     }
1537 }
1538 
1539 /**
1540  * @brief Notify form provider for delete form.
1541  *
1542  * @param formId The Id of the from.
1543  * @param want The want of the form.
1544  * @param remoteObject Form provider proxy object.
1545  * @return none.
1546  */
NotifyFormDelete(const int64_t formId,const Want & want,const sptr<IRemoteObject> & remoteObject)1547 void FormMgrAdapter::NotifyFormDelete(const int64_t formId, const Want &want, const sptr<IRemoteObject> &remoteObject)
1548 {
1549     HILOG_INFO("%{public}s called.", __func__);
1550 
1551     long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0);
1552     sptr<IFormProvider> formProviderProxy = iface_cast<IFormProvider>(remoteObject);
1553     if (formProviderProxy == nullptr) {
1554         FormSupplyCallback::GetInstance()->RemoveConnection(connectId);
1555         HILOG_ERROR("%{public}s fail, Failed to get formProviderProxy", __func__);
1556         return;
1557     }
1558     int error = formProviderProxy->NotifyFormDelete(formId, want, FormSupplyCallback::GetInstance());
1559     if (error != ERR_OK) {
1560         FormSupplyCallback::GetInstance()->RemoveConnection(connectId);
1561         HILOG_ERROR("%{public}s fail, Failed to get acquire provider form info", __func__);
1562     }
1563 }
1564 
1565 /**
1566  * @brief Batch add forms to form records for st limit value test.
1567  * @param want The want of the form to add.
1568  * @return Returns forms count to add.
1569  */
BatchAddFormRecords(const Want & want)1570 int FormMgrAdapter::BatchAddFormRecords(const Want &want)
1571 {
1572     HILOG_INFO("%{public}s called.", __func__);
1573     ElementName elementName = want.GetElement();
1574     std::string bundleName = elementName.GetBundleName();
1575     std::string abilityName = elementName.GetAbilityName();
1576     int formCount = want.GetIntParam(Constants::PARAM_FORM_ADD_COUNT, 0);
1577     HILOG_INFO("%{public}s, batch add form, bundleName: %{public}s, abilityName: %{public}s, count: %{public}d.",
1578         __func__,
1579         bundleName.c_str(),
1580         abilityName.c_str(),
1581         formCount);
1582 
1583     for (int count = 0; count < formCount; count++) {
1584         // get from comfig info
1585         FormItemInfo formItemInfo;
1586         int32_t errCode = GetFormConfigInfo(want, formItemInfo);
1587         if (errCode != ERR_OK) {
1588             HILOG_ERROR("%{public}s fail, get form config info failed.", __func__);
1589             return errCode;
1590         }
1591         if (!formItemInfo.IsValidItem()) {
1592             HILOG_ERROR("%{public}s fail, input param itemInfo is invalid", __func__);
1593             return ERR_APPEXECFWK_FORM_GET_INFO_FAILED;
1594         }
1595         if (!FormDataMgr::GetInstance().GenerateUdidHash()) {
1596             HILOG_ERROR("%{public}s fail, generate udid hash failed", __func__);
1597             return ERR_APPEXECFWK_FORM_COMMON_CODE;
1598         }
1599 
1600         // generate formId
1601         int64_t newFormId = FormDataMgr::GetInstance().GenerateFormId();
1602         if (newFormId < 0) {
1603             HILOG_ERROR("%{public}s fail, generateFormId no invalid formId", __func__);
1604             return ERR_APPEXECFWK_FORM_COMMON_CODE;
1605         }
1606 
1607         formItemInfo.SetFormId(newFormId);
1608         // allot form host record
1609         int callingUid = IPCSkeleton::GetCallingUid();
1610         int32_t currentUserId = GetCurrentUserId(callingUid);
1611         // allot form record
1612         FormRecord formRecord = FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid, currentUserId);
1613         HILOG_INFO("%{public}s, batch add form, formId:" "%{public}" PRId64 ".", __func__, formRecord.formId);
1614 
1615         HILOG_INFO("%{public}s, count: %{public}d", __func__, count + 1);
1616     }
1617     HILOG_INFO("%{public}s end.", __func__);
1618     return ERR_OK;
1619 }
1620 /**
1621  * @brief Clear form records for st limit value test.
1622  * @return Returns forms count to delete.
1623  */
ClearFormRecords()1624 int FormMgrAdapter::ClearFormRecords()
1625 {
1626     HILOG_INFO("%{public}s called.", __func__);
1627     FormDataMgr::GetInstance().ClearFormRecords();
1628     HILOG_INFO("%{public}s end.", __func__);
1629     return ERR_OK;
1630 }
1631 /**
1632  * @brief Create eventMaps for event notify.
1633  *
1634  * @param matchedFormId The Id of the form
1635  * @param formRecord Form storage information
1636  * @param eventMaps eventMaps for event notify
1637  * @return Returns true on success, false on failure.
1638  */
CreateHandleEventMap(const int64_t matchedFormId,const FormRecord & formRecord,std::map<std::string,std::vector<int64_t>> & eventMaps)1639 bool FormMgrAdapter::CreateHandleEventMap(const int64_t matchedFormId, const FormRecord &formRecord,
1640     std::map<std::string, std::vector<int64_t>> &eventMaps)
1641 {
1642     if (!formRecord.formVisibleNotify) {
1643         HILOG_WARN("%{public}s fail, the config item 'formVisibleNotify' is false, formId:%{public}" PRId64 ".",
1644             __func__, matchedFormId);
1645         return false;
1646     }
1647 
1648     std::string providerKey = formRecord.bundleName + Constants::NAME_DELIMITER + formRecord.abilityName;
1649     auto iter = eventMaps.find(providerKey);
1650     if (iter == eventMaps.end()) {
1651         std::vector<int64_t> formEventsByProvider {matchedFormId};
1652         eventMaps.insert(std::make_pair(providerKey, formEventsByProvider));
1653     } else {
1654         iter->second.emplace_back(matchedFormId);
1655     }
1656     return true;
1657 }
1658 /**
1659  * @brief Update provider info to host
1660  *
1661  * @param matchedFormId The Id of the form
1662  * @param callerToken Caller ability token.
1663  * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE.
1664  * @param formRecord Form storage information
1665  * @return Returns true on success, false on failure.
1666  */
UpdateProviderInfoToHost(const int64_t matchedFormId,const sptr<IRemoteObject> & callerToken,const int32_t formVisibleType,FormRecord & formRecord)1667 bool FormMgrAdapter::UpdateProviderInfoToHost(const int64_t matchedFormId, const sptr<IRemoteObject> &callerToken,
1668     const int32_t formVisibleType, FormRecord &formRecord)
1669 {
1670     if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) {
1671         HILOG_WARN("%{public}s fail, not exist such form, formId:%{public}" PRId64 ".", __func__, matchedFormId);
1672         return false;
1673     }
1674 
1675     FormHostRecord formHostRecord;
1676     bool hasFormHostRecord = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord);
1677     if (!(hasFormHostRecord && formHostRecord.Contains(matchedFormId))) {
1678         HILOG_WARN("%{public}s fail, form is not belong to self, formId:%{public}" PRId64 ".", __func__, matchedFormId);
1679         return false;
1680     }
1681 
1682     formRecord.formVisibleNotifyState = formVisibleType;
1683     if (!FormDataMgr::GetInstance().UpdateFormRecord(matchedFormId, formRecord)) {
1684         HILOG_WARN("%{public}s fail, set formVisibleNotifyState error, formId:%{public}" PRId64 ".",
1685         __func__, matchedFormId);
1686         return false;
1687     }
1688 
1689     // If the form need refrsh flag is true and form visibleType is FORM_VISIBLE, refresh the form host.
1690     if (formRecord.needRefresh && formVisibleType == Constants::FORM_VISIBLE) {
1691         std::string cacheData;
1692         std::map<std::string, std::pair<sptr<FormAshmem>, int32_t>> imageMap;
1693         // If the form has business cache, refresh the form host.
1694         if (FormCacheMgr::GetInstance().GetData(matchedFormId, cacheData, imageMap)) {
1695             formRecord.formProviderInfo.SetFormDataString(cacheData);
1696             formRecord.formProviderInfo.SetImageDataMap(imageMap);
1697             formHostRecord.OnUpdate(matchedFormId, formRecord);
1698         }
1699     }
1700     return true;
1701 }
1702 /**
1703  * @brief If the form provider is system app and the config item 'formVisibleNotify' is true,
1704  *        notify the form provider that the current form is visible.
1705  *
1706  * @param bundleName BundleName
1707  * @return Returns true if the form provider is system app, false if not.
1708  */
CheckIsSystemAppByBundleName(const sptr<IBundleMgr> & iBundleMgr,const std::string & bundleName)1709 bool FormMgrAdapter::CheckIsSystemAppByBundleName(const sptr<IBundleMgr> &iBundleMgr, const std::string &bundleName)
1710 {
1711     BundleInfo bundleInfo;
1712     if (IN_PROCESS_CALL(iBundleMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT,
1713         bundleInfo, FormUtil::GetCurrentAccountId()))) {
1714         HILOG_DEBUG("%{public}s, get bundle uid success", __func__);
1715         if (!IN_PROCESS_CALL(iBundleMgr->CheckIsSystemAppByUid(bundleInfo.uid))) {
1716             HILOG_WARN("%{public}s fail, form provider is not system app, bundleName: %{public}s",
1717                 __func__, bundleName.c_str());
1718             return false;
1719         }
1720     } else {
1721         HILOG_WARN("%{public}s fail, can not get bundleInfo's uid", __func__);
1722         return false;
1723     }
1724 
1725     return true;
1726 }
1727 
1728 /**
1729  * @brief  Add forms to storage for st .
1730  * @param Want The Want of the form to add.
1731  * @return Returns ERR_OK on success, others on failure.
1732  */
DistributedDataAddForm(const Want & want)1733 int FormMgrAdapter::DistributedDataAddForm(const Want &want)
1734 {
1735     HILOG_INFO("%{public}s called.", __func__);
1736 
1737     FormDBInfo formDBInfo;
1738     ElementName elementName = want.GetElement();
1739     formDBInfo.formId = want.GetIntParam(Constants::PARAM_FORM_ADD_COUNT, 0);
1740     formDBInfo.formName = want.GetStringParam(Constants::PARAM_FORM_NAME_KEY);
1741     formDBInfo.bundleName = elementName.GetBundleName();
1742     formDBInfo.moduleName = want.GetStringParam(Constants::PARAM_MODULE_NAME_KEY);
1743     formDBInfo.abilityName = elementName.GetAbilityName();
1744     formDBInfo.formUserUids.push_back(HUNDRED);
1745     return FormDbCache::GetInstance().SaveFormInfo(formDBInfo);
1746 }
1747 
1748 /**
1749  * @brief  Delete form form storage for st.
1750  * @param formId The formId of the form to delete.
1751  * @return Returns ERR_OK on success, others on failure.
1752  */
DistributedDataDeleteForm(const std::string & formId)1753 int FormMgrAdapter::DistributedDataDeleteForm(const std::string &formId)
1754 {
1755     return FormDbCache::GetInstance().DeleteFormInfo(std::stoll(formId));
1756 }
1757 /**
1758  * @brief Get current user ID.
1759  * @param callingUid calling Uid.
1760  * @return Returns user ID.
1761  */
GetCurrentUserId(const int callingUid)1762 int32_t FormMgrAdapter::GetCurrentUserId(const int callingUid)
1763 {
1764     // get current userId
1765     int32_t userId = callingUid / UID_CALLINGUID_TRANSFORM_DIVISOR;
1766     return userId;
1767 }
1768 
1769 /**
1770  * @brief Delete the invalid forms.
1771  * @param formIds Indicates the ID of the valid forms.
1772  * @param callerToken Caller ability token.
1773  * @param numFormsDeleted Returns the number of the deleted forms.
1774  * @return Returns ERR_OK on success, others on failure.
1775  */
DeleteInvalidForms(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,int32_t & numFormsDeleted)1776 int FormMgrAdapter::DeleteInvalidForms(const std::vector<int64_t> &formIds, const sptr<IRemoteObject> &callerToken,
1777                                        int32_t &numFormsDeleted)
1778 {
1779     HILOG_INFO("%{public}s called.", __func__);
1780     if (callerToken == nullptr) {
1781         HILOG_ERROR("%{public}s, deleteForm invalid param", __func__);
1782         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1783     }
1784 
1785     std::set<int64_t> matchedFormIds {};
1786     for (int64_t formId: formIds) {
1787         int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
1788         matchedFormIds.emplace(matchedFormId);
1789         HILOG_DEBUG("valid formId, matchedFormIds: %{public}" PRId64 "", formId);
1790     }
1791     int32_t callingUid = IPCSkeleton::GetCallingUid();
1792 
1793     std::map<int64_t, bool> removedFormsMap {};
1794     int32_t userId = GetCurrentUserId(callingUid);
1795 
1796     // delete invalid DB form record
1797     FormDbCache::GetInstance().DeleteInvalidDBForms(userId, callingUid, matchedFormIds, removedFormsMap);
1798     // delete invalid temp form record
1799     FormDataMgr::GetInstance().DeleteInvalidTempForms(userId, callingUid, matchedFormIds, removedFormsMap);
1800 
1801     if (!removedFormsMap.empty()) {
1802         FormDataMgr::GetInstance().ClearHostDataByInvalidForms(callingUid, removedFormsMap);
1803         // delete forms timer
1804         for (const auto &removedForm: removedFormsMap) {
1805             if (removedForm.second) {
1806                 FormTimerMgr::GetInstance().RemoveFormTimer(removedForm.first);
1807             }
1808         }
1809     }
1810 
1811     numFormsDeleted = (int32_t) removedFormsMap.size();
1812     HILOG_INFO("%{public}s done, %{public}d forms deleted.", __func__, numFormsDeleted);
1813     return ERR_OK;
1814 }
1815 
1816 /**
1817  * @brief AcquireFormState want check.
1818  * @param bundleName The bundle name of the form.
1819  * @param abilityName The ability name of the form.
1820  * @param want The want of the form.
1821  * @param provider the provider info.
1822  * @return Returns ERR_OK on success, others on failure.
1823  */
AcquireFormStateCheck(const std::string & bundleName,const std::string & abilityName,const Want & want,std::string & provider)1824 ErrCode FormMgrAdapter::AcquireFormStateCheck(const std::string &bundleName, const std::string &abilityName,
1825                                               const Want &want, std::string &provider)
1826 {
1827     if (bundleName.empty()) {
1828         HILOG_ERROR("%{public}s error, bundleName is empty.", __func__);
1829         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1830     }
1831     if (abilityName.empty()) {
1832         HILOG_ERROR("%{public}s error, abilityName is empty.", __func__);
1833         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1834     }
1835 
1836     std::string moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
1837     std::string formName = want.GetStringParam(AppExecFwk::Constants::PARAM_FORM_NAME_KEY);
1838     int32_t dimensionId = want.GetIntParam(AppExecFwk::Constants::PARAM_FORM_DIMENSION_KEY, 1);
1839 
1840     if (moduleName.empty()) {
1841         HILOG_ERROR("%{public}s error, moduleName is empty.", __func__);
1842         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1843     }
1844     if (formName.empty()) {
1845         HILOG_ERROR("%{public}s error, formName is empty.", __func__);
1846         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1847     }
1848 
1849     std::vector<FormInfo> formInfos {};
1850     ErrCode errCode = FormInfoMgr::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos);
1851     if (errCode != ERR_OK) {
1852         HILOG_ERROR("%{public}s error, failed to get forms info.", __func__);
1853         return errCode;
1854     }
1855 
1856     bool found = false;
1857     for (auto &formInfo: formInfos) {
1858         if ((formInfo.abilityName == abilityName) && (formInfo.name == formName) &&
1859             (IsDimensionValid(formInfo, dimensionId))) {
1860             found = true;
1861             HILOG_INFO("%{public}s form info found.", __func__);
1862             break;
1863         }
1864     }
1865     if (!found) {
1866         HILOG_INFO("failed to find match form info.");
1867         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1868     }
1869 
1870     int32_t callingUid = IPCSkeleton::GetCallingUid();
1871     const std::string doubleColon = "::";
1872     provider.append(bundleName).append(doubleColon).append(abilityName).append(doubleColon)
1873         .append(moduleName).append(doubleColon).append(formName).append(doubleColon)
1874         .append(std::to_string(dimensionId)).append(doubleColon).append(std::to_string(callingUid));
1875     return ERR_OK;
1876 }
1877 
1878 /**
1879  * @brief Acquire form state info by passing a set of parameters (using Want) to the form provider.
1880  * @param want Indicates a set of parameters to be transparently passed to the form provider.
1881  * @param callerToken Caller ability token.
1882  * @param stateInfo Returns the form's state info of the specify.
1883  * @return Returns ERR_OK on success, others on failure.
1884  */
AcquireFormState(const Want & want,const sptr<IRemoteObject> & callerToken,FormStateInfo & stateInfo)1885 int FormMgrAdapter::AcquireFormState(const Want &want, const sptr<IRemoteObject> &callerToken,
1886                                      FormStateInfo &stateInfo)
1887 {
1888     if (callerToken == nullptr) {
1889         HILOG_ERROR("%{public}s, deleteForm invalid param", __func__);
1890         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1891     }
1892     std::string bundleName = want.GetElement().GetBundleName();
1893     std::string abilityName = want.GetElement().GetAbilityName();
1894 
1895     std::string provider;
1896     ErrCode errCode = AcquireFormStateCheck(bundleName, abilityName, want, provider);
1897     if (errCode != ERR_OK) {
1898         return errCode;
1899     }
1900 
1901     int32_t callingUid = IPCSkeleton::GetCallingUid();
1902     FormItemInfo info;
1903     FormDataMgr::GetInstance().CreateFormStateRecord(provider, info, callerToken, callingUid);
1904 
1905     HILOG_DEBUG("bundleName:%{public}s, abilityName:%{public}s", bundleName.c_str(), abilityName.c_str());
1906     sptr<IAbilityConnection> acquireFormStateConnection = new FormAcquireStateConnection(bundleName, abilityName, want,
1907         provider);
1908 
1909     Want targetWant;
1910     targetWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED);
1911     targetWant.SetElementName(bundleName, abilityName);
1912     ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(targetWant, acquireFormStateConnection);
1913     if (errorCode != ERR_OK) {
1914         HILOG_ERROR("%{public}s, ConnectServiceAbility failed.", __func__);
1915         return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED;
1916     }
1917     stateInfo.state = FormState::DEFAULT;
1918     return ERR_OK;
1919 }
1920 
1921 /**
1922  * @brief Notify the form is visible or not.
1923  * @param formIds Indicates the ID of the forms.
1924  * @param isVisible Visible or not.
1925  * @param callerToken Host client.
1926  * @return Returns ERR_OK on success, others on failure.
1927  */
NotifyFormsVisible(const std::vector<int64_t> & formIds,bool isVisible,const sptr<IRemoteObject> & callerToken)1928 int FormMgrAdapter::NotifyFormsVisible(const std::vector<int64_t> &formIds, bool isVisible,
1929                                        const sptr<IRemoteObject> &callerToken)
1930 {
1931     HILOG_INFO("%{public}s, isVisible: %{public}d.", __func__, isVisible);
1932     return FormDataMgr::GetInstance().NotifyFormsVisible(formIds, isVisible, callerToken);
1933 }
1934 
1935 /**
1936  * @brief Notify the form is enable to be updated or not.
1937  * @param formIds Indicates the ID of the forms.
1938  * @param isEnableUpdate enable update or not.
1939  * @param callerToken Host client.
1940  * @return Returns ERR_OK on success, others on failure.
1941  */
NotifyFormsEnableUpdate(const std::vector<int64_t> & formIds,bool isEnableUpdate,const sptr<IRemoteObject> & callerToken)1942 int FormMgrAdapter::NotifyFormsEnableUpdate(const std::vector<int64_t> &formIds, bool isEnableUpdate,
1943                                             const sptr<IRemoteObject> &callerToken)
1944 {
1945     HILOG_INFO("%{public}s, isEnableUpdate: %{public}d.", __func__, isEnableUpdate);
1946     return HandleUpdateFormFlag(formIds, callerToken, isEnableUpdate, true);
1947 }
1948 
1949 /**
1950  * @brief Get All FormsInfo.
1951  * @param formInfos Return the forms' information of all forms provided.
1952  * @return Returns ERR_OK on success, others on failure.
1953  */
GetAllFormsInfo(std::vector<FormInfo> & formInfos)1954 int FormMgrAdapter::GetAllFormsInfo(std::vector<FormInfo> &formInfos)
1955 {
1956     return FormInfoMgr::GetInstance().GetAllFormsInfo(formInfos);
1957 }
1958 
1959 /**
1960  * @brief Get forms info by bundle name .
1961  * @param bundleName Application name.
1962  * @param formInfos Return the forms' information of the specify application name.
1963  * @return Returns ERR_OK on success, others on failure.
1964  */
GetFormsInfoByApp(std::string & bundleName,std::vector<FormInfo> & formInfos)1965 int FormMgrAdapter::GetFormsInfoByApp(std::string &bundleName, std::vector<FormInfo> &formInfos)
1966 {
1967     return FormInfoMgr::GetInstance().GetFormsInfoByBundle(bundleName, formInfos);
1968 }
1969 
1970 /**
1971  * @brief Get forms info by bundle name and module name.
1972  * @param bundleName bundle name.
1973  * @param moduleName Module name of hap.
1974  * @param formInfos Return the forms' information of the specify bundle name and module name.
1975  * @return Returns ERR_OK on success, others on failure.
1976  */
GetFormsInfoByModule(std::string & bundleName,std::string & moduleName,std::vector<FormInfo> & formInfos)1977 int FormMgrAdapter::GetFormsInfoByModule(std::string &bundleName, std::string &moduleName,
1978                                          std::vector<FormInfo> &formInfos)
1979 {
1980     return FormInfoMgr::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos);
1981 }
1982 
1983 /**
1984  * @brief Update action string for router event.
1985  * @param formId Indicates the unique id of form.
1986  * @param action Indicates the origin action string.
1987  * @return Returns ERR_OK on success, others on failure.
1988  */
UpdateRouterAction(const int64_t formId,std::string & action)1989 int FormMgrAdapter::UpdateRouterAction(const int64_t formId, std::string &action)
1990 {
1991     HILOG_INFO("%{public}s called.", __func__);
1992     if (formId <= 0) {
1993         HILOG_ERROR("%{public}s form formId or bundleName is invalid", __func__);
1994         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1995     }
1996 
1997     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
1998     FormRecord record;
1999     bool bGetRecord = FormDataMgr::GetInstance().GetFormRecord(matchedFormId, record);
2000     if (!bGetRecord) {
2001         HILOG_ERROR("%{public}s fail, not exist such form:%{public}" PRId64 "", __func__, matchedFormId);
2002         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
2003     }
2004 
2005     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
2006     if (iBundleMgr == nullptr) {
2007         HILOG_ERROR("%{public}s fail, failed to get IBundleMgr.", __func__);
2008         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
2009     }
2010 
2011     if (CheckIsSystemAppByBundleName(iBundleMgr, record.bundleName)) {
2012         return ERR_OK;
2013     }
2014 
2015     if (action.empty()) {
2016         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
2017     }
2018 
2019     nlohmann::json actionObject = nlohmann::json::parse(action, nullptr, false);
2020     if (actionObject.is_discarded()) {
2021         HILOG_ERROR("failed to parse jsonDataString: %{public}s.", action.c_str());
2022         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
2023     }
2024 
2025     actionObject["bundleName"] = record.bundleName;
2026     action = actionObject.dump();
2027     return ERR_OK;
2028 }
2029 }  // namespace AppExecFwk
2030 }  // namespace OHOS
2031