1/*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import edmEnterpriseDeviceManager from '@ohos.enterprise.adminManager';
17import router from '@ohos.router';
18import appDetailData from '../common/appManagement/appDetailData'
19import baseData from '../common/baseData';
20import entryComponent from './component/entryComponent'
21import headComponent from './component/headComponent';
22import logger from '../common/logger'
23import permissionListComponent from './component/permissionListComponent';
24import utils from '../common/utils'
25import { AppPermission, MyApplicationInfo } from '../common/myApplicationInfo'
26import Want from '@ohos.app.ability.Want';
27import adminManager from '@ohos.enterprise.adminManager';
28import { BusinessError } from '@ohos.base';
29import common from '@ohos.app.ability.common';
30
31let appInfo: MyApplicationInfo;
32let elementNameVal: Want;
33let isAdminTypeVal: adminManager.AdminType;
34let isActiveState: boolean;
35let enterInfo: adminManager.EnterpriseInfo;
36const TAG = 'ApplicationInfo';
37
38@Entry
39@Component
40struct ApplicationInfo {
41  @StorageLink('applicationInfo') applicationInfo: MyApplicationInfo = {
42    appIcon: '',
43    appTitle: '',
44    appBundleName: '',
45    appPermissionList: []
46  };
47  @State isShowActive: boolean = false;
48  @State isEnableButton: boolean = false;
49  @StorageLink('activeType') isAdminType: number = 0;
50  @State deviceAdminActive: string = '';
51  @State deviceAdminDisActive: string = '';
52  @State enterpriseName: string = '';
53  @State enterpriseDescription: string = '';
54  private storage = LocalStorage.getShared();
55
56  build() {
57    Column() {
58      Column() {
59        GridContainer({
60          columns: utils.isLargeDevice(),
61          sizeType: SizeType.Auto,
62          gutter: '12vp',
63          margin: '12vp'
64        }) {
65          Column() {
66            headComponent({ headName: $r('app.string.adminprovisioning') });
67
68            Row() {
69              entryComponent({
70                appIcon: this.applicationInfo.appIcon,
71                appTitle: this.applicationInfo.appTitle,
72              })
73            }
74
75            Column() {
76              Text(this.enterpriseName)
77                .height($r('app.float.wh_value_21'))
78                .fontColor($r('sys.color.ohos_id_color_text_primary'))
79                .fontSize($r('app.float.font_16'))
80                .fontWeight(FontWeight.Medium)
81                .textAlign(TextAlign.Start)
82                .maxLines(3)
83                .textOverflow({ overflow: TextOverflow.Ellipsis })
84                .margin({
85                  left: $r('app.float.wh_value_36'),
86                  top: $r('app.float.wh_value_12'),
87                });
88
89              Text(this.enterpriseDescription)
90                .height($r('app.float.wh_value_19'))
91                .fontColor($r('sys.color.ohos_id_color_text_secondary'))
92                .fontSize($r('app.float.font_14'))
93                .fontWeight(FontWeight.Regular)
94                .textAlign(TextAlign.Start)
95                .maxLines(3)
96                .textOverflow({ overflow: TextOverflow.Ellipsis })
97                .margin({
98                  left: $r('app.float.wh_value_36'),
99                  top: $r('app.float.wh_value_2'),
100                });
101            }
102            .width('100%')
103            .alignItems(HorizontalAlign.Start)
104            .align(Alignment.Start)
105
106            Column() {
107              Text(this.isShowActive ? this.deviceAdminActive : this.deviceAdminDisActive)
108                .fontColor($r('sys.color.ohos_id_color_text_primary'))
109                .fontSize($r('app.float.font_16'))
110                .fontWeight(FontWeight.Medium)
111                .textAlign(TextAlign.Start)
112                .maxLines(3)
113                .textOverflow({ overflow: TextOverflow.Ellipsis })
114                .margin({
115                  left: $r('app.float.wh_value_36'),
116                  top: $r('app.float.wh_value_24'),
117                });
118
119              List() {
120                ForEach(this.applicationInfo.appPermissionList, (item: AppPermission) => {
121                  ListItem() {
122                    permissionListComponent({
123                      permissionName: item.permissionLabel,
124                      permissionDescription: item.permissionDescription,
125                    });
126                  }
127                }, (item: AppPermission) => JSON.stringify(item));
128              }
129            }
130            .alignItems(HorizontalAlign.Start)
131            .align(Alignment.Start)
132          }
133          .useSizeType({
134            xs: { span: 8, offset: 0 }, sm: { span: 8, offset: 0 },
135            md: { span: 8, offset: 0 }, lg: { span: 8, offset: 2 }
136          })
137        }
138      }
139      .layoutWeight(1)
140
141      Column() {
142        GridContainer({
143          columns: utils.isLargeDevice(),
144          sizeType: SizeType.Auto,
145          gutter: '12vp',
146          margin: '12vp'
147        }) {
148          Row() {
149            Row()
150              .useSizeType({
151                xs: { span: 1, offset: 0 }, sm: { span: 1, offset: 0 },
152                md: { span: 1, offset: 0 }, lg: { span: 3, offset: 0 }
153              })
154
155            Button() {
156              Text(this.isShowActive ? $r('app.string.deActivate') : $r('app.string.activation'))
157                .opacity(this.isEnableButton ? 1 : 0.38)
158                .fontSize($r('sys.float.ohos_id_text_size_button1'))
159                .fontColor($r('sys.color.ohos_id_color_text_primary_activated'))
160            }
161            .enabled(this.isEnableButton)
162            .backgroundColor($r('sys.color.ohos_id_color_button_normal'))
163            .height($r('app.float.button_height'))
164            .margin({
165              right: $r('app.float.wh_value_6'),
166              bottom: $r('app.float.wh_value_24')
167            })
168            .onClick(() => {
169              logger.info(TAG, 'button active:' + this.isShowActive);
170              this.activateAdmin(this.isAdminType);
171            })
172            .useSizeType({
173              xs: { span: 3, offset: 1 }, sm: { span: 3, offset: 1 },
174              md: { span: 3, offset: 1 }, lg: { span: 3, offset: 3 }
175            })
176
177            Button() {
178              Text($r('app.string.cancel'))
179                .fontSize($r('sys.float.ohos_id_text_size_button1'))
180                .fontColor($r('sys.color.ohos_id_color_text_primary_activated'))
181            }
182            .backgroundColor($r('sys.color.ohos_id_color_button_normal'))
183            .height($r('app.float.button_height'))
184            .margin({
185              left: $r('app.float.wh_value_6'),
186              bottom: $r('app.float.wh_value_24')
187            })
188            .onClick(() => {
189              logger.info(TAG, 'button cancel in isShowActive:' + this.isShowActive);
190              appDetailData.terminateAbilityPage();
191            })
192            .useSizeType({
193              xs: { span: 3, offset: 4 }, sm: { span: 3, offset: 4 },
194              md: { span: 3, offset: 4 }, lg: { span: 3, offset: 6 }
195            })
196
197            Row()
198              .useSizeType({
199                xs: { span: 1, offset: 7 }, sm: { span: 1, offset: 7 },
200                md: { span: 1, offset: 7 }, lg: { span: 3, offset: 9 }
201              })
202          }
203          .justifyContent(FlexAlign.Center)
204        }
205      }.width('100%')
206    }
207    .height('100%')
208    .width('100%')
209    .backgroundColor($r('sys.color.ohos_id_color_sub_background'))
210  }
211
212  async aboutToAppear(): Promise<void> {
213    elementNameVal = {
214      abilityName: '',
215      bundleName: '',
216    };
217
218    enterInfo = {
219      name: '',
220      description: '',
221    };
222
223    isAdminTypeVal = 0;
224    logger.info(TAG, 'aboutToAppear in');
225    await this.getCheckAbilityList(this.applicationInfo, elementNameVal, isAdminTypeVal);
226    logger.info(TAG, 'aboutToAppear out');
227  }
228
229  aboutToDisappear(): void {
230    logger.info(TAG, 'aboutToDisappear');
231  }
232
233  onPageShow(): void {
234    logger.info(TAG, 'onPageShow in');
235    this.isAdminActive();
236    logger.info(TAG, 'onPageShow isActiveState =' + isActiveState);
237    if (!utils.isValid(isActiveState)) {
238      return;
239    }
240    this.isShowActive = isActiveState;
241    logger.info(TAG, 'onPageShow out');
242  }
243
244  onPageHide() {
245    logger.info(TAG, 'onPageHide');
246  }
247
248  onBackPress() {
249    logger.info(TAG, 'onBackPress');
250    router.back();
251  }
252
253  async isAdminActive() {
254    let wantTemp: Want = {
255      bundleName: elementNameVal.bundleName,
256      abilityName: elementNameVal.abilityName,
257    };
258    let retAppState: boolean;
259    let retSuperState: boolean;
260    logger.info(TAG, 'isAdminActive elementNameVal.bundleName=' + elementNameVal.bundleName +
261    ' | elementNameVal.abilityName=' + elementNameVal.abilityName);
262    if (elementNameVal.bundleName === baseData.EMPTY_STR || elementNameVal.abilityName === baseData.EMPTY_STR) {
263      logger.info(TAG, 'isAdminActive elementNameVal is null');
264      return;
265    }
266
267    retAppState = await edmEnterpriseDeviceManager.isAdminEnabled(wantTemp);
268    let name: string = elementNameVal.bundleName;
269    retSuperState = await edmEnterpriseDeviceManager.isSuperAdmin(name);
270    if (!retAppState) {
271      this.isShowActive = false;
272      this.isEnableButton = true;
273    } else {
274      if (retSuperState) {
275        this.isEnableButton = false;
276      } else {
277        this.isEnableButton = true;
278      }
279      this.isShowActive = true;
280    }
281    logger.info(TAG, 'isAdminActive retAppState:' + retAppState + ' | retSuperState:' + retSuperState);
282    isActiveState = this.isShowActive;
283  }
284
285  async activateAdmin(adminType: adminManager.AdminType) {
286    logger.info(TAG, 'activateAdmin isShowActive:' + this.isShowActive);
287    let wantTemp: Want = {
288      bundleName: elementNameVal.bundleName,
289      abilityName: elementNameVal.abilityName,
290    };
291    await this.isAdminActive();
292    let ret = true;
293    if (!this.isShowActive) {
294      if (adminType === edmEnterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL) {
295        await edmEnterpriseDeviceManager.enableAdmin(wantTemp,
296          { name: enterInfo.name, description: enterInfo.description },
297        edmEnterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL)
298          .catch((error: BusinessError) => {
299            ret = false;
300            logger.info(TAG, 'errorCode : ' + error.code + 'errorMessage : ' + error.message);
301          });
302      } else {
303        logger.warn(TAG, 'not support AdminType.ADMIN_TYPE_SUPER enable Admin')
304      }
305      logger.info(TAG, 'activateAdmin Activate admin end');
306    } else {
307      if (this.isEnableButton) {
308        await edmEnterpriseDeviceManager.disableAdmin(wantTemp)
309          .catch((error: BusinessError) => {
310            ret = false;
311            logger.info(TAG, 'errorCode : ' + error.code + 'errorMessage : ' + error.message);
312          });
313      } else {
314        logger.info(TAG, 'activateAdmin not support super admin active');
315      }
316    }
317    logger.info(TAG, 'activateAdmin adminType:' + adminType + ' | ret:' + ret);
318    if (ret) {
319      appDetailData.terminateAbilityPage();
320    }
321  }
322
323  async getSelfResourceVal(resource: Resource) {
324    let resMgr = getContext().resourceManager;
325    logger.info(TAG, 'getSelfResourceVal in:');
326    let value = await resMgr.getString(resource.id);
327    logger.info(TAG, 'getSelfResourceVal finish value:' + value);
328    if (!utils.isValid(value) || value === baseData.EMPTY_STR) {
329      return baseData.EMPTY_STR;
330    }
331    return value;
332  }
333
334  async getAbilityWantVal(appInfo: MyApplicationInfo, elementNameVal: Want, adminType: adminManager.AdminType) {
335    logger.info(TAG, 'getAbilityWantVal in:');
336    this.storage = LocalStorage.getShared();
337    let data = this.storage.get<Want>('adminProvisioningWant');
338
339    if (!utils.checkObjPropertyValid(data, 'parameters.elementName.abilityName') ||
340    !utils.checkObjPropertyValid(data, 'parameters.enterprise.name') ||
341    !utils.isValid((data.parameters?.elementName as Record<string, string>).bundleName) ||
342    !utils.isValid(data.parameters?.activeType) ||
343    !utils.isValid((data.parameters?.enterprise as Record<string, string>).description)) {
344      logger.warn(TAG, 'data.parameters = ' + JSON.stringify(data.parameters));
345      (getContext(this) as common.UIAbilityContext).terminateSelf();
346      return;
347    }
348
349    elementNameVal.abilityName = (data.parameters?.elementName as Record<string, string>).abilityName;
350    elementNameVal.bundleName = (data.parameters?.elementName as Record<string, string>).bundleName;
351    appInfo.appBundleName = (data.parameters?.elementName as Record<string, string>).bundleName;
352    adminType = data.parameters?.activeType as adminManager.AdminType;
353    AppStorage.SetOrCreate('activeType', adminType);
354
355    enterInfo.name = (data.parameters?.enterprise as Record<string, string>).name.substring(0, baseData.MAX_LEN);
356    enterInfo.description =
357      (data.parameters?.enterprise as Record<string, string>).description.substring(0, baseData.MAX_LEN);
358    logger.info(TAG, 'getAbilityWantVal out isAdminTypeVal.admintype:' + isAdminTypeVal +
359    ' enter.name=' + enterInfo.name + ' enter.des=' + enterInfo.description);
360  }
361
362  async getCheckAbilityList(appInfo: MyApplicationInfo, elementNameVal: Want, adminType: adminManager.AdminType) {
363    let deviceActiveOne = '';
364    let deviceActiveTwo = '';
365    let deviceDeactivate = '';
366    let getName = '';
367    let getDescription = '';
368    logger.info(TAG, 'getCheckAbilityList in:');
369    await this.getAbilityWantVal(appInfo, elementNameVal, adminType);
370
371    let ret = await appDetailData.checkAppItem(elementNameVal);
372    if (!ret) {
373      logger.info(TAG, 'aboutToAppear not exist bundleName:' + appInfo.appBundleName);
374      appDetailData.terminateAbilityPage();
375      return;
376    }
377
378    await this.isAdminActive();
379
380    if (appInfo.appBundleName) {
381      await appDetailData.getBundleInfoItem(appInfo.appBundleName, appInfo);
382    }
383
384    this.deviceAdminActive = getContext()
385      .resourceManager
386      .getStringSync($r('app.string.textApplicationInfoActive').id, `${appInfo.appTitle}`);
387    this.deviceAdminDisActive = getContext()
388      .resourceManager
389      .getStringSync($r('app.string.textApplicationInfoInactive').id, `${appInfo.appTitle}`);
390
391    let want: Want = {
392      bundleName: elementNameVal.bundleName,
393      abilityName: elementNameVal.abilityName,
394    };
395    let getEnterInfo: adminManager.EnterpriseInfo = {
396      name: '',
397      description: '',
398    };
399    if (this.isShowActive) {
400      logger.info(TAG, 'getCheckAbilityList get getEnterInfo');
401      getEnterInfo = await edmEnterpriseDeviceManager.getEnterpriseInfo(want);
402    }
403
404    logger.info(TAG, 'getCheckAbilityList start enterpriseName=' + getEnterInfo.name +
405    ' enterpriseDescription=' + getEnterInfo.description);
406    if (utils.isValid(getEnterInfo.name)) {
407      getName = getEnterInfo.name.substring(0, baseData.MAX_LEN);
408    }
409    if (utils.isValid(getEnterInfo.description)) {
410      getDescription = getEnterInfo.description.substring(0, baseData.MAX_LEN);
411    }
412
413    if (this.isShowActive) {
414      this.enterpriseName = getContext().resourceManager.getStringSync($r('app.string.enterprise_name').id, getName);
415      this.enterpriseDescription = getContext()
416        .resourceManager
417        .getStringSync($r('app.string.enterprise_description').id, getDescription);
418    } else {
419      this.enterpriseName = getContext()
420        .resourceManager
421        .getStringSync($r('app.string.enterprise_name').id, enterInfo.name);
422      this.enterpriseDescription = getContext()
423        .resourceManager
424        .getStringSync($r('app.string.enterprise_description').id, enterInfo.description);
425    }
426    logger.info(TAG, 'getCheckAbilityList enterpriseName=' + this.enterpriseName + ' enterpriseDescription=' +
427    this.enterpriseDescription);
428  }
429}