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