• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "form_mgr_adapter.h"
17 
18 #include <cinttypes>
19 #include <regex>
20 
21 #include "ability_manager_errors.h"
22 #ifdef DEVICE_USAGE_STATISTICS_ENABLE
23 #include "bundle_active_client.h"
24 #endif
25 #include "form_acquire_connection.h"
26 #include "form_acquire_state_connection.h"
27 #include "form_ams_helper.h"
28 #include "form_background_connection.h"
29 #include "form_bms_helper.h"
30 #include "form_cache_mgr.h"
31 #include "form_cast_temp_connection.h"
32 #include "form_constants.h"
33 #include "form_data_mgr.h"
34 #include "form_db_cache.h"
35 #include "form_db_info.h"
36 #include "form_dump_mgr.h"
37 #include "form_event_notify_connection.h"
38 #include "form_info_mgr.h"
39 #include "form_mgr_errors.h"
40 #include "form_provider_info.h"
41 #include "form_provider_interface.h"
42 #include "form_provider_mgr.h"
43 #include "form_render_connection.h"
44 #include "form_render_mgr.h"
45 #include "form_share_mgr.h"
46 #include "form_supply_callback.h"
47 #include "form_timer_mgr.h"
48 #include "form_util.h"
49 #include "hilog_wrapper.h"
50 #include "hitrace_meter.h"
51 #include "if_system_ability_manager.h"
52 #include "in_process_call_wrapper.h"
53 #include "ipc_skeleton.h"
54 #include "iservice_registry.h"
55 #include "nlohmann/json.hpp"
56 #include "system_ability_definition.h"
57 
58 namespace OHOS {
59 namespace AppExecFwk {
60 namespace {
61 constexpr int32_t CALLING_UID_TRANSFORM_DIVISOR = 200000;
62 constexpr int32_t SYSTEM_UID = 1000;
63 const std::string POINT_ETS = ".ets";
64 } // namespace
65 
FormMgrAdapter()66 FormMgrAdapter::FormMgrAdapter()
67 {
68 }
~FormMgrAdapter()69 FormMgrAdapter::~FormMgrAdapter()
70 {
71 }
72 /**
73  * @brief Add form with want, send want to form manager service.
74  * @param formId The Id of the forms to add.
75  * @param want The want of the form to add.
76  * @param callerToken Caller ability token.
77  * @param formInfo Form info.
78  * @return Returns ERR_OK on success, others on failure.
79  */
AddForm(const int64_t formId,const Want & want,const sptr<IRemoteObject> & callerToken,FormJsInfo & formInfo)80 int FormMgrAdapter::AddForm(const int64_t formId, const Want &want,
81     const sptr<IRemoteObject> &callerToken, FormJsInfo &formInfo)
82 {
83     if (formId < 0 || callerToken == nullptr) {
84         HILOG_ERROR("%{public}s fail, callerToken can not be NULL", __func__);
85         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
86     }
87 
88     // check form count limit
89     bool tempFormFlag = want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false);
90     int callingUid = IPCSkeleton::GetCallingUid();
91     int checkCode = 0;
92     if (tempFormFlag && !FormRenderMgr::GetInstance().IsRerenderForRenderServiceDied(formId)) {
93         if (formId > 0) {
94             HILOG_ERROR("%{public}s fail, temp form id is invalid, formId:%{public}" PRId64 "", __func__, formId);
95             return ERR_APPEXECFWK_FORM_INVALID_PARAM;
96         }
97         checkCode = FormDataMgr::GetInstance().CheckTempEnoughForm();
98     } else {
99         if (formId == 0) {
100             // get current userId
101             int32_t currentUserId = GetCurrentUserId(callingUid);
102             checkCode = FormDataMgr::GetInstance().CheckEnoughForm(callingUid, currentUserId);
103         }
104     }
105     if (checkCode != 0) {
106         HILOG_ERROR("%{public}s fail, too much forms in system", __func__);
107         return checkCode;
108     }
109 
110     // get from config info
111     FormItemInfo formItemInfo;
112     int32_t errCode = GetFormConfigInfo(want, formItemInfo);
113     if (errCode != ERR_OK) {
114         HILOG_ERROR("%{public}s fail, get form config info failed.", __func__);
115         return errCode;
116     }
117     formItemInfo.SetFormId(formId);
118 
119     // publish form
120     if (formId > 0 && FormDataMgr::GetInstance().IsRequestPublishForm(formId)) {
121         return AddRequestPublishForm(formItemInfo, want, callerToken, formInfo);
122     }
123 
124     Want newWant(want);
125     // in application form
126     if (formItemInfo.GetProviderBundleName() == formItemInfo.GetHostBundleName()) {
127         HILOG_DEBUG("form in application");
128         newWant.SetParam(Constants::PARAM_FORM_HOST_TOKEN, callerToken);
129     }
130 
131     WantParams wantParams = newWant.GetParams();
132     // share form
133     if (formId == 0 && DelayedSingleton<FormShareMgr>::GetInstance()->IsShareForm(newWant)) {
134         DelayedSingleton<FormShareMgr>::GetInstance()->AddProviderData(newWant, wantParams);
135     }
136     if (formId > 0) {
137         return AllotFormById(formItemInfo, callerToken, wantParams, formInfo);
138     } else {
139         return AllotFormByInfo(formItemInfo, callerToken, wantParams, formInfo);
140     }
141 }
142 
143 /**
144  * @brief Delete forms with formIds, send formIds to form manager service.
145  * @param formId The Id of the forms to delete.
146  * @param callerToken Caller ability token.
147  * @return Returns ERR_OK on success, others on failure.
148  */
DeleteForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)149 int FormMgrAdapter::DeleteForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
150 {
151     if (formId <= 0 || callerToken == nullptr) {
152         HILOG_ERROR("%{public}s, deleteForm invalid param", __func__);
153         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
154     }
155 
156     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
157     // remove connection for in application form
158     FormSupplyCallback::GetInstance()->RemoveConnection(matchedFormId, callerToken);
159     if (FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) {
160         // delete temp form if receive delete form call
161         return HandleDeleteTempForm(matchedFormId, callerToken);
162     }
163     return HandleDeleteForm(matchedFormId, callerToken);
164 }
165 
166 /**
167  * @brief Stop rendering form.
168  * @param formId The Id of the forms to delete.
169  * @param compId The compId of the forms to delete.
170  * @return Returns ERR_OK on success, others on failure.
171  */
StopRenderingForm(const int64_t formId,const std::string & compId)172 int FormMgrAdapter::StopRenderingForm(const int64_t formId, const std::string &compId)
173 {
174     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
175     if (formId <= 0 || compId.empty()) {
176         HILOG_ERROR("%{public}s, deleteForm invalid param", __func__);
177         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
178     }
179 
180     FormRecord record;
181     FormDataMgr::GetInstance().GetFormRecord(formId, record);
182     FormRenderMgr::GetInstance().StopRenderingForm(formId, record, compId);
183     return ERR_OK;
184 }
185 
186 
187 /**
188  * @brief Release forms with formIds, send formIds to form Mgr service.
189  * @param formId The Id of the forms to release.
190  * @param callerToken Caller ability token.
191  * @param delCache Delete Cache or not.
192  * @return Returns ERR_OK on success, others on failure.
193  */
ReleaseForm(const int64_t formId,const sptr<IRemoteObject> & callerToken,const bool delCache)194 int FormMgrAdapter::ReleaseForm(const int64_t formId, const sptr<IRemoteObject> &callerToken, const bool delCache)
195 {
196     HILOG_INFO("%{public}s called.", __func__);
197     if (formId <= 0 || callerToken == nullptr) {
198         HILOG_ERROR("%{public}s, releaseForm invalid param", __func__);
199         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
200     }
201     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
202     // remove connection for in application form
203     FormSupplyCallback::GetInstance()->RemoveConnection(matchedFormId, callerToken);
204     if (FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) {
205         // delete temp form if receive release form call
206         return HandleDeleteTempForm(matchedFormId, callerToken);
207     }
208     FormRecord record;
209     FormDataMgr::GetInstance().GetFormRecord(formId, record);
210     FormRenderMgr::GetInstance().StopRenderingForm(formId, record, "", callerToken);
211     FormRecord dbRecord;
212     if (FormDbCache::GetInstance().GetDBRecord(matchedFormId, dbRecord) != ERR_OK) {
213         HILOG_ERROR("%{public}s, not exist such db form:%{public}" PRId64 "", __func__, formId);
214         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
215     }
216     int callingUid = IPCSkeleton::GetCallingUid();
217     int32_t userId = GetCurrentUserId(callingUid);
218     bool isSelfDbFormId = (userId == dbRecord.userId) && ((std::find(dbRecord.formUserUids.begin(),
219         dbRecord.formUserUids.end(), callingUid) != dbRecord.formUserUids.end()) ? true : false);
220     if (!isSelfDbFormId) {
221         HILOG_ERROR("%{public}s, not self form:%{public}" PRId64 "", __func__, formId);
222         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
223     }
224     if (delCache) {
225         ErrCode result = HandleReleaseForm(matchedFormId, callerToken);
226         if (result != ERR_OK) {
227             HILOG_ERROR("%{public}s, release form error.", __func__);
228             return result;
229         }
230     }
231 
232     if (!FormDataMgr::GetInstance().DeleteHostRecord(callerToken, matchedFormId)) {
233         HILOG_ERROR("%{public}s, failed to remove host record", __func__);
234         return ERR_APPEXECFWK_FORM_COMMON_CODE;
235     }
236     if (!FormTimerMgr::GetInstance().RemoveFormTimer(matchedFormId)) {
237         HILOG_ERROR("%{public}s, remove timer error", __func__);
238         return ERR_APPEXECFWK_FORM_COMMON_CODE;
239     }
240     return ERR_OK;
241 }
242 
243 /**
244  * @brief Handle release form.
245  * @param formId The form id.
246  * @param callerToken Caller ability token.
247  * @return Returns ERR_OK on success, others on failure.
248  */
HandleReleaseForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)249 ErrCode FormMgrAdapter::HandleReleaseForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
250 {
251     HILOG_INFO("%{public}s called.", __func__);
252     if (!FormDataMgr::GetInstance().ExistFormRecord(formId)) {
253         HILOG_ERROR("%{public}s, not exist such db or temp form:%{public}" PRId64 "", __func__, formId);
254         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
255     }
256 
257     FormHostRecord hostRecord;
258     bool hasRecord = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, hostRecord);
259     bool isSelfId = hasRecord && hostRecord.Contains(formId);
260     if (!isSelfId) {
261         HILOG_ERROR("%{public}s, not self form:%{public}" PRId64 "", __func__, formId);
262         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
263     }
264 
265     HILOG_DEBUG("%{public}s, release formRecords, formId: %{public}" PRId64 "", __func__, formId);
266     FormDataMgr::GetInstance().DeleteFormUserUid(formId, IPCSkeleton::GetCallingUid());
267     if (!FormDataMgr::GetInstance().HasFormUserUids(formId)) {
268         FormDataMgr::GetInstance().DeleteFormRecord(formId);
269         if (!FormTimerMgr::GetInstance().RemoveFormTimer(formId)) {
270             HILOG_ERROR("%{public}s, remove timer error", __func__);
271             return ERR_APPEXECFWK_FORM_COMMON_CODE;
272         }
273     }
274     return ERR_OK;
275 }
276 
277 /**
278  * @brief Handle delete form.
279  * @param formId The form id.
280  * @param callerToken Caller ability token.
281  * @return Returns ERR_OK on success, others on failure.
282  */
HandleDeleteForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)283 ErrCode FormMgrAdapter::HandleDeleteForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
284 {
285     FormRecord dbRecord;
286     if (FormDbCache::GetInstance().GetDBRecord(formId, dbRecord) != ERR_OK) {
287         HILOG_ERROR("%{public}s, not exist such db form:%{public}" PRId64 "", __func__, formId);
288         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
289     }
290     FormRecord record;
291     FormDataMgr::GetInstance().GetFormRecord(formId, record);
292     FormRenderMgr::GetInstance().StopRenderingForm(formId, record, "", callerToken);
293 #ifdef DEVICE_USAGE_STATISTICS_ENABLE
294     DeviceUsageStats::BundleActiveEvent event(record.bundleName, record.moduleName, record.formName,
295         record.specification, record.formId, DeviceUsageStats::BundleActiveEvent::FORM_IS_REMOVED);
296 #endif
297     int callingUid = IPCSkeleton::GetCallingUid();
298     int32_t userId = GetCurrentUserId(callingUid);
299     bool isSelfDbFormId = (userId == dbRecord.userId) && ((std::find(dbRecord.formUserUids.begin(),
300         dbRecord.formUserUids.end(), callingUid) != dbRecord.formUserUids.end()) ? true : false);
301     if (!isSelfDbFormId) {
302         HILOG_ERROR("%{public}s, not self form:%{public}" PRId64 ", callingUid:%{public}d",
303             __func__, formId, callingUid);
304         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
305     }
306 
307     ErrCode result = HandleDeleteFormCache(dbRecord, callingUid, formId);
308     if (result != ERR_OK) {
309         return result;
310     }
311 
312     if (!FormDataMgr::GetInstance().DeleteHostRecord(callerToken, formId)) {
313         HILOG_ERROR("%{public}s, failed to remove host record", __func__);
314         return ERR_APPEXECFWK_FORM_COMMON_CODE;
315     }
316 
317 #ifdef DEVICE_USAGE_STATISTICS_ENABLE
318     DeviceUsageStats::BundleActiveClient::GetInstance().ReportEvent(event, userId);
319 #endif
320     return ERR_OK;
321 }
322 
323 /**
324  * @brief Handle delete temp form.
325  * @param formId The form id.
326  * @param callerToken Caller ability token.
327  * @return Returns ERR_OK on success, others on failure.
328  */
HandleDeleteTempForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)329 ErrCode FormMgrAdapter::HandleDeleteTempForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
330 {
331     HILOG_INFO("%{public}s called.", __func__);
332     int uid = IPCSkeleton::GetCallingUid();
333     FormRecord record;
334     bool isFormRecExist = FormDataMgr::GetInstance().GetFormRecord(formId, record);
335     bool isSelfTempFormId = false;
336     if (isFormRecExist && record.formTempFlag) {
337         int32_t userId = GetCurrentUserId(uid);
338         isSelfTempFormId = (userId == record.userId) && ((std::find(record.formUserUids.begin(),
339             record.formUserUids.end(), uid) != record.formUserUids.end()) ? true : false);
340     }
341     if (!isSelfTempFormId) {
342         HILOG_ERROR("%{public}s, not self form:%{public}" PRId64 "", __func__, formId);
343         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
344     }
345     FormRenderMgr::GetInstance().StopRenderingForm(formId, record, "", callerToken);
346     FormDataMgr::GetInstance().DeleteFormUserUid(formId, uid);
347     if (!FormDataMgr::GetInstance().HasFormUserUids(formId)) {
348         int result = FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, record);
349         if (result != ERR_OK) {
350             HILOG_ERROR("%{public}s, failed!", __func__);
351             FormDataMgr::GetInstance().AddFormUserUid(formId, uid);
352             return result;
353         }
354         if (!FormDataMgr::GetInstance().DeleteTempForm(formId)) {
355             HILOG_ERROR("%{public}s, form id is not existed.", __func__);
356             return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
357         }
358         FormDataMgr::GetInstance().DeleteFormRecord(formId);
359         if (!FormCacheMgr::GetInstance().DeleteData(formId)) {
360             HILOG_ERROR("%{public}s, failed to remove cache data", __func__);
361             return ERR_APPEXECFWK_FORM_COMMON_CODE;
362         }
363     }
364 
365     if (!FormDataMgr::GetInstance().DeleteHostRecord(callerToken, formId)) {
366         HILOG_ERROR("%{public}s, failed to remove host record", __func__);
367         return ERR_APPEXECFWK_FORM_COMMON_CODE;
368     }
369 
370     HILOG_DEBUG("%{public}s, record.formUserUids size: %{public}zu", __func__, record.formUserUids.size());
371     return ERR_OK;
372 }
373 
374 /**
375  * @brief Handle delete form cache.
376  * @param dbRecord Form storage information.
377  * @param uid calling user id.
378  * @param formId The form id.
379  * @return Returns ERR_OK on success, others on failure.
380  */
HandleDeleteFormCache(FormRecord & dbRecord,const int uid,const int64_t formId)381 ErrCode FormMgrAdapter::HandleDeleteFormCache(FormRecord &dbRecord, const int uid, const int64_t formId)
382 {
383     HILOG_DEBUG("%{public}s, delete formDBRecords, formId: %{public}" PRId64 "", __func__, formId);
384     auto iter = std::find(dbRecord.formUserUids.begin(), dbRecord.formUserUids.end(), uid);
385     if (iter != dbRecord.formUserUids.end()) {
386         dbRecord.formUserUids.erase(iter);
387     }
388 
389     ErrCode result = ERR_OK;
390     if (dbRecord.formUserUids.empty()) {
391         result = FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, dbRecord);
392         if (result != ERR_OK) {
393             HILOG_ERROR("%{public}s, failed to notify provider form delete", __func__);
394             return result;
395         }
396         if (!FormDataMgr::GetInstance().DeleteFormRecord(formId)) {
397             HILOG_ERROR("%{public}s, failed to remove cache data", __func__);
398             return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
399         }
400         if (result = FormDbCache::GetInstance().DeleteFormInfo(formId); result != ERR_OK) {
401             HILOG_ERROR("%{public}s, failed to remove db data", __func__);
402             return result;
403         }
404 
405         int32_t matchCount = FormDbCache::GetInstance().GetMatchCount(dbRecord.bundleName, dbRecord.moduleName);
406         if (matchCount == 0) {
407             FormBmsHelper::GetInstance().NotifyModuleRemovable(dbRecord.bundleName, dbRecord.moduleName);
408         }
409 
410         if (!FormCacheMgr::GetInstance().DeleteData(formId)) {
411             HILOG_ERROR("%{public}s, failed to remove cache data", __func__);
412             return ERR_APPEXECFWK_FORM_COMMON_CODE;
413         }
414         if (!FormTimerMgr::GetInstance().RemoveFormTimer(formId)) {
415             HILOG_ERROR("%{public}s, remove timer error", __func__);
416             return ERR_APPEXECFWK_FORM_COMMON_CODE;
417         }
418         return ERR_OK;
419     }
420 
421     if (result = FormDbCache::GetInstance().UpdateDBRecord(formId, dbRecord); result != ERR_OK) {
422         return result;
423     }
424 
425     HILOG_DEBUG("%{public}s, dbRecord.formUserUids size: %{public}zu", __func__, dbRecord.formUserUids.size());
426     FormBmsHelper::GetInstance().NotifyModuleNotRemovable(dbRecord.bundleName, dbRecord.moduleName);
427     FormDataMgr::GetInstance().DeleteFormUserUid(formId, uid);
428     return result;
429 }
430 
431 /**
432  * @brief Update form with formId, send formId to form manager service.
433  * @param formId The Id of the form to update.
434  * @param bundleName Provider ability bundleName.
435  * @param formProviderData form provider data.
436  * @return Returns ERR_OK on success, others on failure.
437  */
UpdateForm(const int64_t formId,const std::string & bundleName,const FormProviderData & formProviderData)438 int FormMgrAdapter::UpdateForm(const int64_t formId,
439     const std::string &bundleName, const FormProviderData &formProviderData)
440 {
441     HILOG_INFO("%{public}s start.", __func__);
442 
443     // check formId and bundleName
444     if (formId <= 0 || bundleName.empty()) {
445         HILOG_ERROR("%{public}s error, invalid formId or bundleName.", __func__);
446         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
447     }
448     // check bundle uid for permission
449     int32_t callingUid = IPCSkeleton::GetCallingUid();
450     int32_t userId = GetCurrentUserId(callingUid);
451 
452     // get uid
453     int32_t bundleUid = FormBmsHelper::GetInstance().GetUidByBundleName(bundleName, userId);
454     if (bundleUid != callingUid) {
455         HILOG_ERROR("%{public}s error, permission denied, the updated form is not your own.", __func__);
456         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
457     }
458 
459     // find matched formId
460     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
461 
462     // check exist and get the formRecord
463     FormRecord formRecord;
464     if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) {
465         HILOG_ERROR("%{public}s error, not exist such form:%{public}" PRId64 ".", __func__, matchedFormId);
466         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
467     }
468 
469     if (userId != formRecord.userId && !checkFormHostHasSaUid(formRecord)) {
470         HILOG_ERROR("%{public}s error, not under current user, formId:%{public}" PRId64 ".", __func__, matchedFormId);
471         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
472     }
473 
474     // check bundleName match
475     if (formRecord.bundleName.compare(bundleName) != 0) {
476         HILOG_ERROR("%{public}s error, not match bundleName:%{public}s.", __func__, bundleName.c_str());
477         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
478     }
479 
480     if (formRecord.uiSyntax == FormType::ETS) {
481         WantParams wantParams;
482         return FormRenderMgr::GetInstance().UpdateRenderingForm(formId, formProviderData, wantParams, true);
483     } else {
484         // update Form
485        return FormProviderMgr::GetInstance().UpdateForm(matchedFormId, formRecord, formProviderData);
486     }
487 }
488 
489 /**
490  * @brief Request form with formId and want, send formId and want to form manager service.
491  * @param formId The Id of the form to update.
492  * @param callerToken Caller ability token.
493  * @param want The want of the form to request.
494  * @return Returns ERR_OK on success, others on failure.
495  */
RequestForm(const int64_t formId,const sptr<IRemoteObject> & callerToken,const Want & want)496 int FormMgrAdapter::RequestForm(const int64_t formId, const sptr<IRemoteObject> &callerToken, const Want &want)
497 {
498     HILOG_INFO("%{public}s called.", __func__);
499     if (formId <= 0 || callerToken == nullptr) {
500         HILOG_ERROR("%{public}s fail, invalid formId or callerToken.", __func__);
501         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
502     }
503 
504     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
505     if (!FormDataMgr::GetInstance().ExistFormRecord(matchedFormId)) {
506         HILOG_ERROR("%{public}s fail, not exist such formId:%{public}" PRId64 ".", __func__, matchedFormId);
507         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
508     }
509 
510     FormHostRecord formHostRecord;
511     bool isHostExist = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord);
512     if (!isHostExist) {
513         HILOG_ERROR("%{public}s fail, cannot find target client.", __func__);
514         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
515     }
516 
517     if (!formHostRecord.Contains(matchedFormId)) {
518         HILOG_ERROR("%{public}s fail, form is not self-owned.", __func__);
519         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
520     }
521 
522     HILOG_INFO("%{public}s, find target client.", __func__);
523     Want reqWant(want);
524     int callingUid = IPCSkeleton::GetCallingUid();
525     int32_t userId = GetCurrentUserId(callingUid);
526     reqWant.SetParam(Constants::PARAM_FORM_USER_ID, userId);
527     return FormProviderMgr::GetInstance().RefreshForm(matchedFormId, reqWant, true);
528 }
529 
530 /**
531  * @brief Form visible/invisible notify, send formIds to form manager service.
532  * @param formIds The vector of form Ids.
533  * @param callerToken Caller ability token.
534  * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE.
535  * @return Returns ERR_OK on success, others on failure.
536  */
NotifyWhetherVisibleForms(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,const int32_t formVisibleType)537 ErrCode FormMgrAdapter::NotifyWhetherVisibleForms(const std::vector<int64_t> &formIds,
538     const sptr<IRemoteObject> &callerToken, const int32_t formVisibleType)
539 {
540     HILOG_INFO("%{public}s called.", __func__);
541     if (callerToken == nullptr) {
542         HILOG_ERROR("%{public}s fail, callerToken can not be NULL.", __func__);
543         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
544     }
545 
546     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
547     if (iBundleMgr == nullptr) {
548         HILOG_ERROR("%{public}s fail, failed to get IBundleMgr.", __func__);
549         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
550     }
551 
552     int64_t matchedFormId = 0;
553     std::map<std::string, std::vector<int64_t>> eventMaps;
554     for (int64_t formId : formIds) {
555         if (formId <= 0) {
556             HILOG_WARN("%{public}s, formId %{public}" PRId64 " is less than 0", __func__, formId);
557             continue;
558         }
559         matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
560         FormRecord formRecord;
561         // Update provider info to host
562         if (!UpdateProviderInfoToHost(matchedFormId, callerToken, formVisibleType, formRecord)) {
563             continue;
564         }
565 
566         // Check if the form provider is system app
567         if (!CheckIsSystemAppByBundleName(iBundleMgr, formRecord.bundleName)) {
568             continue;
569         }
570 
571         // Create eventMaps
572         if (!CreateHandleEventMap(matchedFormId, formRecord, eventMaps)) {
573             continue;
574         }
575     }
576 
577     for (auto iter = eventMaps.begin(); iter != eventMaps.end(); iter++) {
578         if (HandleEventNotify(iter->first, iter->second, formVisibleType) != ERR_OK) {
579             HILOG_WARN("%{public}s fail, HandleEventNotify error, key is %{public}s.", __func__, iter->first.c_str());
580         }
581     }
582 
583     return ERR_OK;
584 }
585 
586 /**
587  * @brief Temp form to normal form.
588  * @param formId The Id of the form.
589  * @param callerToken Caller ability token.
590  * @return Returns ERR_OK on success, others on failure.
591  */
CastTempForm(const int64_t formId,const sptr<IRemoteObject> & callerToken)592 int FormMgrAdapter::CastTempForm(const int64_t formId, const sptr<IRemoteObject> &callerToken)
593 {
594     if (formId <= 0 || callerToken == nullptr) {
595         HILOG_ERROR("%{public}s, invalid formId or callerToken", __func__);
596         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
597     }
598 
599     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
600     if (!FormDataMgr::GetInstance().ExistFormRecord(matchedFormId) ||
601         !FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) {
602         HILOG_ERROR("%{public}s, not exist such temp form:%{public}" PRId64 "", __func__, matchedFormId);
603         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
604     }
605 
606     FormHostRecord record;
607     bool hasRecord = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, record);
608     if (!hasRecord || !record.Contains(matchedFormId)) {
609         HILOG_ERROR("%{public}s, not self form:%{public}" PRId64 "", __func__, matchedFormId);
610         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
611     }
612 
613     int callingUid = IPCSkeleton::GetCallingUid();
614     int32_t userId = GetCurrentUserId(callingUid);
615     int checkCode = FormDataMgr::GetInstance().CheckEnoughForm(callingUid, userId);
616     if (checkCode != 0) {
617         HILOG_ERROR("%{public}s, %{public}" PRId64 " failed,because if too mush forms", __func__, matchedFormId);
618         return checkCode;
619     }
620 
621     FormRecord formRecord;
622     if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) {
623         HILOG_ERROR("%{public}s fail, not exist such form:%{public}" PRId64 ".", __func__, matchedFormId);
624         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
625     }
626     int bindSupplierCheckCode = HandleCastTempForm(matchedFormId, formRecord);
627     if (bindSupplierCheckCode != 0) {
628         HILOG_ERROR("%{public}s, cast temp form bindSupplier failed", __func__);
629         return bindSupplierCheckCode;
630     }
631 
632     if (!FormDataMgr::GetInstance().DeleteTempForm(matchedFormId)) {
633         HILOG_ERROR("%{public}s fail, delete temp form error, formId:%{public}" PRId64 ".", __func__, matchedFormId);
634         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
635     }
636     if (!FormDataMgr::GetInstance().ModifyFormTempFlag(matchedFormId, false)) {
637         HILOG_ERROR("%{public}s fail, modify form temp flag error, formId:%{public}" PRId64 ".",
638             __func__, matchedFormId);
639         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
640     }
641     if (!FormDataMgr::GetInstance().AddFormUserUid(matchedFormId, callingUid)) {
642         HILOG_ERROR("%{public}s fail, add form user uid error, formId:%{public}" PRId64 ".", __func__, matchedFormId);
643         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
644     }
645 
646     if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) {
647         HILOG_ERROR("%{public}s fail, not exist such form:%{public}" PRId64 ".", __func__, matchedFormId);
648         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
649     }
650 
651     ErrCode errorCode = FormDbCache::GetInstance().UpdateDBRecord(matchedFormId, formRecord);
652     if (errorCode != ERR_OK) {
653         HILOG_ERROR("%{public}s fail, update db record error, formId:%{public}" PRId64 ".", __func__, matchedFormId);
654         return errorCode;
655     }
656 
657     // start timer
658     return AddFormTimer(formRecord);
659 }
660 /**
661  * @brief Handle cast temp form.
662  * @param formId The form id.
663  * @param record Form information.
664  * @return Returns ERR_OK on success, others on failure.
665  */
HandleCastTempForm(const int64_t formId,const FormRecord & record)666 ErrCode FormMgrAdapter::HandleCastTempForm(const int64_t formId, const FormRecord &record)
667 {
668     HILOG_DEBUG("%{public}s, cast temp form to normal form, notify supplier, package:%{public}s, class:%{public}s",
669         __func__, record.bundleName.c_str(), record.abilityName.c_str());
670     sptr<IAbilityConnection> castTempConnection = new FormCastTempConnection(formId,
671         record.bundleName, record.abilityName);
672 
673     Want want;
674     want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED);
675     want.SetElementName(record.bundleName, record.abilityName);
676     ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, castTempConnection);
677     if (errorCode != ERR_OK) {
678         HILOG_ERROR("%{public}s fail, ConnectServiceAbility failed.", __func__);
679         return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED;
680     }
681     return ERR_OK;
682 }
683 /**
684  * @brief Dump all of form storage infos.
685  * @param formInfos All of form storage infos.
686  * @return Returns ERR_OK on success, others on failure.
687  */
DumpStorageFormInfos(std::string & formInfos) const688 int FormMgrAdapter::DumpStorageFormInfos(std::string &formInfos) const
689 {
690     std::vector<FormDBInfo> formDBInfos;
691     FormDbCache::GetInstance().GetAllFormInfo(formDBInfos);
692     if (formDBInfos.empty()) {
693         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
694     }
695     std::sort(formDBInfos.begin(), formDBInfos.end(),
696         [] (const FormDBInfo &formDBInfoA, const FormDBInfo &formDBInfoB) -> bool {
697         return formDBInfoA.formId < formDBInfoB.formId;
698     });
699     FormDumpMgr::GetInstance().DumpStorageFormInfos(formDBInfos, formInfos);
700     return ERR_OK;
701 }
702 /**
703  * @brief Dump form info by a bundle name.
704  * @param bundleName The bundle name of form provider.
705  * @param formInfos Form infos.
706  * @return Returns ERR_OK on success, others on failure.
707  */
DumpFormInfoByBundleName(const std::string & bundleName,std::string & formInfos) const708 int FormMgrAdapter::DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) const
709 {
710     HILOG_INFO("%{public}s called.", __func__);
711     std::vector<FormRecord> formRecordInfos;
712     if (!FormDataMgr::GetInstance().GetFormRecord(bundleName, formRecordInfos)) {
713         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
714     }
715     FormDumpMgr::GetInstance().DumpFormInfos(formRecordInfos, formInfos);
716     return ERR_OK;
717 }
718 /**
719  * @brief Dump form info by a bundle name.
720  * @param formId The id of the form.
721  * @param formInfo Form info.
722  * @return Returns ERR_OK on success, others on failure.
723  */
DumpFormInfoByFormId(const std::int64_t formId,std::string & formInfo) const724 int FormMgrAdapter::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) const
725 {
726     HILOG_INFO("%{public}s called.", __func__);
727     int reply = ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
728 
729     FormRecord formRecord;
730     if (FormDataMgr::GetInstance().GetFormRecord(formId, formRecord)) {
731         FormDumpMgr::GetInstance().DumpFormInfo(formRecord, formInfo);
732         reply = ERR_OK;
733     }
734 
735     std::vector<FormHostRecord> formHostRecords;
736     FormDataMgr::GetInstance().GetFormHostRecord(formId, formHostRecords);
737     for (const auto &iter : formHostRecords) {
738         FormDumpMgr::GetInstance().DumpFormHostInfo(iter, formInfo);
739         reply = ERR_OK;
740     }
741 
742     return reply;
743 }
744 /**
745  * @brief Dump form timer by form id.
746  * @param formId The id of the form.
747  * @param isTimingService "true" or "false".
748  * @return Returns ERR_OK on success, others on failure.
749  */
DumpFormTimerByFormId(const std::int64_t formId,std::string & isTimingService) const750 int FormMgrAdapter::DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService) const
751 {
752     HILOG_INFO("%{public}s called.", __func__);
753     FormTimer formTimer;
754     UpdateAtItem updateAtItem;
755     DynamicRefreshItem dynamicItem;
756     bool resultInter = FormTimerMgr::GetInstance().GetIntervalTimer(formId, formTimer);
757     bool resultUpdate = FormTimerMgr::GetInstance().GetUpdateAtTimer(formId, updateAtItem);
758     bool resultDynamic = FormTimerMgr::GetInstance().GetDynamicItem(formId, dynamicItem);
759     HILOG_INFO("%{public}s resultInter:%{public}d,resultUpdate:%{public}d,resultDynamic:%{public}d",
760         __func__, resultInter, resultUpdate, resultDynamic);
761     if (resultInter || resultUpdate || resultDynamic) {
762         isTimingService = "true";
763     } else {
764         isTimingService = "false";
765     }
766     return ERR_OK;
767 }
768 /**
769  * @brief Get form configure info.
770  * @param want The want of the request.
771  * @param formItemInfo Form configure info.
772  * @return Returns ERR_OK on success, others on failure.
773  */
GetFormConfigInfo(const Want & want,FormItemInfo & formConfigInfo)774 ErrCode FormMgrAdapter::GetFormConfigInfo(const Want &want, FormItemInfo &formConfigInfo)
775 {
776     HILOG_DEBUG("GetFormConfigInfo start.");
777     BundleInfo bundleInfo;
778     std::string packageName;
779     ErrCode errCode = GetBundleInfo(want, bundleInfo, packageName);
780     if (errCode != ERR_OK) {
781         HILOG_ERROR("Get bundle info failed");
782         return errCode;
783     }
784 
785     FormInfo formInfo;
786     errCode = GetFormInfo(want, formInfo);
787     if (errCode != ERR_OK) {
788         HILOG_ERROR("Get target form info failed");
789         return errCode;
790     }
791     if (!formInfo.IsValid()) {
792         HILOG_ERROR("The form info is invalid");
793         return ERR_APPEXECFWK_FORM_GET_INFO_FAILED;
794     }
795 
796     errCode = GetFormItemInfo(want, bundleInfo, formInfo, formConfigInfo);
797     if (errCode != ERR_OK) {
798         HILOG_ERROR("Get form item info failed.");
799         return errCode;
800     }
801     formConfigInfo.SetPackageName(packageName);
802     formConfigInfo.SetDeviceId(want.GetElement().GetDeviceID());
803 
804     if (!formConfigInfo.IsValidItem()) {
805         HILOG_ERROR("%{public}s fail, input param itemInfo is invalid", __func__);
806         return ERR_APPEXECFWK_FORM_GET_INFO_FAILED;
807     }
808 
809     HILOG_DEBUG("GetFormConfigInfo end.");
810     return ERR_OK;
811 }
812 /**
813  * @brief Allocate form by formId.
814  * @param info Form configure info.
815  * @param callerToken Caller ability token.
816  * @param wantParams WantParams of the request.
817  * @param formInfo Form info for form host.
818  * @return Returns ERR_OK on success, others on failure.
819  */
AllotFormById(const FormItemInfo & info,const sptr<IRemoteObject> & callerToken,const WantParams & wantParams,FormJsInfo & formInfo)820 ErrCode FormMgrAdapter::AllotFormById(const FormItemInfo &info,
821     const sptr<IRemoteObject> &callerToken, const WantParams &wantParams, FormJsInfo &formInfo)
822 {
823     int64_t formId = FormDataMgr::GetInstance().PaddingUdidHash(info.GetFormId());
824     FormRecord record;
825     bool hasRecord = FormDataMgr::GetInstance().GetFormRecord(formId, record);
826     if (hasRecord && record.formTempFlag && !FormRenderMgr::GetInstance().IsRerenderForRenderServiceDied(formId)) {
827         HILOG_ERROR("%{public}s, addForm can not acquire temp form when select form id", __func__);
828         return ERR_APPEXECFWK_FORM_COMMON_CODE;
829     }
830 
831     // ark ts form can only exist with one form host
832     if (info.GetUiSyntax() == FormType::ETS &&
833         !FormDbCache::GetInstance().IsHostOwner(formId, IPCSkeleton::GetCallingUid())) {
834         HILOG_ERROR("the specified form id does not exist in caller. formId: %{public}s.",
835             std::to_string(formId).c_str());
836         return ERR_APPEXECFWK_FORM_CFG_NOT_MATCH_ID;
837     }
838 
839     // get current userId
840     int callingUid = IPCSkeleton::GetCallingUid();
841     int32_t currentUserId = GetCurrentUserId(callingUid);
842     if (hasRecord && (record.userId == currentUserId
843         || FormDataMgr::GetInstance().IsCallingUidValid(record.formUserUids))) {
844         if (!info.IsMatch(record)) {
845             HILOG_ERROR("%{public}s, formId and item info not match:%{public}" PRId64 "", __func__, formId);
846             return ERR_APPEXECFWK_FORM_CFG_NOT_MATCH_ID;
847         }
848         return AddExistFormRecord(info, callerToken, record, formId, wantParams, formInfo);
849     }
850 
851     // find in db but not in cache
852     FormRecord dbRecord;
853     ErrCode getDbRet = FormDbCache::GetInstance().GetDBRecord(formId, dbRecord);
854     if (getDbRet == ERR_OK && (dbRecord.userId == currentUserId
855         || FormDataMgr::GetInstance().IsCallingUidValid(dbRecord.formUserUids))) {
856         return AddNewFormRecord(info, formId, callerToken, wantParams, formInfo);
857     }
858 
859     HILOG_INFO("%{public}s, addForm no such form %{public}" PRId64 "", __func__, formId);
860 
861     // delete form data in provider
862     FormRecord delRecord;
863     delRecord.bundleName = info.GetProviderBundleName();
864     delRecord.abilityName = info.GetAbilityName();
865     FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, delRecord);
866 
867     return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
868 }
869 
AddExistFormRecord(const FormItemInfo & info,const sptr<IRemoteObject> & callerToken,const FormRecord & record,const int64_t formId,const WantParams & wantParams,FormJsInfo & formInfo)870 ErrCode FormMgrAdapter::AddExistFormRecord(const FormItemInfo &info, const sptr<IRemoteObject> &callerToken,
871     const FormRecord &record, const int64_t formId, const WantParams &wantParams, FormJsInfo &formInfo)
872 {
873     HILOG_INFO("%{public}s call, formId:%{public}" PRId64 "", __func__, formId);
874     // allot form host record
875     int callingUid = IPCSkeleton::GetCallingUid();
876     bool isCreated = FormDataMgr::GetInstance().AllotFormHostRecord(info, callerToken, formId, callingUid);
877     if (!isCreated) {
878         HILOG_ERROR("%{public}s fail, AllotFormHostRecord failed when no matched formRecord", __func__);
879         return ERR_APPEXECFWK_FORM_COMMON_CODE;
880     }
881 
882     FormRecord newRecord(record);
883     std::string cacheData;
884     if (FormCacheMgr::GetInstance().GetData(formId, cacheData)) {
885         newRecord.formProviderInfo.SetFormDataString(cacheData);
886     }
887     FormRenderMgr::GetInstance().RenderForm(newRecord, wantParams, callerToken);
888     if (newRecord.needRefresh || !FormCacheMgr::GetInstance().IsExist(newRecord.formId)) {
889         newRecord.isInited = false;
890         FormDataMgr::GetInstance().SetFormCacheInited(formId, false);
891 
892         // acquire formInfo from provider
893         ErrCode errorCode = AcquireProviderFormInfoAsync(formId, info, wantParams);
894         if (errorCode != ERR_OK) {
895             HILOG_ERROR("%{public}s fail, AcquireProviderFormInfoAsync failed", __func__);
896             return errorCode;
897         }
898     }
899 
900     // Add new form user uid.
901     FormDataMgr::GetInstance().AddFormUserUid(formId, callingUid);
902     if (std::find(newRecord.formUserUids.begin(), newRecord.formUserUids.end(), callingUid) ==
903         newRecord.formUserUids.end()) {
904         newRecord.formUserUids.emplace_back(callingUid);
905     }
906 
907     // create form info for js
908     if (FormCacheMgr::GetInstance().GetData(formId, cacheData)) {
909         formInfo.formData = cacheData;
910     }
911     FormDataMgr::GetInstance().CreateFormJsInfo(formId, record, formInfo);
912 
913     // start update timer
914     ErrCode errorCode = AddFormTimer(newRecord);
915     if (errorCode != ERR_OK) {
916         return errorCode;
917     }
918 
919     if (!newRecord.formTempFlag) {
920         return FormDbCache::GetInstance().UpdateDBRecord(formId, newRecord);
921     }
922     return ERR_OK;
923 }
924 
925 /**
926  * @brief Allocate form by form configure info.
927  * @param info Form configure info.
928  * @param callerToken Caller ability token.
929  * @param wantParams WantParams of the request.
930  * @param formInfo Form info for form host.
931  * @return Returns ERR_OK on success, others on failure.
932  */
AllotFormByInfo(const FormItemInfo & info,const sptr<IRemoteObject> & callerToken,const WantParams & wantParams,FormJsInfo & formInfo)933 ErrCode FormMgrAdapter::AllotFormByInfo(const FormItemInfo &info,
934     const sptr<IRemoteObject> &callerToken, const WantParams &wantParams, FormJsInfo &formInfo)
935 {
936     // generate formId
937     int64_t newFormId = FormDataMgr::GetInstance().GenerateFormId();
938     if (newFormId < 0) {
939         HILOG_ERROR("%{public}s fail, generateFormId no invalid formId", __func__);
940         return ERR_APPEXECFWK_FORM_COMMON_CODE;
941     }
942     HILOG_DEBUG("newFormId:%{public}" PRId64 "", newFormId);
943     return AddNewFormRecord(info, newFormId, callerToken, wantParams, formInfo);
944 }
945 
946 /**
947  * @brief Add new form record.
948  * @param info Form configure info.
949  * @param formId The form id.
950  * @param callerToken Caller ability token.
951  * @param wantParams WantParams of the request.
952  * @param formInfo Form info for form host.
953  * @return Returns ERR_OK on success, others on failure.
954  */
AddNewFormRecord(const FormItemInfo & info,const int64_t formId,const sptr<IRemoteObject> & callerToken,const WantParams & wantParams,FormJsInfo & formInfo)955 ErrCode FormMgrAdapter::AddNewFormRecord(const FormItemInfo &info, const int64_t formId,
956     const sptr<IRemoteObject> &callerToken, const WantParams &wantParams, FormJsInfo &formInfo)
957 {
958     HILOG_INFO("%{public}s start", __func__);
959     FormItemInfo newInfo(info);
960     newInfo.SetFormId(formId);
961     // allot form host record
962     int callingUid = IPCSkeleton::GetCallingUid();
963     if (!FormDataMgr::GetInstance().AllotFormHostRecord(newInfo, callerToken, formId, callingUid)) {
964         HILOG_ERROR("%{public}s fail, AllotFormHostRecord failed when no matched formRecord", __func__);
965         return ERR_APPEXECFWK_FORM_COMMON_CODE;
966     }
967 
968     // get current userId
969     int32_t currentUserId = GetCurrentUserId(callingUid);
970     // allot form record
971     FormRecord formRecord = FormDataMgr::GetInstance().AllotFormRecord(newInfo, callingUid, currentUserId);
972 
973     FormRenderMgr::GetInstance().RenderForm(formRecord, wantParams, callerToken);
974 
975     // acquire formInfo from provider
976     ErrCode errorCode = AcquireProviderFormInfoAsync(formId, newInfo, wantParams);
977     if (errorCode != ERR_OK) {
978         HILOG_ERROR("%{public}s fail, AcquireProviderFormInfoAsync failed", __func__);
979         return errorCode;
980     }
981 
982     // create form info for js
983     FormDataMgr::GetInstance().CreateFormJsInfo(formId, formRecord, formInfo);
984 
985     // storage info
986     if (!newInfo.IsTemporaryForm()) {
987         errorCode = FormDbCache::GetInstance().UpdateDBRecord(formId, formRecord);
988         if (errorCode != ERR_OK) {
989             HILOG_ERROR("%{public}s fail, UpdateDBRecord failed", __func__);
990             return errorCode;
991         }
992     }
993 
994     // start update timer
995     if (info.GetProviderBundleName() != info.GetHostBundleName()) {
996         return AddFormTimer(formRecord);
997     }
998 
999     return ERR_OK;
1000 }
1001 
1002 /**
1003  * @brief Add form timer.
1004  * @param formRecord Form information.
1005  * @return Returns ERR_OK on success, others on failure.
1006  */
AddFormTimer(const FormRecord & formRecord)1007 ErrCode FormMgrAdapter::AddFormTimer(const FormRecord &formRecord)
1008 {
1009     HILOG_INFO("%{public}s start", __func__);
1010     if (!formRecord.isEnableUpdate || formRecord.formTempFlag) {
1011         HILOG_INFO("%{public}s isEnableUpdate:%{public}d formTempFlag:%{public}d.",
1012             __func__, formRecord.isEnableUpdate, formRecord.formTempFlag);
1013         return ERR_OK;
1014     }
1015     if (formRecord.updateDuration > 0) {
1016         bool ret = FormTimerMgr::GetInstance().AddFormTimer(formRecord.formId,
1017             formRecord.updateDuration, formRecord.userId);
1018         return ret ? ERR_OK : ERR_APPEXECFWK_FORM_COMMON_CODE;
1019     }
1020     if (formRecord.updateAtHour >= 0 && formRecord.updateAtMin >= 0) {
1021         bool ret = FormTimerMgr::GetInstance().AddFormTimer(formRecord.formId,
1022             formRecord.updateAtHour, formRecord.updateAtMin, formRecord.userId);
1023         return ret ? ERR_OK : ERR_APPEXECFWK_FORM_COMMON_CODE;
1024     }
1025     HILOG_INFO("%{public}s no need add form timer.", __func__);
1026     return ERR_OK;
1027 }
1028 
1029 /**
1030  * @brief Send event notify to form provider. The event notify type include FORM_VISIBLE and FORM_INVISIBLE.
1031  *
1032  * @param providerKey The provider key string which consists of the provider bundle name and ability name.
1033  * @param formIdsByProvider The vector of form Ids which have the same provider.
1034  * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE.
1035  * @return Returns ERR_OK on success, others on failure.
1036  */
HandleEventNotify(const std::string & providerKey,const std::vector<int64_t> & formIdsByProvider,const int32_t formVisibleType)1037 ErrCode FormMgrAdapter::HandleEventNotify(const std::string &providerKey, const std::vector<int64_t> &formIdsByProvider,
1038     const int32_t formVisibleType)
1039 {
1040     HILOG_INFO("%{public}s called.", __func__);
1041     size_t position = providerKey.find(Constants::NAME_DELIMITER);
1042     std::string bundleName = providerKey.substr(0, position);
1043     std::string abilityName = providerKey.substr(position + strlen(Constants::NAME_DELIMITER));
1044     sptr<IAbilityConnection> formEventNotifyConnection = new (std::nothrow) FormEventNotifyConnection(formIdsByProvider,
1045         formVisibleType, bundleName, abilityName);
1046     if (formEventNotifyConnection == nullptr) {
1047         HILOG_ERROR("failed to create FormEventNotifyConnection.");
1048         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1049     }
1050     Want connectWant;
1051     connectWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED);
1052     connectWant.SetElementName(bundleName, abilityName);
1053     ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formEventNotifyConnection);
1054     if (errorCode != ERR_OK) {
1055         HILOG_ERROR("%{public}s fail, ConnectServiceAbility failed.", __func__);
1056         return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED;
1057     }
1058 
1059     return ERR_OK;
1060 }
1061 
1062 /**
1063  * @brief Acquire form data from form provider.
1064  * @param formId The Id of the form.
1065  * @param info Form configure info.
1066  * @param wantParams WantParams of the request.
1067  * @return Returns ERR_OK on success, others on failure.
1068  */
AcquireProviderFormInfoAsync(const int64_t formId,const FormItemInfo & info,const WantParams & wantParams)1069 ErrCode FormMgrAdapter::AcquireProviderFormInfoAsync(const int64_t formId,
1070     const FormItemInfo &info, const WantParams &wantParams)
1071 {
1072     if (formId <= 0) {
1073         HILOG_ERROR("%{public}s fail, formId should be greater than 0", __func__);
1074         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1075     }
1076 
1077     Want newWant;
1078     newWant.SetParams(wantParams);
1079     auto hostToken = newWant.GetRemoteObject(Constants::PARAM_FORM_HOST_TOKEN);
1080     sptr<IAbilityConnection> formAcquireConnection = new (std::nothrow) FormAcquireConnection(formId, info, wantParams,
1081         hostToken);
1082     if (formAcquireConnection == nullptr) {
1083         HILOG_ERROR("formAcquireConnection is null.");
1084         return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED;
1085     }
1086     Want want;
1087     want.SetElementName(info.GetProviderBundleName(), info.GetAbilityName());
1088     want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED);
1089     ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, formAcquireConnection);
1090     if (errorCode != ERR_OK) {
1091         HILOG_ERROR("%{public}s fail, ConnectServiceAbility failed.", __func__);
1092         return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED;
1093     }
1094     return ERR_OK;
1095 }
1096 
1097 /**
1098  * @brief Get bundle info.
1099  * @param want The want of the request.
1100  * @param bundleInfo Bundle info.
1101  * @param packageName Package name.
1102  * @return Returns ERR_OK on success, others on failure.
1103  */
GetBundleInfo(const AAFwk::Want & want,BundleInfo & bundleInfo,std::string & packageName)1104 ErrCode FormMgrAdapter::GetBundleInfo(const AAFwk::Want &want, BundleInfo &bundleInfo, std::string &packageName)
1105 {
1106     HILOG_DEBUG("GetBundleInfo start.");
1107     std::string bundleName = want.GetElement().GetBundleName();
1108     std::string abilityName = want.GetElement().GetAbilityName();
1109     std::string deviceId = want.GetElement().GetDeviceID();
1110     std::string moduleName = want.GetStringParam(Constants::PARAM_MODULE_NAME_KEY);
1111     if (bundleName.empty() || abilityName.empty() || moduleName.empty()) {
1112         HILOG_ERROR("GetBundleInfo bundleName or abilityName or moduleName is invalid");
1113         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1114     }
1115 
1116     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1117     if (iBundleMgr == nullptr) {
1118         HILOG_ERROR("GetBundleMgr, failed to get IBundleMgr.");
1119         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
1120     }
1121 
1122     if (!IN_PROCESS_CALL(iBundleMgr->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES,
1123         bundleInfo, FormUtil::GetCurrentAccountId()))) {
1124         HILOG_ERROR("GetBundleInfo, failed to get bundle info.");
1125         return ERR_APPEXECFWK_FORM_GET_INFO_FAILED;
1126     }
1127 
1128     bool moduleExist = false;
1129     for (const auto &moduleInfo : bundleInfo.moduleNames) {
1130         HILOG_DEBUG("bundleInfo.moduleNames, module name:%{public}s", moduleInfo.c_str());
1131         if (moduleInfo.compare(moduleName) == 0) {
1132             moduleExist = true;
1133             break;
1134         }
1135     }
1136     if (!moduleExist) {
1137         HILOG_ERROR("GetBundleInfo no such module, name:%{public}s", moduleName.c_str());
1138         return ERR_APPEXECFWK_FORM_NO_SUCH_MODULE;
1139     }
1140 
1141     packageName = bundleName + moduleName;
1142     HILOG_DEBUG("GetBundleInfo end.");
1143     return ERR_OK;
1144 }
1145 /**
1146  * @brief Get form info.
1147  * @param want The want of the request.
1148  * @param formInfo Form info.
1149  * @return Returns ERR_OK on success, others on failure.
1150  */
GetFormInfo(const AAFwk::Want & want,FormInfo & formInfo)1151 ErrCode FormMgrAdapter::GetFormInfo(const AAFwk::Want &want, FormInfo &formInfo)
1152 {
1153     HILOG_DEBUG("GetFormInfo start.");
1154     std::string bundleName = want.GetElement().GetBundleName();
1155     std::string abilityName = want.GetElement().GetAbilityName();
1156     std::string moduleName = want.GetStringParam(Constants::PARAM_MODULE_NAME_KEY);
1157     if (bundleName.empty() || abilityName.empty() || moduleName.empty()) {
1158         HILOG_ERROR("bundleName or abilityName or moduleName is invalid");
1159         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1160     }
1161 
1162     std::vector<FormInfo> formInfos {};
1163     ErrCode errCode = FormInfoMgr::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos);
1164     if (errCode != ERR_OK) {
1165         HILOG_ERROR("GetFormsInfoByModule, failed to get form config info.");
1166         return ERR_APPEXECFWK_FORM_GET_INFO_FAILED;
1167     }
1168 
1169     std::string formName = want.GetStringParam(Constants::PARAM_FORM_NAME_KEY);
1170     if (formName.empty()) {
1171         for (const auto &form : formInfos) {
1172             if (form.defaultFlag && form.abilityName == abilityName) {
1173                 formInfo = form;
1174                 formInfo.moduleName = moduleName;
1175                 HILOG_DEBUG("GetFormInfo end.");
1176                 return ERR_OK;
1177             }
1178         }
1179     } else  {
1180         for (const auto &form : formInfos) {
1181             if (form.name == formName && form.abilityName == abilityName) {
1182                 formInfo = form;
1183                 formInfo.moduleName = moduleName;
1184                 HILOG_DEBUG("GetFormInfo end.");
1185                 return ERR_OK;
1186             }
1187         }
1188     }
1189     HILOG_ERROR("failed to get form info failed. ability name is %{public}s, form name is %{public}s",
1190         abilityName.c_str(), formName.c_str());
1191     return ERR_APPEXECFWK_FORM_GET_INFO_FAILED;
1192 }
1193 /**
1194  * @brief Get form configure info.
1195  * @param want The want of the request.
1196  * @param bundleInfo Bundle info.
1197  * @param formInfo Form info.
1198  * @param formItemInfo Form configure info.
1199  * @return Returns ERR_OK on success, others on failure.
1200  */
GetFormItemInfo(const AAFwk::Want & want,const BundleInfo & bundleInfo,const FormInfo & formInfo,FormItemInfo & formItemInfo)1201 ErrCode FormMgrAdapter::GetFormItemInfo(const AAFwk::Want &want, const BundleInfo &bundleInfo,
1202     const FormInfo &formInfo, FormItemInfo &formItemInfo)
1203 {
1204     HILOG_DEBUG("GetFormItemInfo start.");
1205     int32_t dimensionId = want.GetIntParam(Constants::PARAM_FORM_DIMENSION_KEY, formInfo.defaultDimension);
1206     if (!IsDimensionValid(formInfo, dimensionId)) {
1207         HILOG_ERROR("GetFormItemInfo failed, dimension is not valid.");
1208         return ERR_APPEXECFWK_FORM_NO_SUCH_DIMENSION;
1209     }
1210 
1211     ErrCode ret = CreateFormItemInfo(bundleInfo, formInfo, formItemInfo, want);
1212     if (ret != ERR_OK) {
1213         HILOG_ERROR("GetFormItemInfo failed, CreateFormItemInfo failed.");
1214         return ret;
1215     }
1216     formItemInfo.SetSpecificationId(dimensionId);
1217     formItemInfo.SetTemporaryFlag(want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false));
1218     HILOG_DEBUG("GetFormItemInfo end.");
1219     return ERR_OK;
1220 }
1221 /**
1222  * @brief Dimension valid check.
1223  * @param formInfo Form info.
1224  * @param dimensionId Dimension id.
1225  * @return Returns true on success, false on failure.
1226  */
IsDimensionValid(const FormInfo & formInfo,int dimensionId) const1227 bool FormMgrAdapter::IsDimensionValid(const FormInfo &formInfo, int dimensionId) const
1228 {
1229     if (formInfo.supportDimensions.empty()) {
1230         HILOG_ERROR("Js form, no support dimension.");
1231         return false;
1232     }
1233 
1234     for (size_t i = 0; i < formInfo.supportDimensions.size() && i < Constants::MAX_LAYOUT; i++) {
1235         if (formInfo.supportDimensions[i] == dimensionId) {
1236             return true;
1237         }
1238     }
1239 
1240     HILOG_ERROR("No matched dimension found for %{public}d.", dimensionId);
1241     return false;
1242 }
1243 /**
1244  * @brief Create form configure info.
1245  * @param bundleInfo Bundle info.
1246  * @param formInfo Form info.
1247  * @param itemInfo Form configure info.
1248  * @return Returns ERR_OK on success, others on failure.
1249  */
CreateFormItemInfo(const BundleInfo & bundleInfo,const FormInfo & formInfo,FormItemInfo & itemInfo,const AAFwk::Want & want)1250 ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo,
1251     const FormInfo &formInfo, FormItemInfo &itemInfo, const AAFwk::Want &want)
1252 {
1253     itemInfo.SetProviderBundleName(bundleInfo.name);
1254     itemInfo.SetVersionCode(bundleInfo.versionCode);
1255     itemInfo.SetVersionName(bundleInfo.versionName);
1256     itemInfo.SetCompatibleVersion(bundleInfo.compatibleVersion);
1257 
1258     std::string hostBundleName;
1259     bool isSaUid = IPCSkeleton::GetCallingUid() == SYSTEM_UID;
1260     ErrCode ret = ERR_APPEXECFWK_FORM_COMMON_CODE;
1261     if (isSaUid) {
1262         hostBundleName = want.GetStringParam(AppExecFwk::Constants::PARAM_FORM_HOST_BUNDLENAME_KEY);
1263         HILOG_INFO("sa uid call CreateFormItemInfo, hostBundleName is %{public}s", hostBundleName.c_str());
1264         ret = ERR_OK;
1265     } else {
1266         ret = FormBmsHelper::GetInstance().GetCallerBundleName(hostBundleName);
1267     }
1268     if (ret != ERR_OK) {
1269         HILOG_ERROR("GetFormsInfoByModule, failed to get form config info.");
1270         return ret;
1271     }
1272     itemInfo.SetHostBundleName(hostBundleName);
1273     itemInfo.SetAbilityName(formInfo.abilityName);
1274     itemInfo.SetModuleName(formInfo.moduleName); // formInfo.moduleName: bundleMgr do not set
1275     itemInfo.SetFormName(formInfo.name);
1276     itemInfo.SetEnableUpdateFlag(formInfo.updateEnabled);
1277     itemInfo.SetUpdateDuration(formInfo.updateDuration);
1278     itemInfo.SetScheduledUpdateTime(formInfo.scheduledUpdateTime);
1279     itemInfo.SetJsComponentName(formInfo.jsComponentName);
1280     itemInfo.SetFormVisibleNotify(formInfo.formVisibleNotify);
1281     auto formSrc = formInfo.src;
1282     if (formSrc.rfind(POINT_ETS) == formSrc.size() - POINT_ETS.size()) {
1283         formSrc.erase(formSrc.end() - POINT_ETS.size(), formSrc.end());
1284     }
1285     itemInfo.SetFormSrc(formSrc);
1286     itemInfo.SetFormWindow(formInfo.window);
1287     itemInfo.SetType(formInfo.type);
1288     itemInfo.SetUiSyntax(formInfo.uiSyntax);
1289 
1290     for (const auto &abilityInfo : bundleInfo.abilityInfos) {
1291         if (abilityInfo.name == formInfo.abilityName) {
1292             itemInfo.SetAbilityModuleName(abilityInfo.moduleName);
1293             if (!abilityInfo.isModuleJson) {
1294                 itemInfo.SetFormSrc("");
1295             }
1296         }
1297         auto hapPath = abilityInfo.hapPath;
1298         if (hapPath.find(Constants::ABS_CODE_PATH) != std::string::npos) {
1299             hapPath = std::regex_replace(hapPath, std::regex(Constants::ABS_CODE_PATH), Constants::LOCAL_BUNDLES);
1300         }
1301         itemInfo.AddModuleInfo(abilityInfo.moduleName, hapPath);
1302         HILOG_DEBUG("%{public}s hap path is %{public}s", abilityInfo.moduleName.c_str(), hapPath.c_str());
1303     }
1304 
1305     HILOG_INFO("%{public}s moduleInfos size: %{public}zu", __func__, bundleInfo.applicationInfo.moduleInfos.size());
1306     for (const auto &item : bundleInfo.applicationInfo.moduleInfos) {
1307         HILOG_INFO("%{public}s moduleInfos,  moduleName: %{public}s, moduleSourceDir: %{public}s", __func__,
1308             item.moduleName.c_str(), item.moduleSourceDir.c_str());
1309         if (formInfo.moduleName == item.moduleName) {
1310             itemInfo.AddHapSourceDirs(item.moduleSourceDir);
1311         }
1312     }
1313     return ERR_OK;
1314 }
1315 
1316 /**
1317  * @brief set next refresh time.
1318  * @param formId The id of the form.
1319  * @param nextTime next refresh time.
1320  * @return Returns ERR_OK on success, others on failure.
1321  */
SetNextRefreshTime(const int64_t formId,const int64_t nextTime)1322 int FormMgrAdapter::SetNextRefreshTime(const int64_t formId, const int64_t nextTime)
1323 {
1324     HILOG_INFO("%{public}s begin here, formId:%{public}" PRId64 ",nextTime:%{public}" PRId64 "",
1325         __func__, formId, nextTime);
1326     if (formId <= 0) {
1327         HILOG_ERROR("%{public}s formId is invalid", __func__);
1328         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1329     }
1330 
1331     std::string bundleName;
1332     auto ret = FormBmsHelper::GetInstance().GetCallerBundleName(bundleName);
1333     if (ret != ERR_OK) {
1334         HILOG_ERROR("%{public}s failed to get BundleName", __func__);
1335         return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED;
1336     }
1337     int32_t callingUid = IPCSkeleton::GetCallingUid();
1338     int32_t userId = GetCurrentUserId(callingUid);
1339     HILOG_INFO("%{public}s, userId:%{public}d, callingUid:%{public}d.", __func__, userId, callingUid);
1340 
1341     // get IBundleMgr
1342     int32_t bundleUid = FormBmsHelper::GetInstance().GetUidByBundleName(bundleName, userId);
1343     if (bundleUid != callingUid) {
1344         HILOG_ERROR("%{public}s error, permission denied, the form is not your own.", __func__);
1345         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1346     }
1347 
1348     FormRecord formRecord;
1349     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
1350     if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) {
1351         HILOG_ERROR("%{public}s, not found in form record.", __func__);
1352         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
1353     }
1354 
1355     bool isSelfFormId = (userId == formRecord.userId) || checkFormHostHasSaUid(formRecord);
1356     if (!isSelfFormId) {
1357         HILOG_ERROR("%{public}s, not self form:%{public}" PRId64 "", __func__, formId);
1358         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
1359     }
1360 
1361     // check bundleName
1362     if (bundleName != formRecord.bundleName) {
1363         HILOG_ERROR("%{public}s, not match bundleName:%{public}s", __func__, bundleName.c_str());
1364         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
1365     }
1366 
1367     return SetNextRefreshTimeLocked(matchedFormId, nextTime, userId);
1368 }
1369 
CheckPublishForm(Want & want)1370 ErrCode FormMgrAdapter::CheckPublishForm(Want &want)
1371 {
1372     std::string bundleName;
1373     if (!GetBundleName(bundleName)) {
1374         HILOG_ERROR("%{public}s failed to get BundleName", __func__);
1375         return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED;
1376     }
1377     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1378     if (iBundleMgr == nullptr) {
1379         HILOG_ERROR("%{public}s fail, failed to get IBundleMgr.", __func__);
1380         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
1381     }
1382     if (!CheckIsSystemAppByBundleName(iBundleMgr, bundleName)) {
1383         HILOG_ERROR("Only system app can request publish form.");
1384         return ERR_APPEXECFWK_FORM_PERMISSION_DENY_SYS;
1385     }
1386 
1387     if (bundleName != want.GetElement().GetBundleName()) {
1388         HILOG_WARN("The bundleName in want does not match the bundleName of current calling user.");
1389         want.SetBundle(bundleName);
1390     }
1391 
1392     std::string moduleName = want.GetStringParam(Constants::PARAM_MODULE_NAME_KEY);
1393     if (moduleName.empty()) {
1394         HILOG_ERROR("%{public}s error, moduleName is empty.", __func__);
1395         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1396     }
1397 
1398     bool isTemporary = want.GetBoolParam(AppExecFwk::Constants::PARAM_FORM_TEMPORARY_KEY, false);
1399     if (isTemporary) {
1400         HILOG_WARN("The published form should not be temp.");
1401         want.SetParam(AppExecFwk::Constants::PARAM_FORM_TEMPORARY_KEY, false);
1402     }
1403 
1404     std::string abilityName = want.GetElement().GetAbilityName();
1405     std::string formName = want.GetStringParam(AppExecFwk::Constants::PARAM_FORM_NAME_KEY);
1406     std::vector<FormInfo> formInfos {};
1407     ErrCode errCode = FormInfoMgr::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos);
1408     if (errCode != ERR_OK) {
1409         HILOG_ERROR("%{public}s error, failed to get forms info.", __func__);
1410         return errCode;
1411     }
1412     for (auto &formInfo: formInfos) {
1413         int32_t dimensionId = want.GetIntParam(Constants::PARAM_FORM_DIMENSION_KEY, 0);
1414         if ((formInfo.abilityName == abilityName) && (formInfo.name == formName) &&
1415             (IsDimensionValid(formInfo, dimensionId))) {
1416             want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, dimensionId);
1417             return ERR_OK;
1418         }
1419     }
1420     HILOG_ERROR("failed to find match form info.");
1421     return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1422 }
1423 
QueryPublishFormToHost(Want & want)1424 ErrCode FormMgrAdapter::QueryPublishFormToHost(Want &want)
1425 {
1426     /* Query the highest priority ability or extension ability for publishing form */
1427     AppExecFwk::AbilityInfo abilityInfo;
1428     AppExecFwk::ExtensionAbilityInfo extensionAbilityInfo;
1429     int callingUid = IPCSkeleton::GetCallingUid();
1430     int32_t userId = GetCurrentUserId(callingUid);
1431     if (!FormBmsHelper::GetInstance().GetAbilityInfoByAction(
1432         Constants::FORM_PUBLISH_ACTION, userId, abilityInfo, extensionAbilityInfo)) {
1433         HILOG_ERROR("Failed to ImplicitQueryInfoByPriority for publishing form");
1434         return ERR_APPEXECFWK_FORM_GET_HOST_FAILED;
1435     }
1436 
1437     if (abilityInfo.name.empty() && extensionAbilityInfo.name.empty()) {
1438         HILOG_ERROR("Query highest priority ability failed, no form host ability found.");
1439         return ERR_APPEXECFWK_FORM_GET_HOST_FAILED;
1440     }
1441 
1442     if (!abilityInfo.name.empty()) {
1443         /* highest priority ability */
1444         HILOG_INFO("Query highest priority ability success. bundleName: %{public}s, ability:%{public}s",
1445             abilityInfo.bundleName.c_str(), abilityInfo.name.c_str());
1446         want.SetParam(Constants::PARAM_BUNDLE_NAME_KEY, abilityInfo.bundleName);
1447         want.SetParam(Constants::PARAM_ABILITY_NAME_KEY, abilityInfo.name);
1448     } else {
1449         /* highest priority extension ability */
1450         HILOG_INFO("Query highest priority extension ability success. bundleName: %{public}s, ability:%{public}s",
1451             extensionAbilityInfo.bundleName.c_str(), extensionAbilityInfo.name.c_str());
1452         want.SetParam(Constants::PARAM_BUNDLE_NAME_KEY, extensionAbilityInfo.bundleName);
1453         want.SetParam(Constants::PARAM_ABILITY_NAME_KEY, extensionAbilityInfo.name);
1454     }
1455     want.SetParam(Constants::PARAM_FORM_USER_ID, userId);
1456     want.SetAction(Constants::FORM_PUBLISH_ACTION);
1457     return ERR_OK;
1458 }
1459 
RequestPublishFormToHost(Want & want)1460 ErrCode FormMgrAdapter::RequestPublishFormToHost(Want &want)
1461 {
1462     Want wantToHost;
1463     ElementName elementName = want.GetElement();
1464     wantToHost.SetParam(Constants::PARAM_BUNDLE_NAME_KEY, elementName.GetBundleName());
1465     wantToHost.SetParam(Constants::PARAM_ABILITY_NAME_KEY, elementName.GetAbilityName());
1466     std::string strFormId = want.GetStringParam(Constants::PARAM_FORM_IDENTITY_KEY);
1467     wantToHost.SetParam(Constants::PARAM_FORM_IDENTITY_KEY, strFormId);
1468     std::string formName = want.GetStringParam(Constants::PARAM_FORM_NAME_KEY);
1469     wantToHost.SetParam(Constants::PARAM_FORM_NAME_KEY, formName);
1470     std::string moduleName = want.GetStringParam(Constants::PARAM_MODULE_NAME_KEY);
1471     wantToHost.SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName);
1472     int32_t dimensionId = want.GetIntParam(Constants::PARAM_FORM_DIMENSION_KEY, 0);
1473     wantToHost.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, dimensionId);
1474     bool tempFormFlag = want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false);
1475     wantToHost.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlag);
1476     std::string bundleName = want.GetStringParam(Constants::PARAM_BUNDLE_NAME_KEY);
1477     std::string abilityName = want.GetStringParam(Constants::PARAM_ABILITY_NAME_KEY);
1478     wantToHost.SetElementName(bundleName, abilityName);
1479     int32_t userId = want.GetIntParam(Constants::PARAM_FORM_USER_ID, -1);
1480     wantToHost.SetAction(Constants::FORM_PUBLISH_ACTION);
1481 
1482     return FormAmsHelper::GetInstance().StartAbility(wantToHost, userId);
1483 }
1484 
RequestPublishForm(Want & want,bool withFormBindingData,std::unique_ptr<FormProviderData> & formBindingData,int64_t & formId)1485 ErrCode FormMgrAdapter::RequestPublishForm(Want &want, bool withFormBindingData,
1486     std::unique_ptr<FormProviderData> &formBindingData, int64_t &formId)
1487 {
1488     HILOG_INFO("%{public}s called.", __func__);
1489     ErrCode errCode = CheckPublishForm(want);
1490     if (errCode != ERR_OK) {
1491         return errCode;
1492     }
1493 
1494     errCode = QueryPublishFormToHost(want);
1495     if (errCode != ERR_OK) {
1496         return errCode;
1497     }
1498 
1499     // generate formId
1500     formId = FormDataMgr::GetInstance().GenerateFormId();
1501     if (formId < 0) {
1502         HILOG_ERROR("%{public}s fail, generateFormId no invalid formId", __func__);
1503         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1504     }
1505     HILOG_DEBUG("formId:%{public}" PRId64 "", formId);
1506     std::string strFormId = std::to_string(formId);
1507     want.SetParam(Constants::PARAM_FORM_IDENTITY_KEY, strFormId);
1508 
1509     if (withFormBindingData) {
1510         errCode = FormDataMgr::GetInstance().AddRequestPublishFormInfo(formId, want, formBindingData);
1511     } else {
1512         std::unique_ptr<FormProviderData> noFormBindingData = nullptr;
1513         errCode = FormDataMgr::GetInstance().AddRequestPublishFormInfo(formId, want, noFormBindingData);
1514     }
1515     if (errCode != ERR_OK) {
1516         return errCode;
1517     }
1518 
1519     errCode = RequestPublishFormToHost(want);
1520     if (errCode != ERR_OK) {
1521         FormDataMgr::GetInstance().RemoveRequestPublishFormInfo(formId);
1522     }
1523     return errCode;
1524 }
1525 
CheckAddRequestPublishForm(const Want & want,const Want & formProviderWant)1526 ErrCode FormMgrAdapter::CheckAddRequestPublishForm(const Want &want, const Want &formProviderWant)
1527 {
1528     std::string bundleName = want.GetElement().GetBundleName();
1529     std::string bundleNameProvider = formProviderWant.GetElement().GetBundleName();
1530     if (bundleNameProvider != bundleName) {
1531         HILOG_ERROR("The bundleName is not match.");
1532         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1533     }
1534 
1535     std::string moduleName = want.GetStringParam(Constants::PARAM_MODULE_NAME_KEY);
1536     std::string moduleNameProvider = formProviderWant.GetStringParam(Constants::PARAM_MODULE_NAME_KEY);
1537     if (moduleNameProvider != moduleName) {
1538         HILOG_ERROR("The moduleName is not match.");
1539         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1540     }
1541 
1542     std::string abilityName = want.GetElement().GetAbilityName();
1543     std::string abilityNameProvider = formProviderWant.GetElement().GetAbilityName();
1544     if (abilityNameProvider != abilityName) {
1545         HILOG_ERROR("The abilityName is not match.");
1546         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1547     }
1548 
1549     std::string formName = want.GetStringParam(Constants::PARAM_FORM_NAME_KEY);
1550     std::string formNameProvider = formProviderWant.GetStringParam(Constants::PARAM_FORM_NAME_KEY);
1551     if (formNameProvider != formName) {
1552         HILOG_ERROR("The formName is not match.");
1553         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1554     }
1555 
1556     int32_t dimensionId = want.GetIntParam(Constants::PARAM_FORM_DIMENSION_KEY, 0);
1557     int32_t dimensionIdProvider = formProviderWant.GetIntParam(Constants::PARAM_FORM_DIMENSION_KEY, 0);
1558     if (dimensionIdProvider != dimensionId) {
1559         HILOG_ERROR("The dimensionId is not match.");
1560         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1561     }
1562 
1563     bool isTemporary = want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false);
1564     bool isTemporaryProvider = formProviderWant.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false);
1565     if (isTemporaryProvider != isTemporary) {
1566         HILOG_ERROR("The temporary is not match.");
1567         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1568     }
1569 
1570     int32_t callingUid = IPCSkeleton::GetCallingUid();
1571     ErrCode errCode = ERR_OK;
1572     if (isTemporary) {
1573         errCode = FormDataMgr::GetInstance().CheckTempEnoughForm();
1574     } else {
1575         int32_t currentUserId = GetCurrentUserId(callingUid);
1576         errCode = FormDataMgr::GetInstance().CheckEnoughForm(callingUid, currentUserId);
1577     }
1578     if (errCode != ERR_OK) {
1579         HILOG_ERROR("%{public}s fail, too much forms in system", __func__);
1580         return errCode;
1581     }
1582     return ERR_OK;
1583 }
1584 
AddRequestPublishForm(const FormItemInfo & formItemInfo,const Want & want,const sptr<IRemoteObject> & callerToken,FormJsInfo & formJsInfo)1585 ErrCode FormMgrAdapter::AddRequestPublishForm(const FormItemInfo &formItemInfo, const Want &want,
1586     const sptr<IRemoteObject> &callerToken, FormJsInfo &formJsInfo)
1587 {
1588     HILOG_INFO("Add request publish form.");
1589     Want formProviderWant;
1590     std::unique_ptr<FormProviderData> formProviderData = nullptr;
1591     auto formId = formItemInfo.GetFormId();
1592     ErrCode errCode = FormDataMgr::GetInstance().GetRequestPublishFormInfo(formId, formProviderWant, formProviderData);
1593     if (errCode != ERR_OK) {
1594         HILOG_ERROR("Failed to get request publish form");
1595         return errCode;
1596     }
1597 
1598     errCode = CheckAddRequestPublishForm(want, formProviderWant);
1599     if (errCode != ERR_OK) {
1600         return errCode;
1601     }
1602 
1603     int32_t callingUid = IPCSkeleton::GetCallingUid();
1604     if (!FormDataMgr::GetInstance().AllotFormHostRecord(formItemInfo, callerToken, formId, callingUid)) {
1605         HILOG_ERROR("%{public}s fail, AllotFormHostRecord failed when no matched formRecord", __func__);
1606         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1607     }
1608 
1609     // get current userId
1610     int32_t currentUserId = GetCurrentUserId(callingUid);
1611     // allot form record
1612     FormRecord formRecord = FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid, currentUserId);
1613     if (formProviderData != nullptr) {
1614         formRecord.formProviderInfo.SetFormData(*formProviderData);
1615     }
1616     FormRenderMgr::GetInstance().RenderForm(formRecord, want.GetParams()); // render for arkTs form
1617 
1618     // create form info for js
1619     FormDataMgr::GetInstance().CreateFormJsInfo(formId, formRecord, formJsInfo);
1620     if (formProviderData != nullptr) {
1621         formJsInfo.formData = formProviderData->GetDataString();
1622         formJsInfo.formProviderData = *formProviderData;
1623         if (formProviderData->NeedCache()) {
1624             HILOG_INFO("%{public}s, data is less than 1k, cache data.", __func__);
1625             FormCacheMgr::GetInstance().AddData(formId, formJsInfo.formData);
1626         }
1627     }
1628     // storage info
1629     if (!formItemInfo.IsTemporaryForm()) {
1630         if (ErrCode errorCode = FormDbCache::GetInstance().UpdateDBRecord(formId, formRecord);
1631             errorCode != ERR_OK) {
1632             HILOG_ERROR("%{public}s fail, UpdateDBRecord failed", __func__);
1633             return errorCode;
1634         }
1635     }
1636 
1637     // start update timer
1638     return AddFormTimer(formRecord);
1639 }
1640 
1641 /**
1642  * @brief get bundleName.
1643  * @param bundleName for output.
1644  * @return Returns true on success, others on failure.
1645  */
GetBundleName(std::string & bundleName)1646 bool FormMgrAdapter::GetBundleName(std::string &bundleName)
1647 {
1648     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1649     if (iBundleMgr == nullptr) {
1650         HILOG_ERROR("%{public}s, failed to get IBundleMgr.", __func__);
1651         return false;
1652     }
1653 
1654     int uid = IPCSkeleton::GetCallingUid();
1655     if (!IN_PROCESS_CALL(iBundleMgr->CheckIsSystemAppByUid(uid))) {
1656         HILOG_ERROR("%{public}s fail, form is not system app. uid:%{public}d", __func__, uid);
1657         return false;
1658     }
1659 
1660     bool result = IN_PROCESS_CALL(iBundleMgr->GetBundleNameForUid(uid, bundleName));
1661     if (!result || bundleName.empty()) {
1662         HILOG_ERROR("%{public}s failed, cannot get bundle name by uid:%{public}d", __func__, uid);
1663         return false;
1664     }
1665     return true;
1666 }
1667 
1668 /**
1669  * @brief set next refresh time locked.
1670  * @param formId The form's id.
1671  * @param nextTime next refresh time.
1672  * @param userId User ID.
1673  * @return Returns ERR_OK on success, others on failure.
1674  */
SetNextRefreshTimeLocked(const int64_t formId,const int64_t nextTime,const int32_t userId)1675 int FormMgrAdapter::SetNextRefreshTimeLocked(const int64_t formId, const int64_t nextTime, const int32_t userId)
1676 {
1677     HILOG_ERROR("SetNextRefreshTimeLocked.");
1678     int32_t timerRefreshedCount = FormTimerMgr::GetInstance().GetRefreshCount(formId);
1679     if (timerRefreshedCount >= Constants::LIMIT_COUNT) {
1680         HILOG_ERROR("%{public}s, already refresh times:%{public}d", __func__, timerRefreshedCount);
1681         FormTimerMgr::GetInstance().MarkRemind(formId);
1682         return ERR_APPEXECFWK_FORM_MAX_REFRESH;
1683     }
1684 
1685     if (!FormTimerMgr::GetInstance().SetNextRefreshTime(formId, nextTime * Constants::SEC_PER_MIN, userId)) {
1686         HILOG_ERROR("%{public}s failed", __func__);
1687         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1688     }
1689 
1690     return ERR_OK;
1691 }
1692 
1693 /**
1694  * @brief set next refresh time locked.
1695  * @param formId The form's id.
1696  * @param bundleName Provider ability bundleName.
1697  * @return Returns true or false.
1698  */
IsUpdateValid(const int64_t formId,const std::string & bundleName)1699 bool FormMgrAdapter::IsUpdateValid(const int64_t formId, const std::string &bundleName)
1700 {
1701     if (formId <= 0 || bundleName.empty()) {
1702         return false;
1703     }
1704     return true;
1705 }
1706 
1707 /**
1708  * @brief enable update form.
1709  * @param formIDs The id of the forms.
1710  * @param callerToken Caller ability token.
1711  * @return Returns ERR_OK on success, others on failure.
1712  */
EnableUpdateForm(const std::vector<int64_t> formIDs,const sptr<IRemoteObject> & callerToken)1713 int FormMgrAdapter::EnableUpdateForm(const std::vector<int64_t> formIDs, const sptr<IRemoteObject> &callerToken)
1714 {
1715     HILOG_INFO("enableUpdateForm");
1716     return HandleUpdateFormFlag(formIDs, callerToken, true, false);
1717 }
1718 
1719 /**
1720  * @brief disable update form.
1721  * @param formIDs The id of the forms.
1722  * @param callerToken Caller ability token.
1723  * @return Returns ERR_OK on success, others on failure.
1724  */
DisableUpdateForm(const std::vector<int64_t> formIDs,const sptr<IRemoteObject> & callerToken)1725 int FormMgrAdapter::DisableUpdateForm(const std::vector<int64_t> formIDs, const sptr<IRemoteObject> &callerToken)
1726 {
1727     HILOG_INFO("disableUpdateForm");
1728     return HandleUpdateFormFlag(formIDs, callerToken, false, false);
1729 }
1730 
1731 /**
1732  * @brief Process js message event.
1733  * @param formId Indicates the unique id of form.
1734  * @param want information passed to supplier.
1735  * @param callerToken Caller ability token.
1736  * @return Returns true if execute success, false otherwise.
1737  */
MessageEvent(const int64_t formId,const Want & want,const sptr<IRemoteObject> & callerToken)1738 int FormMgrAdapter::MessageEvent(const int64_t formId, const Want &want, const sptr<IRemoteObject> &callerToken)
1739 {
1740     HILOG_INFO("%{public}s called.", __func__);
1741     if (formId <= 0) {
1742         HILOG_ERROR("%{public}s form formId is invalid", __func__);
1743         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1744     }
1745 
1746     if (callerToken == nullptr) {
1747         HILOG_ERROR("%{public}s failed, callerToken can not be NULL", __func__);
1748         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1749     }
1750 
1751     if (!want.HasParameter(Constants::PARAM_MESSAGE_KEY)) {
1752         HILOG_ERROR("%{public}s failed, message info is not exist", __func__);
1753         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1754     }
1755 
1756     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
1757     FormRecord record;
1758     bool bGetRecord = FormDataMgr::GetInstance().GetFormRecord(matchedFormId, record);
1759     if (!bGetRecord) {
1760         HILOG_ERROR("%{public}s fail, not exist such form:%{public}" PRId64 "", __func__, matchedFormId);
1761         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
1762     }
1763 
1764     FormHostRecord formHostRecord;
1765     bool isHostExist = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord);
1766     if (!isHostExist) {
1767         HILOG_ERROR("%{public}s failed, cannot find target client.", __func__);
1768         return ERR_APPEXECFWK_FORM_COMMON_CODE;
1769     }
1770 
1771     if (!formHostRecord.Contains(matchedFormId)) {
1772         HILOG_ERROR("%{public}s failed, form is not self-owned.", __func__);
1773         return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF;
1774     }
1775 
1776     auto errCode = FormProviderMgr::GetInstance().MessageEvent(matchedFormId, record, want);
1777     if (errCode != ERR_OK) {
1778         return errCode;
1779     }
1780     HILOG_INFO("%{public}s, find target client.", __func__);
1781 
1782 #ifdef DEVICE_USAGE_STATISTICS_ENABLE
1783     if (!FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) {
1784         int callingUid = IPCSkeleton::GetCallingUid();
1785         int32_t userId = GetCurrentUserId(callingUid);
1786         DeviceUsageStats::BundleActiveEvent event(record.bundleName, record.moduleName, record.formName,
1787             record.specification, record.formId, DeviceUsageStats::BundleActiveEvent::FORM_IS_CLICKED);
1788         DeviceUsageStats::BundleActiveClient::GetInstance().ReportEvent(event, userId);
1789     }
1790 #endif
1791     return ERR_OK;
1792 }
1793 
1794 /**
1795  * @brief Process js router event.
1796  * @param formId Indicates the unique id of form.
1797  * @param want the want of the ability to start.
1798  * @param callerToken Caller ability token.
1799  * @return Returns true if execute success, false otherwise.
1800  */
RouterEvent(const int64_t formId,Want & want,const sptr<IRemoteObject> & callerToken)1801 int FormMgrAdapter::RouterEvent(const int64_t formId, Want &want, const sptr<IRemoteObject> &callerToken)
1802 {
1803     HILOG_INFO("%{public}s called.", __func__);
1804     if (formId <= 0) {
1805         HILOG_ERROR("%{public}s form formId or bundleName is invalid", __func__);
1806         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1807     }
1808 
1809     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
1810     FormRecord record;
1811     bool bGetRecord = FormDataMgr::GetInstance().GetFormRecord(matchedFormId, record);
1812     if (!bGetRecord) {
1813         HILOG_ERROR("%{public}s fail, not exist such form:%{public}" PRId64 "", __func__, matchedFormId);
1814         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
1815     }
1816 
1817     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1818     if (iBundleMgr == nullptr) {
1819         HILOG_ERROR("%{public}s fail, failed to get IBundleMgr.", __func__);
1820         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
1821     }
1822 
1823     if (record.bundleName != want.GetBundle()) {
1824         if (!CheckIsSystemAppByBundleName(iBundleMgr, record.bundleName)) {
1825             HILOG_WARN("Only system apps can launch the ability of the other apps.");
1826             want.SetBundle(record.bundleName);
1827         }
1828     }
1829 
1830     want.SetParam(Constants::PARAM_FORM_ID, formId);
1831     want.SetParam(Constants::PARAM_FORM_IDENTITY_KEY, formId);
1832     int32_t result = FormAmsHelper::GetInstance().GetAbilityManager()->StartAbility(want, callerToken);
1833     if (result != ERR_OK && result != START_ABILITY_WAITING) {
1834         HILOG_ERROR("Failed to StartAbility, result: %{public}d.", result);
1835         return result;
1836     }
1837 
1838 #ifdef DEVICE_USAGE_STATISTICS_ENABLE
1839     if (!FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) {
1840         int32_t callingUid = IPCSkeleton::GetCallingUid();
1841         int32_t userId = GetCurrentUserId(callingUid);
1842         DeviceUsageStats::BundleActiveEvent event(record.bundleName, record.moduleName, record.formName,
1843             record.specification, record.formId, DeviceUsageStats::BundleActiveEvent::FORM_IS_CLICKED);
1844         DeviceUsageStats::BundleActiveClient::GetInstance().ReportEvent(event, userId);
1845     }
1846 #endif
1847     return ERR_OK;
1848 }
1849 
1850 /**
1851  * @brief Process background router event.
1852  * @param formId Indicates the unique id of form.
1853  * @param want the want of the ability to start.
1854  * @param callerToken Caller ability token.
1855  * @return Returns true if execute success, false otherwise.
1856  */
BackgroundEvent(const int64_t formId,Want & want,const sptr<IRemoteObject> & callerToken)1857 int FormMgrAdapter::BackgroundEvent(const int64_t formId, Want &want, const sptr<IRemoteObject> &callerToken)
1858 {
1859     HILOG_INFO("%{public}s called.", __func__);
1860     if (formId <= 0) {
1861         HILOG_ERROR("%{public}s form formId or bundleName is invalid", __func__);
1862         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1863     }
1864 
1865     int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
1866     FormRecord record;
1867     bool bGetRecord = FormDataMgr::GetInstance().GetFormRecord(matchedFormId, record);
1868     if (!bGetRecord) {
1869         HILOG_ERROR("%{public}s fail, not exist such form:%{public}" PRId64 "", __func__, matchedFormId);
1870         return ERR_APPEXECFWK_FORM_NOT_EXIST_ID;
1871     }
1872 
1873     sptr<IBundleMgr> iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr();
1874     if (iBundleMgr == nullptr) {
1875         HILOG_ERROR("%{public}s fail, failed to get IBundleMgr.", __func__);
1876         return ERR_APPEXECFWK_FORM_GET_BMS_FAILED;
1877     }
1878 
1879     if (want.GetBundle().empty() || record.bundleName != want.GetBundle()) {
1880         HILOG_DEBUG("The parameter contains the wrong bundleName or the empty bundleName");
1881         want.SetBundle(record.bundleName);
1882     }
1883 
1884     if (!CheckKeepBackgroundRunningPermission(iBundleMgr, record.bundleName)) {
1885         HILOG_ERROR("The app does not have permission for keeping background running.");
1886         return ERR_APPEXECFWK_FORM_PERMISSION_DENY;
1887     }
1888 
1889     std::string params = want.GetStringParam(Constants::FORM_CALL_EVENT_PARAMS);
1890     nlohmann::json jsonObject = nlohmann::json::parse(params, nullptr, false);
1891     if (jsonObject.is_discarded()) {
1892         HILOG_ERROR("failed to parse jsonDataString: %{public}s.", params.c_str());
1893         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1894     }
1895     if (!jsonObject.contains(Constants::PARAM_FORM_CALL_EVENT_METHOD_KEY) ||
1896         !jsonObject.at(Constants::PARAM_FORM_CALL_EVENT_METHOD_KEY).is_string()) {
1897         HILOG_ERROR("failed to get method from params");
1898         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1899     }
1900     sptr<IAbilityConnection> formBackgroundConnection = new (std::nothrow) FormBackgroundConnection(formId, want.GetBundle(),
1901         want.GetElement().GetAbilityName(), jsonObject[Constants::PARAM_FORM_CALL_EVENT_METHOD_KEY].get<std::string>(), params);
1902     if (formBackgroundConnection == nullptr) {
1903         HILOG_ERROR("formBackgroundConnection is null.");
1904         return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED;
1905     }
1906     want.SetParam(Constants::PARAM_FORM_ID, formId);
1907     want.SetParam(Constants::PARAM_FORM_IDENTITY_KEY, formId);
1908     int32_t result = IN_PROCESS_CALL(FormAmsHelper::GetInstance().GetAbilityManager()->StartAbilityByCall(want,
1909         formBackgroundConnection, callerToken));
1910     if (result != ERR_OK) {
1911         HILOG_ERROR("Failed to StartAbilityByCall, result: %{public}d.", result);
1912         return result;
1913     }
1914     return ERR_OK;
1915 }
1916 
HandleUpdateFormFlag(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,bool flag,bool isOnlyEnableUpdate)1917 ErrCode FormMgrAdapter::HandleUpdateFormFlag(const std::vector<int64_t> &formIds,
1918     const sptr<IRemoteObject> &callerToken, bool flag, bool isOnlyEnableUpdate)
1919 {
1920     HILOG_INFO("%{public}s called.", __func__);
1921     if (formIds.empty() || callerToken == nullptr) {
1922         HILOG_ERROR("%{public}s, invalid param", __func__);
1923         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
1924     }
1925     std::vector<int64_t> refreshForms;
1926     int errCode = FormDataMgr::GetInstance().UpdateHostFormFlag(formIds, callerToken,
1927         flag, isOnlyEnableUpdate, refreshForms);
1928     if (errCode == ERR_OK && !refreshForms.empty()) {
1929         for (const int64_t id : refreshForms) {
1930             HILOG_INFO("%{public}s, formRecord need refresh: %{public}" PRId64 "", __func__, id);
1931             Want want;
1932             int callingUid = IPCSkeleton::GetCallingUid();
1933             int32_t userId = GetCurrentUserId(callingUid);
1934             want.SetParam(Constants::PARAM_FORM_USER_ID, userId);
1935             FormProviderMgr::GetInstance().RefreshForm(id, want, false);
1936         }
1937     }
1938     return errCode;
1939 }
1940 
1941 /**
1942  * @brief check form cached.
1943  * @param record Form information.
1944  * @return Returns true on cached, false on not.
1945  */
IsFormCached(const FormRecord record)1946 bool FormMgrAdapter::IsFormCached(const FormRecord record)
1947 {
1948     if (record.versionUpgrade) {
1949         return false;
1950     }
1951     return true;
1952 }
1953 
AcquireProviderFormInfo(const int64_t formId,const Want & want,const sptr<IRemoteObject> & remoteObject)1954 void FormMgrAdapter::AcquireProviderFormInfo(const int64_t formId, const Want &want,
1955     const sptr<IRemoteObject> &remoteObject)
1956 {
1957     HILOG_INFO("%{public}s called.", __func__);
1958     auto connectId = want.GetIntParam(Constants::FORM_CONNECT_ID, 0);
1959     sptr<IFormProvider> formProviderProxy = iface_cast<IFormProvider>(remoteObject);
1960     if (formProviderProxy == nullptr) {
1961         FormSupplyCallback::GetInstance()->RemoveConnection(connectId);
1962         HILOG_ERROR("%{public}s fail, Failed to get formProviderProxy", __func__);
1963         return;
1964     }
1965     FormRecord formRecord;
1966     FormDataMgr::GetInstance().GetFormRecord(formId, formRecord);
1967     FormJsInfo formJsInfo;
1968     FormDataMgr::GetInstance().CreateFormJsInfo(formId, formRecord, formJsInfo);
1969     int error = formProviderProxy->AcquireProviderFormInfo(formJsInfo, want, FormSupplyCallback::GetInstance());
1970     if (error != ERR_OK) {
1971         FormSupplyCallback::GetInstance()->RemoveConnection(connectId);
1972         HILOG_ERROR("%{public}s fail, Failed to get acquire provider form info", __func__);
1973     }
1974 }
1975 
1976 /**
1977  * @brief Notify form provider for delete form.
1978  *
1979  * @param formId The Id of the from.
1980  * @param want The want of the form.
1981  * @param remoteObject Form provider proxy object.
1982  */
NotifyFormDelete(const int64_t formId,const Want & want,const sptr<IRemoteObject> & remoteObject)1983 void FormMgrAdapter::NotifyFormDelete(const int64_t formId, const Want &want, const sptr<IRemoteObject> &remoteObject)
1984 {
1985     HILOG_INFO("%{public}s called.", __func__);
1986     auto connectId = want.GetIntParam(Constants::FORM_CONNECT_ID, 0);
1987     sptr<IFormProvider> formProviderProxy = iface_cast<IFormProvider>(remoteObject);
1988     if (formProviderProxy == nullptr) {
1989         HILOG_ERROR("%{public}s fail, Failed to get formProviderProxy", __func__);
1990         FormSupplyCallback::GetInstance()->RemoveConnection(connectId);
1991         return;
1992     }
1993     int error = formProviderProxy->NotifyFormDelete(formId, want, FormSupplyCallback::GetInstance());
1994     if (error != ERR_OK) {
1995         HILOG_ERROR("%{public}s fail, Failed to NotifyFormDelete", __func__);
1996         FormSupplyCallback::GetInstance()->RemoveConnection(connectId);
1997     }
1998 }
1999 
2000 /**
2001  * @brief Create eventMaps for event notify.
2002  *
2003  * @param matchedFormId The Id of the form
2004  * @param formRecord Form storage information
2005  * @param eventMaps eventMaps for event notify
2006  * @return Returns true on success, false on failure.
2007  */
CreateHandleEventMap(const int64_t matchedFormId,const FormRecord & formRecord,std::map<std::string,std::vector<int64_t>> & eventMaps)2008 bool FormMgrAdapter::CreateHandleEventMap(const int64_t matchedFormId, const FormRecord &formRecord,
2009     std::map<std::string, std::vector<int64_t>> &eventMaps)
2010 {
2011     if (!formRecord.formVisibleNotify) {
2012         HILOG_WARN("%{public}s fail, the config 'formVisibleNotify' is false, formId:%{public}" PRId64 ".",
2013             __func__, matchedFormId);
2014         return false;
2015     }
2016 
2017     std::string providerKey = formRecord.bundleName + Constants::NAME_DELIMITER + formRecord.abilityName;
2018     auto iter = eventMaps.find(providerKey);
2019     if (iter == eventMaps.end()) {
2020         std::vector<int64_t> formEventsByProvider {matchedFormId};
2021         eventMaps.insert(std::make_pair(providerKey, formEventsByProvider));
2022     } else {
2023         iter->second.emplace_back(matchedFormId);
2024     }
2025     return true;
2026 }
2027 /**
2028  * @brief Update provider info to host
2029  *
2030  * @param matchedFormId The Id of the form
2031  * @param callerToken Caller ability token.
2032  * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE.
2033  * @param formRecord Form storage information
2034  * @return Returns true on success, false on failure.
2035  */
UpdateProviderInfoToHost(const int64_t matchedFormId,const sptr<IRemoteObject> & callerToken,const int32_t formVisibleType,FormRecord & formRecord)2036 bool FormMgrAdapter::UpdateProviderInfoToHost(const int64_t matchedFormId, const sptr<IRemoteObject> &callerToken,
2037     const int32_t formVisibleType, FormRecord &formRecord)
2038 {
2039     if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) {
2040         HILOG_WARN("%{public}s fail, not exist such form, formId:%{public}" PRId64 ".", __func__, matchedFormId);
2041         return false;
2042     }
2043 
2044     FormHostRecord formHostRecord;
2045     bool hasFormHostRecord = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord);
2046     if (!(hasFormHostRecord && formHostRecord.Contains(matchedFormId))) {
2047         HILOG_WARN("%{public}s fail, form is not belong to self, formId:%{public}" PRId64 ".", __func__, matchedFormId);
2048         return false;
2049     }
2050 
2051     formRecord.formVisibleNotifyState = formVisibleType;
2052     if (!FormDataMgr::GetInstance().UpdateFormRecord(matchedFormId, formRecord)) {
2053         HILOG_WARN("%{public}s fail, set formVisibleNotifyState error, formId:%{public}" PRId64 ".",
2054         __func__, matchedFormId);
2055         return false;
2056     }
2057 
2058     // If the form need refresh flag is true and form visibleType is FORM_VISIBLE, refresh the form host.
2059     if (formRecord.needRefresh && formVisibleType == Constants::FORM_VISIBLE) {
2060         if (formRecord.isTimerRefresh) {
2061             Want want;
2062             int32_t userId = FormUtil::GetCurrentAccountId();
2063             want.SetParam(Constants::KEY_IS_TIMER, true);
2064             want.SetParam(Constants::KEY_TIMER_REFRESH, true);
2065             want.SetParam(Constants::PARAM_FORM_USER_ID, userId);
2066             FormProviderMgr::GetInstance().RefreshForm(formRecord.formId, want, false);
2067         } else {
2068             std::string cacheData;
2069             // If the form has business cache, refresh the form host.
2070             if (FormCacheMgr::GetInstance().GetData(matchedFormId, cacheData)) {
2071                 formRecord.formProviderInfo.SetFormDataString(cacheData);
2072                 formHostRecord.OnUpdate(matchedFormId, formRecord);
2073             }
2074         }
2075     }
2076     return true;
2077 }
2078 /**
2079  * @brief If the form provider is system app and the config item 'formVisibleNotify' is true,
2080  *        notify the form provider that the current form is visible.
2081  * @param iBundleMgr BundleManagerProxy
2082  * @param bundleName BundleName
2083  * @return Returns true if the form provider is system app, false if not.
2084  */
CheckIsSystemAppByBundleName(const sptr<IBundleMgr> & iBundleMgr,const std::string & bundleName)2085 bool FormMgrAdapter::CheckIsSystemAppByBundleName(const sptr<IBundleMgr> &iBundleMgr, const std::string &bundleName)
2086 {
2087     BundleInfo bundleInfo;
2088     if (IN_PROCESS_CALL(iBundleMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT,
2089         bundleInfo, FormUtil::GetCurrentAccountId()))) {
2090         HILOG_DEBUG("%{public}s, get bundle uid success", __func__);
2091         if (!IN_PROCESS_CALL(iBundleMgr->CheckIsSystemAppByUid(bundleInfo.uid))) {
2092             HILOG_WARN("%{public}s fail, form provider is not system app, bundleName: %{public}s",
2093                 __func__, bundleName.c_str());
2094             return false;
2095         }
2096     } else {
2097         HILOG_WARN("%{public}s fail, can not get bundleInfo's uid", __func__);
2098         return false;
2099     }
2100 
2101     return true;
2102 }
2103 
2104 /**
2105  * @brief if the ability have permission for keeping background running is true,
2106  * @param iBundleMgr BundleManagerProxy
2107  * @param bundleName BundleName
2108  * @return Returns true if the ability have permission for keeping background running, false if not.
2109  */
CheckKeepBackgroundRunningPermission(const sptr<IBundleMgr> & iBundleMgr,const std::string & bundleName)2110 bool FormMgrAdapter::CheckKeepBackgroundRunningPermission(const sptr<IBundleMgr> &iBundleMgr, const std::string &bundleName)
2111 {
2112     BundleInfo bundleInfo;
2113     if (FormBmsHelper::GetInstance().GetBundleInfoWithPermission(bundleName,
2114         FormUtil::GetCurrentAccountId(), bundleInfo)) {
2115         HILOG_DEBUG("%{public}s, get bundleInfo success", __func__);
2116         auto item = find(bundleInfo.reqPermissions.begin(), bundleInfo.reqPermissions.end(), Constants::PERMISSION_KEEP_BACKGROUND_RUNNING);
2117         if (item == bundleInfo.reqPermissions.end()) {
2118             return false;
2119         }
2120     } else {
2121         HILOG_WARN("%{public}s fail, can not get bundleInfo's uid", __func__);
2122         return false;
2123     }
2124 
2125     return true;
2126 }
2127 /**
2128  * @brief Get current user ID.
2129  * @param callingUid calling Uid.
2130  * @return Returns user ID.
2131  */
GetCurrentUserId(const int callingUid)2132 int32_t FormMgrAdapter::GetCurrentUserId(const int callingUid)
2133 {
2134     // get current userId
2135     int32_t userId = callingUid / CALLING_UID_TRANSFORM_DIVISOR;
2136     return userId;
2137 }
2138 
2139 /**
2140  * @brief Delete the invalid forms.
2141  * @param formIds Indicates the ID of the valid forms.
2142  * @param callerToken Caller ability token.
2143  * @param numFormsDeleted Returns the number of the deleted forms.
2144  * @return Returns ERR_OK on success, others on failure.
2145  */
DeleteInvalidForms(const std::vector<int64_t> & formIds,const sptr<IRemoteObject> & callerToken,int32_t & numFormsDeleted)2146 int FormMgrAdapter::DeleteInvalidForms(const std::vector<int64_t> &formIds,
2147     const sptr<IRemoteObject> &callerToken, int32_t &numFormsDeleted)
2148 {
2149     HILOG_INFO("%{public}s called.", __func__);
2150     if (callerToken == nullptr) {
2151         HILOG_ERROR("%{public}s, callerToken is nullptr", __func__);
2152         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
2153     }
2154 
2155     std::set<int64_t> matchedFormIds {};
2156     for (int64_t formId : formIds) {
2157         int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId);
2158         matchedFormIds.emplace(matchedFormId);
2159         HILOG_DEBUG("valid formId, matchedFormIds: %{public}" PRId64 "", formId);
2160     }
2161     int32_t callingUid = IPCSkeleton::GetCallingUid();
2162     std::map<int64_t, bool> removedFormsMap {};
2163     int32_t userId = GetCurrentUserId(callingUid);
2164 
2165     // delete invalid DB form record
2166     FormDbCache::GetInstance().DeleteInvalidDBForms(userId, callingUid, matchedFormIds, removedFormsMap);
2167     // delete invalid temp form record
2168     FormDataMgr::GetInstance().DeleteInvalidTempForms(userId, callingUid, matchedFormIds, removedFormsMap);
2169 
2170     if (!removedFormsMap.empty()) {
2171         FormDataMgr::GetInstance().ClearHostDataByInvalidForms(callingUid, removedFormsMap);
2172         // delete forms timer
2173         for (const auto &removedForm : removedFormsMap) {
2174             if (removedForm.second) {
2175                 FormTimerMgr::GetInstance().RemoveFormTimer(removedForm.first);
2176             }
2177         }
2178     }
2179 
2180     std::string bundleName;
2181     if (GetBundleName(bundleName)) {
2182         // delete invalid publish form data
2183         FormDataMgr::GetInstance().DeleteInvalidPublishForms(userId, bundleName, matchedFormIds);
2184     }
2185 
2186     numFormsDeleted = static_cast<int32_t>(removedFormsMap.size());
2187     HILOG_INFO("%{public}s done, %{public}d forms deleted.", __func__, numFormsDeleted);
2188     return ERR_OK;
2189 }
2190 
2191 /**
2192  * @brief AcquireFormState want check.
2193  * @param bundleName The bundle name of the form.
2194  * @param abilityName The ability name of the form.
2195  * @param want The want of the form.
2196  * @param provider the provider info.
2197  * @return Returns ERR_OK on success, others on failure.
2198  */
AcquireFormStateCheck(const std::string & bundleName,const std::string & abilityName,const Want & want,std::string & provider)2199 ErrCode FormMgrAdapter::AcquireFormStateCheck(const std::string &bundleName,
2200     const std::string &abilityName, const Want &want, std::string &provider)
2201 {
2202     if (bundleName.empty() || abilityName.empty()) {
2203         HILOG_ERROR("%{public}s error, bundleName or abilityName is empty.", __func__);
2204         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
2205     }
2206 
2207     std::string moduleName = want.GetStringParam(AppExecFwk::Constants::PARAM_MODULE_NAME_KEY);
2208     std::string formName = want.GetStringParam(AppExecFwk::Constants::PARAM_FORM_NAME_KEY);
2209     int32_t dimensionId = want.GetIntParam(AppExecFwk::Constants::PARAM_FORM_DIMENSION_KEY, 1);
2210 
2211     if (moduleName.empty() || formName.empty()) {
2212         HILOG_ERROR("%{public}s error, moduleName or formName is empty.", __func__);
2213         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
2214     }
2215 
2216     std::vector<FormInfo> formInfos {};
2217     ErrCode errCode = FormInfoMgr::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos);
2218     if (errCode != ERR_OK) {
2219         HILOG_ERROR("%{public}s error, failed to get forms info.", __func__);
2220         return errCode;
2221     }
2222 
2223     bool found = false;
2224     for (auto &formInfo : formInfos) {
2225         if ((formInfo.abilityName == abilityName) && (formInfo.name == formName) &&
2226             (IsDimensionValid(formInfo, dimensionId))) {
2227             found = true;
2228             HILOG_INFO("%{public}s form info found.", __func__);
2229             break;
2230         }
2231     }
2232     if (!found) {
2233         HILOG_INFO("failed to find match form info.");
2234         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
2235     }
2236 
2237     int32_t callingUid = IPCSkeleton::GetCallingUid();
2238     const std::string doubleColon = "::";
2239     provider.append(bundleName).append(doubleColon).append(abilityName).append(doubleColon)
2240         .append(moduleName).append(doubleColon).append(formName).append(doubleColon)
2241         .append(std::to_string(dimensionId)).append(doubleColon).append(std::to_string(callingUid));
2242     return ERR_OK;
2243 }
2244 
2245 /**
2246  * @brief Acquire form state info by passing a set of parameters (using Want) to the form provider.
2247  * @param want Indicates a set of parameters to be transparently passed to the form provider.
2248  * @param callerToken Caller ability token.
2249  * @param stateInfo Returns the form's state info of the specify.
2250  * @return Returns ERR_OK on success, others on failure.
2251  */
AcquireFormState(const Want & want,const sptr<IRemoteObject> & callerToken,FormStateInfo & stateInfo)2252 int FormMgrAdapter::AcquireFormState(const Want &want, const sptr<IRemoteObject> &callerToken,
2253                                      FormStateInfo &stateInfo)
2254 {
2255     if (callerToken == nullptr) {
2256         HILOG_ERROR("%{public}s, callerToken is nullptr", __func__);
2257         return ERR_APPEXECFWK_FORM_INVALID_PARAM;
2258     }
2259     std::string bundleName = want.GetElement().GetBundleName();
2260     std::string abilityName = want.GetElement().GetAbilityName();
2261 
2262     std::string provider;
2263     ErrCode errCode = AcquireFormStateCheck(bundleName, abilityName, want, provider);
2264     if (errCode != ERR_OK) {
2265         return errCode;
2266     }
2267 
2268     int32_t callingUid = IPCSkeleton::GetCallingUid();
2269     FormItemInfo info;
2270     FormDataMgr::GetInstance().CreateFormStateRecord(provider, info, callerToken, callingUid);
2271 
2272     HILOG_DEBUG("bundleName:%{public}s, abilityName:%{public}s", bundleName.c_str(), abilityName.c_str());
2273     sptr<IAbilityConnection> connection =
2274         new (std::nothrow) FormAcquireStateConnection(bundleName, abilityName, want, provider);
2275     if (connection == nullptr) {
2276         HILOG_ERROR("failed to create FormAcquireStateConnection.");
2277         return ERR_APPEXECFWK_FORM_COMMON_CODE;
2278     }
2279     Want targetWant;
2280     targetWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED);
2281     targetWant.SetElementName(bundleName, abilityName);
2282     ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(targetWant, connection);
2283     if (errorCode != ERR_OK) {
2284         HILOG_ERROR("%{public}s, ConnectServiceAbility failed.", __func__);
2285         return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED;
2286     }
2287     stateInfo.state = FormState::DEFAULT;
2288     return ERR_OK;
2289 }
2290 
2291 /**
2292  * @brief Notify the form is visible or not.
2293  * @param formIds Indicates the ID of the forms.
2294  * @param isVisible Visible or not.
2295  * @param callerToken Host client.
2296  * @return Returns ERR_OK on success, others on failure.
2297  */
NotifyFormsVisible(const std::vector<int64_t> & formIds,bool isVisible,const sptr<IRemoteObject> & callerToken)2298 int FormMgrAdapter::NotifyFormsVisible(const std::vector<int64_t> &formIds,
2299     bool isVisible, const sptr<IRemoteObject> &callerToken)
2300 {
2301     HILOG_INFO("%{public}s, isVisible: %{public}d.", __func__, isVisible);
2302     return FormDataMgr::GetInstance().NotifyFormsVisible(formIds, isVisible, callerToken);
2303 }
2304 
2305 /**
2306  * @brief Notify the form is enable to be updated or not.
2307  * @param formIds Indicates the ID of the forms.
2308  * @param isEnableUpdate enable update or not.
2309  * @param callerToken Host client.
2310  * @return Returns ERR_OK on success, others on failure.
2311  */
NotifyFormsEnableUpdate(const std::vector<int64_t> & formIds,bool isEnableUpdate,const sptr<IRemoteObject> & callerToken)2312 int FormMgrAdapter::NotifyFormsEnableUpdate(const std::vector<int64_t> &formIds,
2313     bool isEnableUpdate, const sptr<IRemoteObject> &callerToken)
2314 {
2315     HILOG_INFO("%{public}s, isEnableUpdate: %{public}d.", __func__, isEnableUpdate);
2316     return HandleUpdateFormFlag(formIds, callerToken, isEnableUpdate, true);
2317 }
2318 
2319 /**
2320  * @brief Get All FormsInfo.
2321  * @param formInfos Return the forms' information of all forms provided.
2322  * @return Returns ERR_OK on success, others on failure.
2323  */
GetAllFormsInfo(std::vector<FormInfo> & formInfos)2324 int FormMgrAdapter::GetAllFormsInfo(std::vector<FormInfo> &formInfos)
2325 {
2326     return FormInfoMgr::GetInstance().GetAllFormsInfo(formInfos);
2327 }
2328 
2329 /**
2330  * @brief Get forms info by bundle name .
2331  * @param bundleName Application name.
2332  * @param formInfos Return the forms' information of the specify application name.
2333  * @return Returns ERR_OK on success, others on failure.
2334  */
GetFormsInfoByApp(const std::string & bundleName,std::vector<FormInfo> & formInfos)2335 int FormMgrAdapter::GetFormsInfoByApp(const std::string &bundleName, std::vector<FormInfo> &formInfos)
2336 {
2337     return FormInfoMgr::GetInstance().GetFormsInfoByBundle(bundleName, formInfos);
2338 }
2339 
2340 /**
2341  * @brief Get forms info by bundle name and module name.
2342  * @param bundleName bundle name.
2343  * @param moduleName Module name of hap.
2344  * @param formInfos Return the forms' information of the specify bundle name and module name.
2345  * @return Returns ERR_OK on success, others on failure.
2346  */
GetFormsInfoByModule(const std::string & bundleName,const std::string & moduleName,std::vector<FormInfo> & formInfos)2347 int FormMgrAdapter::GetFormsInfoByModule(const std::string &bundleName,
2348     const std::string &moduleName, std::vector<FormInfo> &formInfos)
2349 {
2350     return FormInfoMgr::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos);
2351 }
2352 
IsRequestPublishFormSupported()2353 bool FormMgrAdapter::IsRequestPublishFormSupported()
2354 {
2355     /* Query the highest priority ability or extension ability for publishing form */
2356     AppExecFwk::AbilityInfo abilityInfo;
2357     AppExecFwk::ExtensionAbilityInfo extensionAbilityInfo;
2358     int callingUid = IPCSkeleton::GetCallingUid();
2359     int32_t userId = GetCurrentUserId(callingUid);
2360     if (!FormBmsHelper::GetInstance().GetAbilityInfoByAction(
2361         Constants::FORM_PUBLISH_ACTION, userId, abilityInfo, extensionAbilityInfo)) {
2362         HILOG_ERROR("Failed to ImplicitQueryInfoByPriority for publishing form");
2363         return false;
2364     }
2365 
2366     if (abilityInfo.name.empty() && extensionAbilityInfo.name.empty()) {
2367         HILOG_ERROR("Query highest priority ability failed, no form host ability found.");
2368         return false;
2369     }
2370     return true;
2371 }
2372 
2373 /**
2374  * @brief check if the form host is system app
2375  * @param formRecord Form storage information
2376  * @return Returns true if the form host is system app, false if not.
2377  */
checkFormHostHasSaUid(const FormRecord & formRecord)2378 bool FormMgrAdapter::checkFormHostHasSaUid(const FormRecord &formRecord)
2379 {
2380     return std::find(formRecord.formUserUids.begin(), formRecord.formUserUids.end(),
2381         SYSTEM_UID) != formRecord.formUserUids.end();
2382 }
2383 } // namespace AppExecFwk
2384 } // namespace OHOS
2385