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