• 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
16import UIAbility from '@ohos.app.ability.UIAbility';
17import bundleMonitor from '@ohos.bundle.bundleMonitor';
18import account_osAccount from '@ohos.account.osAccount';
19import { GlobalContext } from '../common/utils/globalContext';
20import { abilityAccessCtrl, bundleManager } from '@kit.AbilityKit';
21
22const TAG = 'PermissionManager_Log:';
23const USER_ID = 100;
24let callerBundleName: string;
25
26export default class MainAbility extends UIAbility {
27  onCreate(want, launchParam): void {
28    console.log(TAG + 'MainAbility onCreate, ability name is ' + want.abilityName + '.');
29
30    callerBundleName = want.parameters?.bundleName as string ?? '';
31    GlobalContext.store('bundleName', callerBundleName);
32  }
33
34  onWindowStageCreate(windowStage): void {
35    // Main window is created, set main page for this ability
36    console.log(TAG + 'MainAbility onWindowStageCreate.');
37    globalThis.windowStage = windowStage;
38    globalThis.refresh = false;
39    if (!this.permissionCheck()) {
40      windowStage.loadContent('pages/transition');
41      this.context.terminateSelf();
42      return;
43    }
44
45    if (callerBundleName) {
46      globalThis.currentApp = callerBundleName;
47      this.getSperifiedApplication(callerBundleName);
48    } else {
49      globalThis.currentApp = 'all';
50      this.getAllApplications();
51    }
52
53    try {
54      bundleMonitor.on('add', (bundleChangeInfo) => {
55        console.log(`${TAG} bundleMonitor.add: ${JSON.stringify(bundleChangeInfo)}`);
56        if (globalThis.currentApp === 'all') {
57          this.getAllApplications();
58          globalThis.refresh = true;
59        }
60      });
61      bundleMonitor.on('remove', (bundleChangeInfo) => {
62        console.log(`${TAG} bundleMonitor.remove: ${JSON.stringify(bundleChangeInfo)}`);
63        if (globalThis.currentApp === 'all') {
64          this.getAllApplications();
65          globalThis.refresh = true;
66        }
67      });
68      bundleMonitor.on('update', (bundleChangeInfo) => {
69        console.log(`${TAG} bundleMonitor.update: ${JSON.stringify(bundleChangeInfo)}`);
70        if (globalThis.currentApp === 'all') {
71          this.getAllApplications();
72          globalThis.refresh = true;
73        }
74      });
75    } catch (error) {
76      console.error(TAG + 'bundleMonitor failed.');
77    }
78
79  }
80
81  onNewWant(want): void {
82    console.log(TAG + 'MainAbility onNewWant. want: ' + JSON.stringify(want));
83
84    let bundleName = want.parameters?.bundleName ? want.parameters.bundleName : 'all';
85    if (globalThis.currentApp === 'all') {
86      if (globalThis.currentApp !== bundleName) {
87        console.log(TAG + 'MainAbility onNewWant. all -> app');
88        globalThis.windowStage?.setUIContent(this.context, 'pages/transition', null);
89        globalThis.currentApp = bundleName;
90        GlobalContext.store('bundleName', bundleName);
91        this.getSperifiedApplication(bundleName);
92      } else {
93        if (globalThis.refresh === true) {
94          globalThis.windowStage?.setUIContent(this.context, 'pages/transition', null);
95          this.getAllApplications();
96          globalThis.refresh = false;
97        }
98      }
99    } else {
100      if (bundleName === 'all') {
101        console.log(TAG + 'MainAbility onNewWant. app -> all');
102        globalThis.windowStage?.setUIContent(this.context, 'pages/transition', null);
103        globalThis.currentApp = 'all';
104        this.getAllApplications();
105      } else {
106        if (globalThis.currentApp !== bundleName) {
107          console.log(TAG + 'MainAbility onNewWant. app -> app');
108          globalThis.windowStage?.setUIContent(this.context, 'pages/transition', null);
109          globalThis.currentApp = bundleName;
110          GlobalContext.store('bundleName', bundleName);
111          this.getSperifiedApplication(bundleName);
112        }
113      }
114    }
115
116  }
117
118  onWindowStageDestroy(): void {
119    try {
120      bundleMonitor.off('add');
121      bundleMonitor.off('remove');
122      bundleMonitor.off('update');
123      console.log(TAG + 'MainAbility onWindowStageDestroy.');
124    } catch (err) {
125      console.log(`errData is errCode:${err.code}  message:${err.message}`);
126    }
127  }
128
129  onBackground(): void {
130    console.log(TAG + ' onBackground.');
131  }
132
133  onDestroy(): void {
134    console.log(TAG + ' onDestroy.');
135  }
136
137  onForeground(): void {
138    console.log(TAG + ' onForeground.');
139  }
140
141  private permissionCheck(): boolean {
142    try {
143      let flag = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION;
144      let bundleInfo = bundleManager.getBundleInfoForSelfSync(flag);
145      let atManager = abilityAccessCtrl.createAtManager();
146      let status =
147        atManager.verifyAccessTokenSync(bundleInfo.appInfo.accessTokenId, 'ohos.permission.GET_INSTALLED_BUNDLE_LIST');
148      if (status === abilityAccessCtrl.GrantStatus.PERMISSION_DENIED) {
149        console.log(TAG + 'permission status is denied.');
150        return false;
151      }
152      return true;
153    } catch (err) {
154      console.error(TAG + 'verifyAccessTokenSync failed.');
155      return false;
156    }
157  }
158
159  getAllApplications(): void {
160    const flag =
161      bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION |
162      bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION;
163    let accountManager = account_osAccount.getAccountManager();
164    try {
165      accountManager.getActivatedOsAccountLocalIds((err, idArray: number[])=>{
166        console.log(TAG + 'getActivatedOsAccountLocalIds err:' + JSON.stringify(err));
167        console.log(TAG + 'getActivatedOsAccountLocalIds idArray: ' + JSON.stringify(idArray));
168        let userId = idArray[0];
169        bundleManager.getAllBundleInfo(flag, userId || USER_ID).then(async(bundleInfos) => {
170          if (bundleInfos.length <= 0) {
171            console.info(TAG + 'bundle.getAllBundleInfo result.length less than or equal to zero');
172            this.context.terminateSelf();
173            return;
174          }
175          let initialGroups = [];
176          for (let i = 0; i < bundleInfos.length; i++) {
177            let info = bundleInfos[i];
178            // Filter blank icon icon and text label resources
179            try {
180              await bundleManager.queryAbilityInfo({
181                bundleName: info.name,
182                action: 'action.system.home',
183                entities: ['entity.system.home']
184              }, bundleManager.AbilityFlag.GET_ABILITY_INFO_WITH_APPLICATION);
185            } catch (error) {
186              console.error(
187                TAG + 'queryAbilityByWant catch app: ' + JSON.stringify(info.name) + 'err: ' + JSON.stringify(error)
188              );
189              continue;
190            }
191
192            initialGroups.push(info);
193          }
194          let storage: LocalStorage = new LocalStorage({ 'initialGroups': initialGroups });
195          globalThis.windowStage?.loadContent('pages/authority-management', storage);
196        }).catch((error) => {
197          console.error(TAG + 'bundle.getAllBundleInfo failed. Cause: ' + JSON.stringify(error));
198          this.context.terminateSelf();
199        });
200      });
201    } catch (e) {
202      console.error(TAG + 'getActivatedOsAccountLocalIds exception: ' + JSON.stringify(e));
203      this.context.terminateSelf();
204    }
205  }
206
207  getSperifiedApplication(bundleName): void {
208    const flag =
209      bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION |
210      bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION;
211    try {
212      bundleManager.getBundleInfo(bundleName, flag).then(bundleInfo => {
213        let reqPermissions: Array<string> = [];
214        bundleInfo.reqPermissionDetails.forEach(item => {
215          reqPermissions.push(item.name);
216        });
217
218        let info = {
219          'bundleName': bundleInfo.name,
220          'api': bundleInfo.targetVersion,
221          'tokenId': bundleInfo.appInfo.accessTokenId,
222          'icon': '',
223          'iconId': bundleInfo.appInfo.iconId,
224          'iconResource': bundleInfo.appInfo.iconResource,
225          'label': '',
226          'labelId': bundleInfo.appInfo.labelId,
227          'labelResource': bundleInfo.appInfo.labelResource,
228          'permissions': reqPermissions,
229          'groupId': [],
230          'zhTag': '',
231          'indexTag': '',
232          'language': ''
233        };
234        GlobalContext.store('applicationInfo', info);
235        globalThis.windowStage?.setUIContent(this.context, 'pages/application-secondary', null);
236      }).catch((error) => {
237        console.log(TAG + 'Special branch getBundleInfo failed:' + JSON.stringify(error));
238        this.context.terminateSelf();
239      });
240    } catch (error) {
241      console.error(TAG + 'Special branch failed: ' + JSON.stringify(error));
242      this.context.terminateSelf();
243    }
244  }
245};
246