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