• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2022-2023 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 bundleManager from '@ohos.bundle.bundleManager';
17import router from '@ohos.router';
18import common from '@ohos.app.ability.common';
19import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
20import privacyManager from '@ohos.privacyManager';
21import { backBar } from '../common/components/backBar';
22import Constants from '../common/utils/constant';
23import { Log, getPermissionGroup, getGroupIdByPermission, supportPermission } from '../common/utils/utils';
24import {
25  StringObj,
26  AppInfoSimple,
27  AppRecordInfo,
28  AppInfo,
29  GroupRecordInfo,
30  AppGroupRecordInfo
31} from '../common/model/typedef';
32import { GlobalContext } from '../common/utils/globalContext';
33import { Permission } from '../common/model/definition';
34
35@Extend(Image)function customizeImage(width: number, height: number) {
36  .objectFit(ImageFit.Contain)
37  .width(width)
38  .height(height)
39  .draggable(false)
40};
41
42@Entry
43@Component
44struct permissionRecordPage {
45  private context = getContext(this) as common.UIAbilityContext;
46  @State isVertical: boolean = GlobalContext.load('isVertical');
47  @State allBundleInfo: AppInfo[] = GlobalContext.load('allBundleInfo');
48  @State groups: GroupRecordInfo[] = [];
49  @State applicationInfos: AppRecordInfo[] = [];
50  @State permissionApplications: AppRecordInfo[] = [];
51  @State permissionIndex: number = -1;
52  @State applicationIndex: number = -1;
53  @State strings: StringObj = new StringObj('', '');
54  @State currentIndex: number = 0;
55  @State show: boolean = false;
56  @State isTouch: string = '';
57  @State reqUserRecords: privacyManager.PermissionUsedRecord[] = [];
58  @State reqUserPermissions: Permission[] = [];
59  @State permissionGroups: AppGroupRecordInfo[] = [];
60  @State groupNames: ResourceStr[] = [];
61  @State appLastTime: number = 0;
62  @Builder TabBuilder(index: number) {
63    Flex({
64      alignItems: index ? ItemAlign.Start : ItemAlign.End,
65      justifyContent: FlexAlign.Center,
66      direction: FlexDirection.Column
67    }) {
68      Text(index ? $r('app.string.application') : $r('app.string.permission'))
69        .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE)
70        .fontColor(
71          this.currentIndex == index ?
72          $r('sys.color.ohos_id_color_subtab_text_on') :
73          $r('sys.color.icon_secondary')
74        )
75        .fontWeight(this.currentIndex == index ? FontWeight.Bold : FontWeight.Regular)
76        .lineHeight(Constants.TEXT_LINE_HEIGHT)
77        .baselineOffset(Constants.TAB_DECORATION_POSITION_Y)
78      if (this.currentIndex == index) {
79        Text(index ? $r('app.string.application') : $r('app.string.permission'))
80          .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE)
81          .fontWeight(FontWeight.Bold)
82          .lineHeight(Constants.TAB_LINE_HEIGHT)
83          .height(Constants.TAB_DECORATION_HEIGHT)
84          .backgroundColor($r('sys.color.comp_background_emphasize'))
85      }
86    }.height(Constants.TAB_HEIGHT)
87    .width(Constants.FULL_WIDTH)
88    .padding({ left: this.isVertical ? Constants.TAB_INNER_PADDING : Constants.DEFAULT_PADDING_START,
89      right: this.isVertical ? Constants.TAB_INNER_PADDING : Constants.DEFAULT_PADDING_END })
90  }
91
92  @Builder PermissionListItemLayout(item: GroupRecordInfo, index: number) {
93    ListItem() {
94      Column() {
95        Column() {
96          Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
97            Row() {
98              Image(item.icon)
99                .fillColor($r('sys.color.icon_secondary'))
100                .customizeImage(Constants.MANAGEMENT_IMAGE_WIDTH, Constants.MANAGEMENT_IMAGE_HEIGHT)
101                .margin({
102                  right: Constants.MANAGEMENT_IMAGE_MARGIN_RIGHT_RECORD,
103                  left: Constants.MANAGEMENT_IMAGE_MARGIN_LEFT
104                })
105              Column() {
106                Text(item.groupName)
107                  .width(Constants.MAXIMUM_HEADER_WIDTH)
108                  .maxLines(Constants.MAXIMUM_HEADER_LINES)
109                  .textOverflow({ overflow: TextOverflow.Ellipsis })
110                  .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE)
111                  .fontWeight(FontWeight.Medium)
112                  .fontColor($r('sys.color.font_primary'))
113                  .lineHeight(Constants.TEXT_LINE_HEIGHT)
114                  .margin({ bottom: Constants.TERTIARY_LABEL_MARGIN_BOTTOM })
115                Text($r('app.string.visits', String(item.sum)))
116                  .fontSize(Constants.TEXT_SMALL_FONT_SIZE)
117                  .fontColor($r('sys.color.font_secondary'))
118                  .lineHeight(Constants.TEXT_SMALL_LINE_HEIGHT)
119              }.flexGrow(Constants.FLEX_GROW)
120              .alignItems(HorizontalAlign.Start)
121              Image(index == this.permissionIndex ? $r('app.media.xiangshangjiantou') : $r('app.media.xiangxiajiantou'))
122                .fillColor($r('sys.color.icon_secondary'))
123                .customizeImage(Constants.IMAGE_WIDTH_RECORD, Constants.IMAGE_HEIGHT_RECORD)
124            }
125            .width(Constants.FULL_WIDTH)
126            .height(Constants.LISTITEM_HEIGHT_PERMISSION)
127          }
128        }.onClick(() => {
129          this.permissionIndex = this.permissionIndex == index ? -1 : index
130          this.permissionApplications = this.applicationInfos.filter((appInfo) => {
131            return appInfo.groupNames.includes(item.groupName);
132          })
133        })
134        .padding({ left: $r('sys.float.ohos_id_card_margin_start'), right: $r('sys.float.ohos_id_card_margin_end') })
135        if (index == this.permissionIndex) {
136          List() {
137            ForEach(this.permissionApplications, (permissionApplication: AppRecordInfo) => {
138              ListItem() {
139                Row() {
140                  Image(permissionApplication.icon)
141                    .customizeImage(Constants.APPLICATION_IMAGE_WIDTH, Constants.APPLICATION_IMAGE_HEIGHT)
142                    .margin({ right: Constants.MANAGEMENT_IMAGE_MARGIN_RIGHT })
143                  Column() {
144                    Row().width(Constants.FULL_WIDTH).height(Constants.DIVIDER)
145                      .backgroundColor($r('sys.color.comp_divider'))
146                      .position({ x: 0, y: 0 })
147                    Text(permissionApplication.groupName)
148                      .width(Constants.MAXIMUM_HEADER_WIDTH)
149                      .maxLines(Constants.MAXIMUM_HEADER_LINES)
150                      .textOverflow({ overflow: TextOverflow.Ellipsis })
151                      .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE)
152                      .fontWeight(FontWeight.Medium)
153                      .fontColor($r('sys.color.font_primary'))
154                      .lineHeight(Constants.TEXT_LINE_HEIGHT)
155                      .margin({ bottom: Constants.TERTIARY_LABEL_MARGIN_BOTTOM })
156                    Text(
157                      $r('app.string.recent_visit',
158                      String(this.getAppRecords(permissionApplication, item.groupName, true)),
159                      this.getTime(this.getAppRecords(permissionApplication, item.groupName, false)))
160                    )
161                      .padding({ right: Constants.LISTITEM_PADDING_RIGHT_RECORD })
162                      .fontSize(Constants.TEXT_SMALL_FONT_SIZE)
163                      .fontColor($r('sys.color.font_secondary'))
164                      .lineHeight(Constants.TEXT_SMALL_LINE_HEIGHT)
165                  }.alignItems(HorizontalAlign.Start)
166                  .height(Constants.FULL_HEIGHT)
167                  .width(Constants.FULL_WIDTH)
168                  .justifyContent(FlexAlign.Center)
169                }
170              }.height(Constants.LISTITEM_HEIGHT_APPLICATION)
171              .onClick(() => {
172                let info: AppInfoSimple = new AppInfoSimple(
173                  permissionApplication.name,
174                  permissionApplication.api,
175                  permissionApplication.accessTokenId,
176                  permissionApplication.icon,
177                  permissionApplication.groupName,
178                  permissionApplication.reqUserPermissions,
179                  permissionApplication.groupIds
180                )
181                GlobalContext.store('applicationInfo', info);
182                router.pushUrl({ url: 'pages/application-secondary' });
183              })
184              .padding({
185                left: $r('sys.float.ohos_id_card_margin_start'),
186                right: $r('sys.float.ohos_id_card_margin_end')
187              })
188              .borderRadius($r('sys.float.ohos_id_corner_radius_default_l'))
189              .linearGradient((this.isTouch === permissionApplication.name) ? {
190                  angle: 90,
191                  direction: GradientDirection.Right,
192                  colors: [['#DCEAF9', 0.0], ['#FAFAFA', 1.0]]
193                } : {
194                  angle: 90,
195                  direction: GradientDirection.Right,
196                  colors: [
197                    [$r('sys.color.comp_background_list_card'), 1],
198                    [$r('sys.color.comp_background_list_card'), 1]
199                  ]
200                })
201              .onTouch(event => {
202                if (event === undefined) {
203                  return;
204                }
205                if (event.type === TouchType.Down) {
206                  this.isTouch = permissionApplication.name;
207                }
208                if (event.type === TouchType.Up) {
209                  this.isTouch = '';
210                }
211              })
212            }, (item: AppRecordInfo) => JSON.stringify(item))
213          }
214        }
215      }
216    }.padding(Constants.LIST_PADDING_TOP)
217    .margin({ bottom: Constants.LISTITEM_MARGIN_BOTTOM })
218    .backgroundColor($r('sys.color.comp_background_list_card'))
219    .borderRadius($r('sys.float.ohos_id_corner_radius_card'))
220  }
221
222  @Builder ApplicationListItemLayout(item: AppRecordInfo, index: number) {
223    ListItem() {
224      Column() {
225        Column() {
226          Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
227            Row() {
228              Image(item.icon)
229                .customizeImage(Constants.APPLICATION_IMAGE_WIDTH, Constants.APPLICATION_IMAGE_HEIGHT)
230                .margin({ right: Constants.MANAGEMENT_IMAGE_MARGIN_RIGHT })
231              Column() {
232                Text(item.groupName)
233                  .width(Constants.MAXIMUM_HEADER_WIDTH)
234                  .maxLines(Constants.MAXIMUM_HEADER_LINES)
235                  .textOverflow({ overflow: TextOverflow.Ellipsis })
236                  .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE)
237                  .fontWeight(FontWeight.Medium)
238                  .fontColor($r('sys.color.font_primary'))
239                  .lineHeight(Constants.TEXT_LINE_HEIGHT)
240                  .margin({ bottom: Constants.TERTIARY_LABEL_MARGIN_BOTTOM })
241                Row() {
242                  ForEach(item.permissions, (permission: AppGroupRecordInfo) => {
243                    Image(permission.icon)
244                      .fillColor($r('sys.color.icon_secondary'))
245                      .customizeImage(
246                        Constants.IMAGE_WIDTH_RECORD_APPLICATION,
247                        Constants.IMAGE_HEIGHT_RECORD_APPLICATION
248                      )
249                      .margin({ right: Constants.APPLICATION_TEXT_MARGIN_RIGHT })
250                  }, (item: AppGroupRecordInfo) => JSON.stringify(item))
251                }
252              }.flexGrow(Constants.FLEX_GROW)
253              .alignItems(HorizontalAlign.Start)
254              Image(
255                index == this.applicationIndex ? $r('app.media.xiangshangjiantou') : $r('app.media.xiangxiajiantou')
256              )
257                .fillColor($r('sys.color.icon_secondary'))
258                .customizeImage(Constants.IMAGE_WIDTH_RECORD, Constants.IMAGE_HEIGHT_RECORD)
259            }
260            .width(Constants.FULL_WIDTH)
261            .height(Constants.LISTITEM_HEIGHT_APPLICATION)
262          }
263        }.onClick(() => {
264          this.applicationIndex = this.applicationIndex == index ? -1 : index
265        })
266        .padding({ left: $r('sys.float.ohos_id_card_margin_start'), right: $r('sys.float.ohos_id_card_margin_end') })
267        if (index == this.applicationIndex) {
268          List() {
269            ForEach(item.permissions, (permission: AppGroupRecordInfo) => {
270              ListItem() {
271                Row() {
272                  Image(permission.icon)
273                    .fillColor($r('sys.color.icon_secondary'))
274                    .customizeImage(Constants.MANAGEMENT_IMAGE_WIDTH, Constants.MANAGEMENT_IMAGE_HEIGHT)
275                    .margin({
276                      right: Constants.MANAGEMENT_IMAGE_MARGIN_RIGHT_RECORD,
277                      left: Constants.MANAGEMENT_IMAGE_MARGIN_LEFT
278                    })
279                  Column() {
280                    Row().width(Constants.FULL_WIDTH).height(Constants.DIVIDER)
281                      .backgroundColor($r('sys.color.comp_divider'))
282                      .position({ x: 0, y: 0 })
283                    Text(permission.groupName)
284                      .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE)
285                      .fontWeight(FontWeight.Medium)
286                      .fontColor($r('sys.color.font_primary'))
287                      .lineHeight(Constants.TEXT_LINE_HEIGHT)
288                      .margin({ bottom: Constants.TERTIARY_LABEL_MARGIN_BOTTOM })
289                    Text($r('app.string.recent_visit', String(permission.count), this.getTime(permission.lastTime)))
290                      .padding({ right: Constants.LISTITEM_PADDING_RIGHT_RECORD })
291                      .fontSize(Constants.TEXT_SMALL_FONT_SIZE)
292                      .fontColor($r('sys.color.font_secondary'))
293                      .lineHeight(Constants.TEXT_SMALL_LINE_HEIGHT)
294                  }.alignItems(HorizontalAlign.Start)
295                  .height(Constants.FULL_HEIGHT)
296                  .width(Constants.FULL_WIDTH)
297                  .justifyContent(FlexAlign.Center)
298                }
299              }.height(Constants.LISTITEM_HEIGHT_PERMISSION)
300              .onClick(() => {
301                let info: AppInfoSimple = new AppInfoSimple(
302                  item.name,
303                  item.api,
304                  item.accessTokenId,
305                  item.icon,
306                  item.groupName,
307                  item.reqUserPermissions,
308                  item.groupIds
309                );
310                GlobalContext.store('applicationInfo', info);
311                router.pushUrl({ url: 'pages/application-secondary' });
312              })
313              .padding({
314                left: $r('sys.float.ohos_id_card_margin_start'),
315                right: $r('sys.float.ohos_id_card_margin_end')
316              })
317              .borderRadius($r('sys.float.ohos_id_corner_radius_default_l'))
318              .linearGradient((this.isTouch === permission.name) ? {
319                   angle: 90,
320                   direction: GradientDirection.Right,
321                   colors: [['#DCEAF9', 0.0], ['#FAFAFA', 1.0]]
322                 } : {
323                   angle: 90,
324                   direction: GradientDirection.Right,
325                   colors: [
326                     [$r('sys.color.comp_background_list_card'), 1],
327                     [$r('sys.color.comp_background_list_card'), 1]
328                   ]
329                 })
330              .onTouch(event => {
331                if (event === undefined) {
332                  return;
333                }
334                if (event.type === TouchType.Down) {
335                  this.isTouch = permission.name;
336                }
337                if (event.type === TouchType.Up) {
338                  this.isTouch = '';
339                }
340              })
341            }, (item: AppGroupRecordInfo) => JSON.stringify(item))
342          }
343        }
344      }
345    }.padding(Constants.LIST_PADDING_TOP)
346    .margin({ bottom: Constants.LISTITEM_MARGIN_BOTTOM })
347    .backgroundColor($r('sys.color.comp_background_list_card'))
348    .borderRadius($r('sys.float.ohos_id_corner_radius_card'))
349  }
350
351  build() {
352    GridRow({ gutter: Constants.GUTTER, columns: {
353      xs: Constants.XS_COLUMNS, sm: Constants.SM_COLUMNS, md: Constants.MD_COLUMNS, lg: Constants.LG_COLUMNS } }) {
354      GridCol({
355        span: { xs: Constants.XS_SPAN, sm: Constants.SM_SPAN, md: Constants.MD_SPAN, lg: Constants.LG_SPAN },
356        offset: { xs: Constants.XS_OFFSET, sm: Constants.SM_OFFSET, md: Constants.MD_OFFSET, lg: Constants.LG_OFFSET }
357      }) {
358        Row() {
359          Column() {
360            Row() {
361              backBar( { title: JSON.stringify($r('app.string.permission_access_record')), recordable: false })
362            }
363            Row() {
364              Column() {
365                Column() {
366                  Flex({ justifyContent: FlexAlign.Start }) {
367                    Text($r('app.string.record_time_limit'))
368                      .margin({ left: Constants.DEFAULT_MARGIN_START })
369                      .fontSize(Constants.TEXT_SMALL_FONT_SIZE)
370                      .fontColor($r('sys.color.font_secondary'))
371                      .lineHeight(Constants.SUBTITLE_LINE_HEIGHT)
372                  }.constraintSize({ minHeight: Constants.SUBTITLE_MIN_HEIGHT })
373                  .padding({ top: Constants.SUBTITLE_PADDING_TOP, bottom: Constants.SUBTITLE_PADDING_BOTTOM })
374                  if (this.groups.length) {
375                    Stack() {
376                      Tabs() {
377                        TabContent() {
378                          Row() {
379                            Column() {
380                              Scroll() {
381                                Row() {
382                                  List() {
383                                    ForEach(this.groups, (item: GroupRecordInfo, index) => {
384                                      this.PermissionListItemLayout(item, index as number)
385                                    }, (item: GroupRecordInfo) => JSON.stringify(item))
386                                  }.padding({ top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM })
387                                  .height(Constants.FULL_HEIGHT)
388                                }.padding({
389                                  left: Constants.MANAGEMENT_ROW_PADDING_LEFT,
390                                  right: Constants.MANAGEMENT_ROW_PADDING_RIGHT,
391                                  top: Constants.MANAGEMENT_ROW_PADDING_TOP,
392                                  bottom: Constants.MANAGEMENT_ROW_PADDING_BOTTOM
393                                })
394                              }.scrollBar(BarState.Off)
395                            }.width(Constants.FULL_WIDTH)
396                          }
397                        }.tabBar(this.TabBuilder(0))
398                        TabContent() {
399                          Row() {
400                            Column() {
401                              Scroll() {
402                                Row() {
403                                  if (this.show) {
404                                    List() {
405                                      ForEach(this.applicationInfos, (item: AppRecordInfo, index) => {
406                                        this.ApplicationListItemLayout(item, index as number)
407                                      }, (item: AppRecordInfo) => JSON.stringify(item))
408                                    }
409                                    .padding({ top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM })
410                                    .height(Constants.FULL_HEIGHT)
411                                  }
412                                }.padding({
413                                  left: Constants.MANAGEMENT_ROW_PADDING_LEFT,
414                                  right: Constants.MANAGEMENT_ROW_PADDING_RIGHT,
415                                  top: Constants.MANAGEMENT_ROW_PADDING_TOP,
416                                  bottom: Constants.MANAGEMENT_ROW_PADDING_BOTTOM
417                                })
418                              }.scrollBar(BarState.Off)
419                            }.width(Constants.FULL_WIDTH)
420                          }
421                        }.tabBar(this.TabBuilder(1))
422                      }
423                      .barMode(BarMode.Fixed)
424                      .barWidth(Constants.BAR_WIDTH)
425                      .onChange((index) => {
426                        this.currentIndex = index;
427                        if (!this.show) {
428                          this.show = true;
429                        }
430                      })
431                    }.height(Constants.FULL_HEIGHT)
432                  } else {
433                    Flex({
434                      justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center, direction: FlexDirection.Column
435                    }) {
436                      Image($r('app.media.noRecord'))
437                        .customizeImage(Constants.NORECORD_IMAGE_WIDTH, Constants.NORECORD_IMAGE_HEIGHT)
438                        .margin({ left: Constants.NORECORD_IMAGE_MARGIN_LEFT })
439                      Text($r('app.string.no_record')).margin({ top: Constants.DIALOG_REQ_MARGIN_TOP })
440                        .fontSize(Constants.TEXT_SMALL_FONT_SIZE)
441                        .fontColor($r('sys.color.font_secondary'))
442                    }.width(Constants.FULL_WIDTH).height(Constants.FULL_HEIGHT)
443                    .padding({ bottom: Constants.RECORD_PADDING_BOTTOM })
444                  }
445                }
446              }
447            }
448            .layoutWeight(Constants.LAYOUT_WEIGHT)
449          }
450        }
451        .height(Constants.FULL_HEIGHT)
452        .width(Constants.FULL_WIDTH)
453        .backgroundColor($r('sys.color.background_secondary'))
454      }
455    }.backgroundColor($r('sys.color.background_secondary'))
456  }
457
458  /**
459   * Get time
460   * @param {Number} The time stamp
461   */
462  getTime(time: number, format = 'MM月DD日 NNHH:mm') {
463    if (this.strings.morning == 'am') { format = 'HH:mm NN MM/DD' }
464    let date = new Date(time);
465    let key = ['MM', 'DD', 'NN', 'HH', 'mm'];
466    let value = [
467      date.getMonth() + 1,
468      date.getDate(),
469      date.getHours() >= 12 ? this.strings.afternoon : this.strings.morning,
470      date.getHours() >= 12 ? date.getHours() - 12 : date.getHours(),
471      date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes(),
472    ];
473
474    for (let i = 0; i < key.length; ++i) {
475      format = format.replace(key[i], String(value[i]));
476    }
477    return format;
478  }
479
480  /**
481   * Get application record info
482   * @param {Object} application info
483   * @param {String} groupName
484   * @param {Boolean} true: count, false: lastTime
485   */
486  getAppRecords(appInfo: AppRecordInfo, groupName: ResourceStr, option: boolean): number {
487    let record = appInfo.permissions.filter(permission => {
488      return permission.groupName == groupName;
489    })
490    if (record.length > 0) {
491      return option ? record[0].count : record[0].lastTime;
492    } else {
493      return 0;
494    }
495  }
496
497  getStrings() {
498    this.context.resourceManager.getStringValue($r('app.string.morning').id, (err, val) => {
499      this.strings.morning = val;
500    })
501    this.context.resourceManager.getStringValue($r('app.string.afternoon').id, (err, val) => {
502      this.strings.afternoon = val;
503    })
504  }
505
506  async getReqUserRecords(record: privacyManager.BundleUsedRecord, info: bundleManager.BundleInfo) {
507    for (let j = 0; j < record.permissionRecords.length; j++) {
508      let permission = record.permissionRecords[j].permissionName as Permission;
509      try {
510        let flag = await abilityAccessCtrl.createAtManager().getPermissionFlags(info.appInfo.accessTokenId, permission);
511        if (flag == Constants.PERMISSION_SYSTEM_FIXED) {
512          continue;
513        }
514      } catch (err) {
515        Log.error('getPermissionFlags error: ' + JSON.stringify(err));
516      }
517      let supportPermissions = supportPermission();
518      if (supportPermissions.indexOf(permission) != -1) {
519        this.reqUserRecords.push(record.permissionRecords[j]);
520      }
521    }
522  }
523
524  async getReqUserPermissions(reqPermissions: Permission[], info: bundleManager.BundleInfo) {
525    let acManager = abilityAccessCtrl.createAtManager();
526    for (let k = 0; k < reqPermissions.length; k++) {
527      let reqPermission = reqPermissions[k];
528      try {
529        let reqFlag = await acManager.getPermissionFlags(info.appInfo.accessTokenId, reqPermission);
530        if (reqFlag == Constants.PERMISSION_SYSTEM_FIXED) {
531          continue;
532        }
533      } catch (err) {
534        Log.error('getPermissionFlags error: ' + JSON.stringify(err));
535      }
536      let supportPermissions = supportPermission();
537      if (supportPermissions.indexOf(reqPermission) != -1) {
538        this.reqUserPermissions.push(reqPermission);
539      }
540    }
541  }
542
543  getPermissionGroups() {
544    this.reqUserRecords.forEach(reqUserRecord => {
545      let group = getPermissionGroup(reqUserRecord.permissionName as Permission);
546      if (!group) {
547        Log.info('permission not find:' + reqUserRecord.permissionName);
548      } else {
549        let existing = this.permissionGroups.find(permissionGroup => permissionGroup.name == group.name);
550        let lastTime = reqUserRecord.lastAccessTime;
551        lastTime > this.appLastTime ? this.appLastTime = lastTime : '';
552        if (!existing) {
553          let appGroupRecord: AppGroupRecordInfo = new AppGroupRecordInfo(
554            group.name,
555            group.groupName,
556            group.label,
557            group.icon,
558            reqUserRecord.accessCount,
559            lastTime
560          );
561          this.permissionGroups.push(appGroupRecord);
562          this.groupNames.push(group.groupName);
563        } else {
564          existing.count += reqUserRecord.accessCount;
565          lastTime > existing.lastTime ? existing.lastTime = lastTime : '';
566        }
567      }
568    })
569  }
570
571  getInfo(record: privacyManager.BundleUsedRecord, sortFlag: boolean) {
572    bundleManager.getBundleInfo(record.bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION |
573    bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION).then(async (info): Promise<boolean> => {
574      let appInfo: AppRecordInfo = new AppRecordInfo('', '', '', 0, 0, [], [], [], [], 0);
575      let reqPermissions: Permission[] = [];
576      let groupIds: number[] = [];
577      this.reqUserPermissions = [];
578      this.reqUserRecords = [];
579      this.permissionGroups = [];
580      this.groupNames = [];
581      this.appLastTime = 0;
582      info.reqPermissionDetails.forEach(item => {
583        reqPermissions.push(item.name as Permission);
584      });
585      await this.getReqUserRecords(record, info);
586      await this.getReqUserPermissions(reqPermissions, info);
587      if (this.reqUserRecords.length == 0) {
588        return false;
589      }
590      this.getPermissionGroups();
591      for (let i = 0; i < this.reqUserPermissions.length; i++) {
592        let groupId = getGroupIdByPermission(this.reqUserPermissions[i])
593        if (groupIds.indexOf(groupId) == -1) {
594          groupIds.push(groupId);
595        }
596      }
597      this.allBundleInfo.forEach(bundleInfo => {
598        if (bundleInfo.bundleName === info.name) {
599          appInfo.groupName = bundleInfo.label;
600          appInfo.icon = bundleInfo.icon;
601        }
602      })
603      appInfo.name = info.name;
604      appInfo.api = info.targetVersion;
605      appInfo.accessTokenId = info.appInfo.accessTokenId;
606      appInfo.reqUserPermissions = this.reqUserPermissions;
607      appInfo.permissions = this.permissionGroups;
608      appInfo.groupNames = this.groupNames;
609      appInfo.groupIds = groupIds;
610      appInfo.appLastTime = this.appLastTime;
611      this.applicationInfos.push(appInfo);
612      if (sortFlag) {
613        let appInfos: AppRecordInfo[] = [];
614        this.applicationInfos.forEach(item => { appInfos.push(item) });
615        appInfos.sort((a, b) => { return b.appLastTime - a.appLastTime });
616        this.applicationInfos = appInfos;
617      }
618      return true;
619    })
620  }
621
622  getAllRecords() {
623    let request: privacyManager.PermissionUsedRequest = {
624      tokenId: 0,
625      isRemote: false,
626      deviceId: '',
627      bundleName: '',
628      permissionNames: [],
629      beginTime: 0,
630      endTime: 0,
631      flag: 1
632    }
633    privacyManager.getPermissionUsedRecord(request).then(records => {
634      this.getRecord(records);
635    })
636  }
637
638  async getRecord(records: privacyManager.PermissionUsedResponse) {
639    let groupArray: GroupRecordInfo[] = [];
640    let acManager = abilityAccessCtrl.createAtManager();
641    for (let i = 0; i < records.bundleRecords.length; i++) {
642      let record = records.bundleRecords[i];
643      Log.info('bundleName: ' + record.bundleName + 'permissionRecords: ' + JSON.stringify(record.permissionRecords));
644      try {
645        await bundleManager.queryAbilityInfo({
646          bundleName: record.bundleName,
647          action: 'action.system.home',
648          entities: ['entity.system.home']
649        }, bundleManager.AbilityFlag.GET_ABILITY_INFO_WITH_APPLICATION);
650      } catch (e) {
651        continue;
652      }
653      this.getInfo(record, (i + 1) == records.bundleRecords.length);
654      for (let j = 0; j < record.permissionRecords.length; j++) {
655        let permissionRecord = record.permissionRecords[j];
656        try {
657          let reqFlag = await acManager.getPermissionFlags(record.tokenId, permissionRecord.permissionName);
658          if (reqFlag == Constants.PERMISSION_SYSTEM_FIXED) {
659            continue;
660          }
661        } catch (err) {
662          Log.error('getPermissionFlags error: ' + JSON.stringify(err));
663        }
664        let group = getPermissionGroup(permissionRecord.permissionName as Permission);
665        if (group) {
666          let exist = groupArray.find(permissionGroup => permissionGroup.name == group.name);
667          let lastTime = permissionRecord.lastAccessTime;
668          if (!exist) {
669            let groupRecord: GroupRecordInfo = new GroupRecordInfo(
670              group.name,
671              group.groupName,
672              group.label,
673              group.icon,
674              group.permissions,
675              permissionRecord.accessCount,
676              lastTime);
677            groupArray.push(groupRecord);
678          } else {
679            exist.sum += permissionRecord.accessCount;
680            lastTime > exist.recentVisit ? exist.recentVisit = lastTime : '';
681          }
682        }
683      }
684    }
685    groupArray.sort((a, b) => { return b.recentVisit - a.recentVisit });
686    this.groups = groupArray;
687  }
688
689  aboutToAppear() {
690    this.getStrings();
691    this.getAllRecords();
692  }
693}
694