• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 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 UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession';
17import ability from '@ohos.ability.ability';
18import dlpPermission from '@ohos.dlpPermission';
19import hiSysEvent from '@ohos.hiSysEvent';
20import router from '@ohos.router';
21import picker from '@ohos.file.picker';
22import fileUri from '@ohos.file.fileuri';
23import fs from '@ohos.file.fs';
24import osAccount from '@ohos.account.osAccount';
25import { BusinessError } from '@ohos.base';
26import common from '@ohos.app.ability.common';
27import { EncryptingPanel } from '../common/encryptionComponents/encrypting';
28import { DlpAlertDialog } from '../common/components/dlp_alert_dialog';
29import {
30  PermissionType,
31  getOsAccountInfo,
32  checkDomainAccountInfo,
33  getUserId,
34  removeDuplicate,
35  directionStatus,
36  AuthAccount,
37  getFileUriByPath,
38  sendDlpFileCreateProperties,
39  sendDlpManagerFileConfiguration,
40  getFileSizeByUri
41} from '../common/utils';
42import Constants from '../common/constant';
43import {
44  permissionTypeSelect,
45  validDateTypeMenu,
46  validDateTypeMenuItem
47} from '../common/encryptionComponents/permission_type_select';
48import { AddStaff } from '../common/encryptionComponents/AddStaff';
49import GlobalContext from '../common/GlobalContext';
50import IDLDLPProperty from '../serviceExtensionAbility/sequenceable/dlpClass';
51import { IAuthUser } from '../serviceExtensionAbility/sequenceable/dlpClass';
52import HomeFeature from '../feature/HomeFeature';
53import { GetAlertMessage } from '../common/GetAlertMessage';
54import { HiLog } from '../common/HiLog';
55import FileUtils, { FileMsg } from '../common/FileUtils';
56
57const TAG = 'Encrypt';
58let abilityResult: ability.AbilityResult = {
59  'resultCode': 0,
60  'want': {}
61};
62
63interface dlpDataType {
64  ownerAccount: string;
65  ownerAccountID: string;
66  ownerAccountType: number;
67  authUserList: Array<dlpPermission.AuthUser>;
68  contactAccount: string;
69  offlineAccess: boolean;
70  everyoneAccessList: Array<dlpPermission.DLPFileAccess>;
71}
72let defaultDlpProperty: dlpPermission.DLPProperty = {
73  ownerAccount: '',
74  ownerAccountType: dlpPermission.AccountType.DOMAIN_ACCOUNT,
75  authUserList: [],
76  contactAccount: '',
77  offlineAccess: true,
78  ownerAccountID: '',
79  everyoneAccessList: []
80};
81
82@Component
83struct DlpDialog {
84  @State dlpProperty: dlpDataType =
85    GlobalContext.load('dlpProperty') !== undefined ? GlobalContext.load('dlpProperty') : defaultDlpProperty;
86  private homeFeature: HomeFeature = GlobalContext.load('homeFeature');
87  @State session: UIExtensionContentSession | undefined =
88    storage === undefined ? undefined : storage.get<UIExtensionContentSession>('session');
89  srcFileName: string = '';
90  isDlpFile: boolean = false;
91  linkFileName: string = '';
92  dlpAlertDialog?: CustomDialogController;
93  @State directionStatus: number = 0;
94  @State authPerm: number = 2;
95  @State handlePopupReadOnly: boolean = false;
96  @State handlePopupEdit: boolean = false;
97  @State processing: boolean = false;
98  @State prepareData: boolean = false;
99  @State validity: Date = AppStorage.get('validity') || new Date();
100  @State selectedIndex: number = AppStorage.get('permanent') === false ? 1 : 0;
101  @State permissionDict: PermissionType[] = [
102    {
103      value: $r('app.string.PERMISSION_TYPE_SELECT_TARGET'), data: 'target', index: 0
104    } as PermissionType,
105    {
106      value: $r('app.string.PERMISSION_TYPE_SELECT_ALL'), data: 'all', index: 1
107    } as PermissionType,
108    {
109      value: $r('app.string.PERMISSION_TYPE_SELECT_SELF'), data: 'self', index: 2
110    } as PermissionType
111  ];
112  @State isAccountCheckSuccess: boolean = true;
113  @State staffDataArrayReadOnly: AuthAccount[] = [];
114  @State staffDataArrayEdit: AuthAccount[] = [];
115  @State selectedPermissionTypeReadOnly: PermissionType =
116    { data: '', value: { id: 0, type: 0, params: [], bundleName: '', moduleName: '' }, index: -1 };
117  @State selectedPermissionTypeEdit: PermissionType =
118    { data: '', value: { id: 0, type: 0, params: [], bundleName: '', moduleName: '' }, index: -1 };
119
120  @Builder popupBuilderReadOnly() {
121    Row() {
122      Text($r('app.string.header_title_readonly_tips'))
123        .fontFamily('HarmonyHeiTi')
124        .fontSize($r('sys.float.ohos_id_text_size_body2'))
125        .fontColor($r('sys.color.ohos_id_color_text_primary'))
126    }
127    .width(Constants.HEADER_COLUMN_MESSAGE_TIPS)
128    .padding({
129      left: Constants.ROW_FONT_SIZE,
130      right: Constants.ROW_FONT_SIZE,
131      top: Constants.DA_MARGIN_TOP,
132      bottom: Constants.DA_MARGIN_TOP
133    })
134  }
135
136  @Builder popupBuilderEdit() {
137    Row() {
138      Text($r('app.string.header_title_edit_tips'))
139        .fontSize($r('sys.float.ohos_id_text_size_body2'))
140        .fontColor($r('sys.color.ohos_id_color_text_primary'))
141    }
142    .width(Constants.HEADER_COLUMN_MESSAGE_TIPS)
143    .padding({
144      left: Constants.ROW_FONT_SIZE,
145      right: Constants.ROW_FONT_SIZE,
146      top: Constants.DA_MARGIN_TOP,
147      bottom: Constants.DA_MARGIN_TOP
148    })
149  }
150
151  @Builder
152  MenuBuilder() {
153    validDateTypeMenuItem({ selectedIndex: $selectedIndex });
154  }
155
156  showErrorDialog(title: string | Resource, message: string | Resource) {
157    this.dlpAlertDialog = new CustomDialogController({
158      builder: DlpAlertDialog({
159        title: title,
160        message: message,
161        action: () => {
162        }
163      }),
164      autoCancel: false,
165      customStyle: true,
166      maskColor: Constants.TRANSPARENT_BACKGROUND_COLOR
167    })
168    this.dlpAlertDialog.open();
169  }
170
171  showErrorDialogNoTitle(message: Resource) {
172    this.dlpAlertDialog = new CustomDialogController({
173      builder: DlpAlertDialog({
174        message: message,
175        action: () => {
176        }
177      }),
178      autoCancel: false,
179      customStyle: true,
180      maskColor: Constants.TRANSPARENT_BACKGROUND_COLOR
181    })
182    this.dlpAlertDialog.open();
183  }
184
185  async sendDlpFileCreateFault(code: number, reason?: string) {
186    let event: hiSysEvent.SysEventInfo = {
187      domain: 'DLP',
188      name: 'DLP_FILE_CREATE',
189      eventType: hiSysEvent.EventType.FAULT,
190      params: {
191        'CODE': code,
192        'REASON': reason
193      } as Record<string, number | string>
194    };
195
196    try {
197      let userId = await getUserId();
198      if (event.params) {
199        event.params['USER_ID'] = userId;
200        await hiSysEvent.write(event);
201      }
202    } catch (err) {
203      HiLog.error(TAG, `sendDlpFileCreateFault failed, err: ${JSON.stringify(err)}`);
204    }
205  }
206
207  async sendDlpFileCreateEvent(code: number) {
208    let event: hiSysEvent.SysEventInfo = {
209      domain: 'DLP',
210      name: 'DLP_FILE_CREATE_EVENT',
211      eventType: hiSysEvent.EventType.BEHAVIOR,
212      params: {
213        'CODE': code,
214      } as Record<string, number>
215    };
216    try {
217      let userId = await getUserId();
218      if (event.params) {
219        event.params['USER_ID'] = userId;
220        await hiSysEvent.write(event);
221      }
222    } catch (err) {
223      HiLog.error(TAG, `sendDlpFileCreateEvent, err: ${JSON.stringify(err)}`);
224    }
225  }
226
227  async catchProcess() {
228    this.processing = false;
229    if (GlobalContext.load('requestIsFromSandBox') as boolean) {
230      HiLog.info(TAG, `resumeFuseLink: ${this.srcFileName}`);
231      this.homeFeature.resumeFuseLinkHome(GlobalContext.load('uri'), (err: number) => {
232        if (err !== 0) {
233          HiLog.error(TAG, `resumeFuseLink failed: ${err}`);
234        }
235      });
236    }
237  }
238
239  async setUserStat() {
240    if (this.selectedPermissionTypeReadOnly.index === 0) {
241      AppStorage.setOrCreate('hiReadScope', 'User');
242    } else if (this.selectedPermissionTypeReadOnly.index === 1) {
243      AppStorage.setOrCreate('hiReadScope', 'Everyone');
244    }
245    if (this.selectedPermissionTypeEdit.index === 0) {
246      AppStorage.setOrCreate('hiWriteScope', 'User');
247    } else if (this.selectedPermissionTypeEdit.index === 1) {
248      AppStorage.setOrCreate('hiWriteScope', 'Everyone');
249    } else {
250      AppStorage.setOrCreate('hiWriteScope', 'Onlyme');
251    }
252  }
253
254  async changeEncrypt() {
255    this.processing = true;
256    await this.setUserStat();
257    if (GlobalContext.load('requestIsFromSandBox') as boolean) {
258      try {
259        await this.stopFuseLinkHome();
260      } catch {
261        return;
262      }
263    }
264    let filePath = getContext(this).filesDir + '/' + (new Date().getTime());
265    let file: fs.File | undefined;
266    try {
267      file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
268      HiLog.info(TAG, `open temp file`);
269    } catch (err) {
270      HiLog.error(TAG, `open temp failed: ${JSON.stringify(err)}`);
271      this.showErrorDialog($r('app.string.TITLE_APP_ERROR'), $r('app.string.MESSAGE_SERVICE_INSIDE_ERROR'));
272      await this.catchProcess();
273      return;
274    } finally {
275      if (file) {
276        fs.closeSync(file);
277      }
278    };
279    let filePathUri = getFileUriByPath(filePath);
280    try {
281      await new Promise<void>((resolve, reject) => {
282        this.homeFeature.recoverDLPFileHome(GlobalContext.load('uri'), filePathUri, async (err: number) => {
283          if (err !== 0) {
284            fs.unlinkSync(filePath);
285            HiLog.error(TAG, `recoverDLPFile: ${this.srcFileName}, failed: ${err}`);
286            let errorInfo =
287              {'title': '', 'msg': $r('app.string.MESSAGE_RECOVER_DLP_ERROR') } as Record<string, string | Resource>;
288            this.showErrorDialog(errorInfo.title, errorInfo.msg);
289            await this.catchProcess();
290            reject();
291          }
292          resolve();
293        });
294      })
295    } catch {
296      return;
297    }
298    this.changeToGenDlpFileHome(filePathUri, filePath);
299  }
300
301  stopFuseLinkHome() {
302    return new Promise<void>((resolve, reject) => {
303      this.homeFeature.stopFuseLinkHome(GlobalContext.load('uri'), (err: number) => {
304        if (err !== 0) {
305          HiLog.error(TAG, `stopFuseLink failed: ${err}`);
306          this.showErrorDialog($r('app.string.TITLE_APP_ERROR'), $r('app.string.MESSAGE_SERVICE_INSIDE_ERROR'));
307          this.processing = false;
308          reject();
309        }
310        resolve();
311      });
312    })
313  }
314
315  changeToGenDlpFileHome(filePathUri: string, filePath: string) {
316    let _dlp = this.tempData();
317    this.homeFeature.genDlpFileHome(filePathUri, GlobalContext.load('uri'), _dlp, async(err: number) => {
318      if (err !== 0) {
319        HiLog.error(TAG, `generateDLPFile failed: ${err}`);
320        fs.unlinkSync(filePath);
321        let errorInfo =
322          {'title': '', 'msg': $r('app.string.MESSAGE_SERVICE_INSIDE_ERROR') } as Record<string, string | Resource>;
323        this.showErrorDialog(errorInfo.title, errorInfo.msg);
324        await this.catchProcess();
325      } else {
326        if (GlobalContext.load('requestIsFromSandBox') as boolean) {
327          this.homeFeature.replaceDLPLinkFileHome(GlobalContext.load('uri'), this.linkFileName, (err: number) => {
328            if (err !== 0) {
329              HiLog.error(TAG, `replaceDLPLinkFile failed: ${err}`);
330            }
331          });
332        }
333        fs.unlinkSync(filePath);
334        await this.catchProcess();
335        this.processing = false;
336        GlobalContext.store('dlpFileName', this.srcFileName);
337        GlobalContext.store('dlpProperty', _dlp);
338        sendDlpManagerFileConfiguration();
339        router.replaceUrl({
340          url: 'pages/encryptionSuccess',
341          params: {
342            staffDataArrayReadOnly: this.staffDataArrayReadOnly,
343            staffDataArrayEdit: this.staffDataArrayEdit,
344            selectedPermissionTypeReadOnly: this.selectedPermissionTypeReadOnly,
345            selectedPermissionTypeEdit: this.selectedPermissionTypeEdit,
346          }
347        })
348      }
349    });
350  }
351
352  async beginEncrypt() {
353    this.processing = true;
354    HiLog.info(TAG, `begin encryption for: ${this.srcFileName}`);
355    let uri: string = '';
356    let displayName: string = this.srcFileName;
357    await this.setUserStat();
358    try {
359      let srcFileUri: string = GlobalContext.load('uri');
360      let srcFileMsg: FileMsg = FileUtils.getSuffixFileMsgByUri(srcFileUri);
361      let srcFileSize: number = await getFileSizeByUri(srcFileUri);
362      AppStorage.setOrCreate('hiFileSize', srcFileSize);
363      AppStorage.setOrCreate('hiFileType', srcFileMsg.fileType);
364      let documentSaveOptions = new picker.DocumentSaveOptions();
365      displayName = displayName + '.dlp';
366      documentSaveOptions.newFileNames = [decodeURIComponent(srcFileMsg.fileName)];
367      documentSaveOptions.fileSuffixChoices = [srcFileMsg.fileType + '.dlp'];
368      documentSaveOptions.defaultFilePathUri = srcFileUri.substring(0,
369        srcFileUri.length - srcFileMsg.fileType.length - srcFileMsg.fileName.length);
370      let documentPicker = new picker.DocumentViewPicker();
371      documentPicker.save(documentSaveOptions).then(async (saveRes) => {
372        if (saveRes === undefined || saveRes.length === 0) {
373          HiLog.error(TAG, `fail to get uri`);
374          this.processing = false;
375          return;
376        }
377        HiLog.info(TAG, `get uri success`);
378        uri = saveRes[0];
379        let uriInfo: fileUri.FileUri = new fileUri.FileUri('');
380        try {
381          uriInfo = new fileUri.FileUri(uri);
382        } catch (err) {
383          HiLog.info(TAG, `fileUri fail: ${JSON.stringify(err)}`);
384        }
385        this.beginToGenDlpFileHome(srcFileUri, uri, uriInfo);
386      }).catch((err: BusinessError) => {
387        HiLog.error(TAG, `DocumentViewPicker save failed: ${JSON.stringify(err)}`);
388        let errorInfo = GetAlertMessage.getAlertMessage(err, $r('app.string.TITLE_APP_ERROR'), $r('app.string.MESSAGE_SERVICE_INSIDE_ERROR'));
389        this.showErrorDialog(errorInfo.title, errorInfo.msg);
390        this.processing = false;
391        return;
392      });
393    } catch (err) {
394      HiLog.error(TAG, `DocumentViewPicker failed: ${JSON.stringify(err)}`);
395      this.processing = false;
396      return;
397    }
398  }
399
400  beginToGenDlpFileHome(srcFileUri: string, uri: string, uriInfo: fileUri.FileUri) {
401    let _dlp = this.tempData();
402    this.homeFeature.genDlpFileHome(srcFileUri, uri, _dlp, async (err: number) => {
403      if (err !== 0) {
404        if (err === 100) {
405          this.showErrorDialog($r('app.string.TITLE_APP_ERROR'), $r('app.string.MESSAGE_SERVICE_INSIDE_ERROR'));
406          this.processing = false;
407          return;
408        }
409        try {
410          await fs.unlink(uriInfo.path);
411        } catch (err) {
412          HiLog.info(TAG, `unlink fail: ${JSON.stringify(err)}`);
413        }
414        await this.sendDlpFileCreateFault(102, (err.toString())); // 102: DLP_FILE_CREATE_ERROR
415        let errorInfo =
416          {'title': '', 'msg': $r('app.string.MESSAGE_SERVICE_INSIDE_ERROR') } as Record<string, string | Resource>;
417        this.showErrorDialog(errorInfo.title, errorInfo.msg);
418        this.processing = false;
419        return;
420      } else {
421        await this.sendDlpFileCreateEvent(201); // 201: DLP_FILE_CREATE_SUCCESS
422        let dstFileSize: number = await getFileSizeByUri(uri);
423        AppStorage.setOrCreate('hiPolicySizeEnc', dstFileSize);
424        AppStorage.setOrCreate('hiCode', 201);
425        sendDlpFileCreateProperties(dlpPermission.AccountType.DOMAIN_ACCOUNT); // 201: DLP_FILE_CREATE_SUCCESS
426        GlobalContext.store('dlpFileName', uriInfo.name);
427        GlobalContext.store('dlpProperty', _dlp);
428        GlobalContext.store('uri', uri);
429        this.processing = false;
430        sendDlpManagerFileConfiguration();
431        router.replaceUrl({
432          url: 'pages/encryptionSuccess',
433          params: {
434            staffDataArrayReadOnly: this.staffDataArrayReadOnly,
435            staffDataArrayEdit: this.staffDataArrayEdit,
436            selectedPermissionTypeReadOnly: this.selectedPermissionTypeReadOnly,
437            selectedPermissionTypeEdit: this.selectedPermissionTypeEdit,
438          }
439        })
440      }
441    });
442  }
443
444  tempData() {
445    let accountInfo: osAccount.OsAccountInfo = GlobalContext.load('accountInfo');
446    let property: dlpPermission.DLPProperty = GlobalContext.load('dlpProperty') !==
447      undefined ? GlobalContext.load('dlpProperty') : defaultDlpProperty;
448    this.staffDataArrayReadOnly = removeDuplicate(this.staffDataArrayReadOnly, 'authAccount');
449    this.staffDataArrayEdit = removeDuplicate(this.staffDataArrayEdit, 'authAccount');
450    this.staffDataArrayReadOnly = this.staffDataArrayReadOnly.filter((item) =>
451      !this.staffDataArrayEdit.some((ele) => ele.authAccount === item.authAccount)
452    );
453    property.ownerAccount = accountInfo.domainInfo.accountName;
454    property.ownerAccountID = accountInfo.domainInfo.accountId ?? '';
455    property.authUserList = [];
456    property.everyoneAccessList = [];
457    property.offlineAccess = this.selectedIndex === 0 ? true : false;
458    property.expireTime = this.selectedIndex === 0 ? 0 : this.reconfigurationTime(new Date(this.validity)).getTime();
459    if (this.selectedPermissionTypeEdit.data === 'all') {
460      property.everyoneAccessList = [dlpPermission.DLPFileAccess.CONTENT_EDIT];
461      this.staffDataArrayReadOnly = [];
462      this.staffDataArrayEdit = [];
463    } else {
464      this.propertyAddData(property);
465    }
466    let authUserListNew: IAuthUser[] = [];
467    property.authUserList.forEach(item => {
468      authUserListNew.push(
469        new IAuthUser(
470          item.authAccount,
471          item.authAccountType,
472          item.dlpFileAccess,
473          item.permExpiryTime
474        )
475      )
476    })
477    let _dlp = new IDLDLPProperty(
478      property.ownerAccount,
479      property.ownerAccountID,
480      property.ownerAccountType,
481      authUserListNew,
482      property.contactAccount,
483      property.offlineAccess,
484      property.everyoneAccessList,
485      property.expireTime
486    );
487    return _dlp;
488  }
489
490  propertyAddData(property: dlpPermission.DLPProperty) {
491    let isReadyOnlyAll = this.selectedPermissionTypeReadOnly.data === 'all';
492    if (isReadyOnlyAll) {
493      property.everyoneAccessList = [dlpPermission.DLPFileAccess.READ_ONLY];
494    }
495    if (this.selectedPermissionTypeReadOnly.data === 'all') {
496      this.staffDataArrayReadOnly = []
497    }
498    if (['all', 'self'].includes(this.selectedPermissionTypeEdit.data)) {
499      this.staffDataArrayEdit = [];
500    }
501    this.staffDataArrayReadOnly && this.staffDataArrayReadOnly.forEach(item => {
502      property.authUserList?.push({
503        authAccount: item.authAccount,
504        dlpFileAccess: dlpPermission.DLPFileAccess.READ_ONLY,
505        permExpiryTime: Date.UTC(9999, 1, 1),
506        authAccountType: dlpPermission.AccountType.DOMAIN_ACCOUNT,
507      })
508    })
509    this.staffDataArrayEdit && this.staffDataArrayEdit.forEach(item => {
510      property.authUserList?.push({
511        authAccount: item.authAccount,
512        dlpFileAccess: dlpPermission.DLPFileAccess.CONTENT_EDIT,
513        permExpiryTime: Date.UTC(9999, 1, 1),
514        authAccountType: dlpPermission.AccountType.DOMAIN_ACCOUNT,
515      })
516    })
517  }
518
519  async prepareDlpProperty() {
520    let accountInfo: osAccount.OsAccountInfo = GlobalContext.load('accountInfo') as osAccount.OsAccountInfo;
521    this.dlpProperty.ownerAccount = accountInfo.domainInfo.accountName;
522    this.dlpProperty.contactAccount = accountInfo.domainInfo.accountName;
523    this.dlpProperty.ownerAccountID = accountInfo.domainInfo.accountId ?? '';
524    let ownerAccount: dlpPermission.AuthUser = {
525      authAccount: this.dlpProperty.ownerAccount,
526      dlpFileAccess: dlpPermission.DLPFileAccess.FULL_CONTROL,
527      permExpiryTime: Date.UTC(9999, 1, 1),
528      authAccountType: dlpPermission.AccountType.DOMAIN_ACCOUNT,
529    }
530    this.dlpProperty.authUserList?.push(ownerAccount)
531    return
532  }
533
534  async showData(defaultDlpProperty: dlpPermission.DLPProperty) {
535    let routerParams: Record<string, AuthAccount[]> = router.getParams() as Record<string, AuthAccount[]>;
536    this.permissionDict.forEach(async (item, index) => {
537      this.permissionDict[index].value =
538        $r(await getContext(this).resourceManager.getStringValue(item.value.id))
539    })
540    let readOnlyData: dlpPermission.AuthUser[] =
541      defaultDlpProperty.authUserList?.filter((item: dlpPermission.AuthUser) => {
542      return item.dlpFileAccess === 1;
543    }) ?? []
544    let editData: dlpPermission.AuthUser[] = defaultDlpProperty.authUserList?.filter((item: dlpPermission.AuthUser) => {
545      return item.dlpFileAccess === 2;
546    }) ?? []
547    const filterEditFilter = () => {
548      if (editData.length === 0) {
549        this.selectedPermissionTypeEdit = this.permissionDict[2];
550      } else {
551        this.staffDataArrayEdit = routerParams.staffDataArrayEdit as AuthAccount[];
552      }
553    }
554    if ((defaultDlpProperty.everyoneAccessList !== undefined) && (defaultDlpProperty.everyoneAccessList.length > 0)) {
555      let perm = Math.max(...defaultDlpProperty.everyoneAccessList);
556      if (perm === dlpPermission.DLPFileAccess.CONTENT_EDIT) {
557        this.selectedPermissionTypeEdit = this.permissionDict[1];
558        this.staffDataArrayReadOnly = readOnlyData;
559      } else if (perm === dlpPermission.DLPFileAccess.READ_ONLY) {
560        this.selectedPermissionTypeReadOnly = this.permissionDict[1];
561        this.staffDataArrayReadOnly = [];
562        filterEditFilter()
563      }
564    } else {
565      this.staffDataArrayReadOnly = routerParams.staffDataArrayReadOnly as AuthAccount[];
566      filterEditFilter()
567    }
568  }
569
570  async checkAccount() {
571    try {
572      GlobalContext.store('accountInfo', await getOsAccountInfo());
573    } catch (err) {
574      HiLog.error(TAG, `getOsAccountInfo failed: ${JSON.stringify(err)}`);
575      if (this.session !== undefined) {
576        let errorInfo = GetAlertMessage.getAlertMessage({ code: Constants.ERR_JS_GET_ACCOUNT_ERROR } as BusinessError);
577        this.showErrorDialog(errorInfo.title, errorInfo.msg);
578      } else {
579        await GetAlertMessage.startAlertAbility(getContext(this) as common.UIAbilityContext,
580          { code: Constants.ERR_JS_GET_ACCOUNT_ERROR } as BusinessError);
581      }
582      return;
583    }
584    let codeMessage = checkDomainAccountInfo(GlobalContext.load('accountInfo') as osAccount.OsAccountInfo);
585    if (codeMessage) {
586      if (this.session !== undefined) {
587        let errorInfo = GetAlertMessage.getAlertMessage(
588          { code: codeMessage } as BusinessError);
589        this.showErrorDialog(errorInfo.title, errorInfo.msg);
590      } else {
591        await GetAlertMessage.startAlertAbility(getContext(this) as common.UIAbilityContext,
592          { code: codeMessage } as BusinessError);
593      }
594      return;
595    }
596  }
597
598  reconfigurationTime(date: Date) {
599    let year = date.getFullYear();
600    let month = date.getMonth();
601    let day = date.getDate();
602    return new Date(year, month, day, 23, 59, 59);
603  }
604
605  async aboutToAppear() {
606    this.prepareData = true;
607    await this.checkAccount();
608    AppStorage.setOrCreate('hiAccountVerifySucc', 0);
609    AppStorage.setOrCreate('hiAccountVerifyFail', 0);
610    if (GlobalContext.load('requestIsFromSandBox') as boolean) {
611      HiLog.info(TAG, `encryption request from sandbox`);
612      this.linkFileName = GlobalContext.load('linkFileName') as string;
613      this.srcFileName = GlobalContext.load('dlpFileName') as string;
614      setTimeout(() => {
615        this.showData(GlobalContext.load('dlpProperty'));
616      }, Constants.ENCRYPTION_SET_TIMEOUT_TIME)
617      this.isDlpFile = true;
618      setTimeout(() => {
619        this.prepareData = false;
620      }, Constants.ENCRYPTION_SET_TIMEOUT_TIME)
621      return
622    } else {
623      let routerParams = router.getParams();
624      if (routerParams !== undefined) { // is a dlp file
625        HiLog.info(TAG, `encryption request from router`);
626        this.srcFileName = GlobalContext.load('dlpFileName') as string;
627      } else { // not a dlp file
628        HiLog.info(TAG, `encryption request from ability`);
629        this.srcFileName = GlobalContext.load('originFileName') as string;
630      }
631    }
632
633    let isDlpSuffix: boolean = this.srcFileName.endsWith('.dlp');
634    if (!isDlpSuffix) {
635      await this.prepareDlpProperty();
636      this.isDlpFile = false;
637    } else {
638      setTimeout(() => {
639        this.showData(GlobalContext.load('dlpProperty'));
640      }, Constants.ENCRYPTION_SET_TIMEOUT_TIME)
641      this.isDlpFile = true;
642    }
643    setTimeout(() => {
644      this.prepareData = false;
645    }, Constants.ENCRYPTION_SET_TIMEOUT_TIME)
646
647    this.directionStatus = (getContext(this) as common.UIAbilityContext).config.direction ?? -1;
648    directionStatus((counter) => {
649      this.directionStatus = counter;
650    })
651  }
652
653  build() {
654    Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
655      EncryptingPanel({ processing: $processing })
656      if (!this.processing) {
657        Column() {
658          Row() {
659            Text($r('app.string.header_title'))
660              .fontWeight(FontWeight.Bold)
661              .fontFamily($r('app.string.typeface'))
662              .fontColor($r('sys.color.ohos_id_color_text_primary'))
663              .fontSize($r('sys.float.ohos_id_text_size_dialog_tittle'))
664              .lineHeight(Constants.HEADER_TEXT_LINE_HEIGHT)
665              .width(Constants.HEADER_TEXT_WIDTH)
666              .align(Alignment.Start)
667          }
668          .width(Constants.HEADER_COLUMN_WIDTH)
669          .height(Constants.HEADER_COLUMN_HEIGHT)
670          .padding({
671            left: Constants.HEADER_COLUMN_PADDING_LEFT,
672            right: Constants.HEADER_COLUMN_PADDING_RIGHT
673          })
674          .margin({ bottom: Constants.HEADER_COLUMN_MARGIN_BOTTOM });
675
676          Scroll() {
677            Column() {
678              Row() {
679                Text($r('app.string.header_title_list'))
680                  .fontWeight(FontWeight.Regular)
681                  .fontColor($r('sys.color.ohos_id_color_text_secondary'))
682                  .fontSize($r('sys.float.ohos_id_text_size_body1'))
683                  .width(Constants.HEADER_TEXT_WIDTH)
684                  .align(Alignment.Start)
685              }
686              .width(Constants.HEADER_COLUMN_WIDTH)
687
688              Row() {
689                Text($r('app.string.header_title_readonly'))
690                  .fontWeight(FontWeight.Medium)
691                  .fontColor($r('sys.color.ohos_id_color_text_primary'))
692                  .fontSize($r('sys.float.ohos_id_text_size_body1'))
693                Image($r('app.media.ic_public_detail'))
694                  .width(Constants.FOOTER_ROW_PAD_RIGHT)
695                  .height(Constants.FOOTER_ROW_PAD_RIGHT)
696                  .margin({ left: Constants.AP_TEXT_PAD_RIGHT })
697                  .fillColor($r('sys.color.icon_secondary'))
698                  .onClick(() => {
699                    this.handlePopupReadOnly = !this.handlePopupReadOnly
700                  })
701                  .draggable(false)
702                  .bindPopup(this.handlePopupReadOnly, {
703                    builder: this.popupBuilderReadOnly,
704                    placement: Placement.BottomLeft,
705                    offset: { x: Constants.POPUP_OFFSET_X },
706                    enableArrow: true,
707                    showInSubWindow: false,
708                    onStateChange: (e) => {
709                      if (!e.isVisible) {
710                        this.handlePopupReadOnly = false
711                      }
712                    }
713                  })
714                Blank()
715                permissionTypeSelect({
716                  selectedItem: $selectedPermissionTypeReadOnly,
717                  staffArray: $staffDataArrayReadOnly,
718                  isDisable: this.selectedPermissionTypeEdit?.data === 'all',
719                  isReadType: true
720                })
721              }
722              .width(Constants.FOOTER_ROW_WIDTH)
723              .height(Constants.HEADER_COLUMN_HEIGHT_READONLY)
724              .margin({ top: Constants.FOOTER_ROW_MARGIN })
725
726              Row() {
727                if (!['all', 'self'].includes(this.selectedPermissionTypeReadOnly?.data ?? '')) {
728                  AddStaff({
729                    isAccountCheckSuccess: $isAccountCheckSuccess,
730                    staffArray: $staffDataArrayReadOnly,
731                    isDisable: this.selectedPermissionTypeEdit?.data === 'all',
732                  })
733                }
734              }
735              .margin({ bottom: Constants.ENCRYPTION_STAFF_ITEM_MARGIN_BOTTOM })
736
737              Row() {
738                Text($r('app.string.header_title_edit'))
739                  .fontWeight(FontWeight.Medium)
740                  .fontColor($r('sys.color.ohos_id_color_text_primary'))
741                  .fontSize($r('sys.float.ohos_id_text_size_body1'))
742                Image($r('app.media.ic_public_detail'))
743                  .width(Constants.FOOTER_ROW_PAD_RIGHT)
744                  .height(Constants.FOOTER_ROW_PAD_RIGHT)
745                  .margin({ left: Constants.AP_TEXT_PAD_RIGHT })
746                  .fillColor($r('sys.color.icon_secondary'))
747                  .onClick(() => {
748                    this.handlePopupEdit = !this.handlePopupEdit
749                  })
750                  .draggable(false)
751                  .bindPopup(this.handlePopupEdit, {
752                    builder: this.popupBuilderEdit,
753                    placement: Placement.BottomLeft,
754                    offset: { x: Constants.POPUP_OFFSET_X },
755                    enableArrow: true,
756                    showInSubWindow: false,
757                    onStateChange: (e) => {
758                      if (!e.isVisible) {
759                        this.handlePopupEdit = false
760                      }
761                    }
762                  })
763                Blank()
764                permissionTypeSelect({
765                  selectedItem: $selectedPermissionTypeEdit,
766                  staffArray: $staffDataArrayEdit,
767                  isDisable: false,
768                  isReadType: false
769                })
770              }
771              .width(Constants.FOOTER_ROW_WIDTH)
772              .height(Constants.HEADER_COLUMN_HEIGHT_READONLY)
773
774              Row() {
775                if (!['all', 'self'].includes(this.selectedPermissionTypeEdit?.data ?? '')) {
776                  AddStaff({
777                    isAccountCheckSuccess: $isAccountCheckSuccess,
778                    staffArray: $staffDataArrayEdit,
779                    isDisable: false
780                  })
781                }
782              }
783              .margin({ bottom: Constants.ENCRYPTION_STAFF_ITEM_MARGIN_BOTTOM })
784
785              Row() {
786                Text($r('app.string.Document_valid_until'))
787                  .fontWeight(FontWeight.Medium)
788                  .fontColor($r('sys.color.ohos_id_color_text_primary'))
789                  .fontSize($r('sys.float.ohos_id_text_size_body1'))
790                Blank()
791                if (this.selectedIndex === 1) {
792                  CalendarPicker({ selected: new Date(this.validity) })
793                    .onChange((value) => {
794                      this.validity = value;
795                    })
796                  Row() {
797                    Image($r('app.media.rectangle'))
798                      .width(Constants.VALIDITY_IMAGE_WIDTH)
799                      .fillColor($r('sys.color.ohos_id_color_tertiary'))
800                  }
801                  .height(Constants.VALIDITY_IMAGE_HEIGHT)
802                  .padding({
803                    right: Constants.VALIDITY_IMAGE_PADDING_RIGHT,
804                    left: Constants.VALIDITY_IMAGE_PADDING_LEFT
805                  })
806                  .bindMenu(this.MenuBuilder, { placement: Placement.BottomRight, showInSubWindow: false })
807                } else {
808                  validDateTypeMenu({
809                    selectedIndex: $selectedIndex,
810                    isDisable: false,
811                  })
812                }
813              }
814              .width(Constants.FOOTER_ROW_WIDTH)
815              .height(Constants.HEADER_COLUMN_HEIGHT_READONLY)
816            }
817          }.constraintSize({
818            maxHeight: this.directionStatus ===
819              0 ? Constants.CHANGE_MAX_HEIGHT : Constants.ENCRYPTION_SUCCESS_MAX_HEIGHT
820          })
821          .padding({
822            left: Constants.HEADER_COLUMN_PADDING_LEFT,
823            right: Constants.HEADER_COLUMN_PADDING_RIGHT
824          })
825
826          Flex({ direction: FlexDirection.Row }) {
827            Button($r('app.string.ban'), { type: ButtonType.Capsule, stateEffect: true })
828              .backgroundColor($r('sys.color.ohos_id_color_button_normal'))
829              .width(Constants.HEADER_TEXT_WIDTH)
830              .focusable(true)
831              .fontColor($r('sys.color.ohos_id_color_text_primary_activated'))
832              .height(Constants.FOOTER_HEIGHT)
833              .onClick(async (event) => {
834                if (this.isDlpFile && !(GlobalContext.load('requestIsFromSandBox') as boolean)) {
835                  this.homeFeature.closeDLPFileHome(GlobalContext.load('uri'), (err: number) => {
836                    if (err !== 0) {
837                      HiLog.error(TAG, `closeDLPFile failed: ${err}`);
838                    }
839                  });
840                }
841                if (this.session !== undefined) {
842                  this.session.terminateSelfWithResult({
843                    'resultCode': 0,
844                    'want': {
845                      'bundleName': Constants.DLP_MANAGER_BUNDLE_NAME,
846                    },
847                  });
848                } else {
849                  if (GlobalContext.load('fileOpenHistoryFromMain')) {
850                    (GlobalContext.load('fileOpenHistoryFromMain') as Map<string, Object>).delete(GlobalContext.load('uri') as string)
851                  }
852                  abilityResult.resultCode = 0;
853                  (getContext(this) as common.UIAbilityContext).terminateSelfWithResult(abilityResult);
854                }
855              })
856              .margin({ right: Constants.ENCRYPTION_PROTECTION_BUTTON_MARGIN })
857            Button($r('app.string.sure'), {
858              type: ButtonType.Capsule, stateEffect: true
859            })
860              .backgroundColor($r('sys.color.ohos_id_color_button_normal'))
861              .width(Constants.HEADER_TEXT_WIDTH)
862              .focusable(true)
863              .fontColor($r('sys.color.ohos_id_color_text_primary_activated'))
864              .enabled(
865                this.isAccountCheckSuccess &&
866                (this.staffDataArrayReadOnly.length > 0 ||
867                this.staffDataArrayEdit.length > 0 ||
868                ['all', 'self'].includes(this.selectedPermissionTypeReadOnly.data ?? '') ||
869                ['all', 'self'].includes(this.selectedPermissionTypeEdit.data ?? ''))
870              )
871              .height(Constants.FOOTER_BUTTON_HEIGHT)
872              .onClick(async (event) => {
873                AppStorage.setOrCreate('hiValidDate', false);
874                if (this.selectedIndex === 1) {
875                  let currentTime = new Date().getTime();
876                  let validity = this.reconfigurationTime(new Date(this.validity)).getTime();
877                  if (currentTime >= validity) {
878                    this.showErrorDialogNoTitle($r('app.string.Timeout_is_not_supported'));
879                    return;
880                  }
881                  AppStorage.setOrCreate('validity', this.reconfigurationTime(new Date(this.validity)));
882                  AppStorage.setOrCreate('hiValidDate', true);
883                }
884                AppStorage.setOrCreate('permanent', this.selectedIndex ? false : true);
885                AppStorage.setOrCreate('hiAdvancedSettings', false);
886                AppStorage.setOrCreate('hiStorePath', false);
887                if (this.isDlpFile) {
888                  AppStorage.setOrCreate('hiOperation', 'Change_policy');
889                  await this.changeEncrypt();
890                } else {
891                  AppStorage.setOrCreate('hiOperation', 'Pack_policy');
892                  await this.beginEncrypt();
893                }
894              })
895              .margin({ left: Constants.ENCRYPTION_PROTECTION_BUTTON_MARGIN })
896          }
897          .margin({
898            left: Constants.ENCRYPTION_BUTTON_TO_BUTTON_WIDTH,
899            right: Constants.ENCRYPTION_BUTTON_TO_BUTTON_WIDTH,
900            bottom: Constants.ENCRYPTION_BUTTON_MARGIN_BOTTOM,
901            top: Constants.ENCRYPTION_BUTTON_TO_BUTTON_WIDTH
902          })
903        }
904        .visibility(this.processing ? Visibility.Hidden : Visibility.Visible)
905        .width(Constants.ENCRYPTION_PC_FIXING_WIDTH)
906        .backgroundColor($r('sys.color.ohos_id_color_dialog_bg'))
907        .borderRadius($r('sys.float.ohos_id_corner_radius_dialog'))
908        .constraintSize({minWidth: Constants.ENCRYPTION_PC_FIXING_WIDTH})
909        .backgroundBlurStyle(BlurStyle.COMPONENT_ULTRA_THICK);
910      }
911    }
912  }
913}
914
915let storage = LocalStorage.getShared();
916@Entry(storage)
917@Component
918struct encryptionProtection {
919  aboutToAppear() {
920  }
921
922  build() {
923    GridRow({
924      columns: {
925        xs: Constants.XS_COLUMNS,
926        sm: Constants.SM_COLUMNS,
927        md: Constants.MD_COLUMNS,
928        lg: Constants.LG_COLUMNS
929      },
930      gutter: Constants.DIALOG_GUTTER
931    }) {
932      GridCol({
933        span: {
934          xs: Constants.XS_SPAN,
935          sm: Constants.SM_SPAN,
936          md: Constants.DIALOG_MD_SPAN,
937          lg: Constants.DIALOG_LG_SPAN
938        },
939        offset: {
940          xs: Constants.XS_OFFSET,
941          sm: Constants.SM_OFFSET,
942          md: Constants.DIALOG_MD_OFFSET,
943          lg: Constants.DIALOG_LG_OFFSET
944        }
945      }) {
946        Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center,
947          direction: FlexDirection.Column }) {
948          DlpDialog()
949        }
950      }
951    }
952    .backgroundColor($r('sys.color.mask_fourth'))
953  }
954}
955