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