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