Skip to content

Commit

Permalink
misc: code clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
SolidFaker committed Nov 16, 2024
1 parent e578b5f commit 6ff65c5
Show file tree
Hide file tree
Showing 8 changed files with 217 additions and 442 deletions.
12 changes: 4 additions & 8 deletions entry/src/main/ets/dialogs/DropFilesDialog.ets
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,9 @@ export struct DropFilesDialog {
private appCtx = AppStorage.get<common.UIAbilityContext>('appContext') as common.UIAbilityContext;
build() {
Column({ space: 10}) {
Row()
{
Row()
{
Column()
{
Row() {
Row() {
Column() {
SymbolGlyph(this.replaceFlag ? $r('sys.symbol.chevron_down_2_circle') : $r('sys.symbol.arrow_down_circle'))
.fontWeight(FontWeight.Lighter)
.fontSize(96)
Expand All @@ -26,7 +23,6 @@ export struct DropFilesDialog {
.fontSize(20)
.fontColor($r('app.color.str_gray'))
}

}
.width('100%')
.height('40%')
Expand All @@ -35,7 +31,7 @@ export struct DropFilesDialog {
.onDrop((event?: DragEvent, extraParams?: string) => {
console.log("enter onDrop")
if (event!=null) {
let records: Array<unifiedDataChannel.UnifiedRecord> = event.getData().getRecords();
let records: Array<unifiedDataChannel.UnifiedRecord >= event.getData().getRecords();
let plainfile: unifiedDataChannel.File = records[0] as unifiedDataChannel.File;
this.appCtx.eventHub.emit('onFileDrop',plainfile.uri);
}
Expand Down
130 changes: 26 additions & 104 deletions entry/src/main/ets/pages/Index.ets
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { FortiConfigDialog } from '../dialogs/FortiConfigDialog';
import { scanCore, scanBarcode } from '@kit.ScanKit';
import { TokenItem } from '../components/TokenItem';
import { SettingPage } from '../pages/SettingPage'
import { HashMap, util } from '@kit.ArkTS';
import { util } from '@kit.ArkTS';
import { fileIo as fs } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { router } from '@kit.ArkUI';
Expand All @@ -20,27 +20,14 @@ import CommonEventManager from '@ohos.commonEventManager';
import { TokenStore } from '../utils/TokenStore';
import { PermissionManager } from '../utils/PermissionManager';
import { DropFilesDialog } from '../dialogs/DropFilesDialog';
import { unifiedDataChannel, uniformTypeDescriptor } from '@kit.ArkData';
import { uniformTypeDescriptor } from '@kit.ArkData';
import { EncryptionPassWordDialog } from '../dialogs/EncryptionPassWordDialog';
import { faceDetector } from '@kit.CoreVisionKit';
import MediaFileUri from '../utils/MediaFileUri';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import {
base32Decode,
base32Encode,
stringToIntArray,
intArrayToString,
generateFileNameWithDate
} from '../utils/TokenUtils'
import { restoreFromBackup } from '../utils/TokenBackup';

const TAG = 'PrivacySubscribe';

let tkStore = TokenStore.getInstance();
class backup_file {
magic!: number;
version!: number;
configs!: Array<TokenConfig>;
}

@Entry
@ComponentV2
struct Index {
Expand Down Expand Up @@ -71,10 +58,8 @@ struct Index {
};
//拖拽文件弹框
private DropFilesDialogController: CustomDialogController | null = new CustomDialogController({
builder: DropFilesDialog({
}),
cancel: () => {
},
builder: DropFilesDialog({}),
cancel: () => {},
autoCancel: true,
openAnimation:({
delay: 0,
Expand Down Expand Up @@ -178,37 +163,39 @@ struct Index {
}
})

this.appCtx.eventHub.on('onFileDrop',( plainfile:string)=>{

this.backup_select_uri = plainfile;
if (this.backup_select_uri.endsWith('.bak')) {
//后缀bak为加密包 唤醒加密导入弹窗
this.dialogController?.open();
this.appCtx.eventHub.on('onFileDrop', (uri: string) => {
this.backup_select_uri = uri;
if (this.backup_select_uri.endsWith('.bak')) { // 后缀bak为加密包 唤醒加密导入弹窗
this.password_input_dialog?.open();
} else if (this.backup_select_uri.endsWith('.json')) {
this.readContentFromSelectedFile(this.backup_select_uri);
restoreFromBackup(uri).then((backup) => {
this.updateTokenConfigs(backup.configs).then(() => {
tkStore.sortTokens();
});
});
}
setTimeout(()=>{
this.DropFilesDialogIsOpen=false;
setTimeout(() => {
this.DropFilesDialogIsOpen = false;
this.DropFilesDialogController?.close();
},250)
}, 250)
});
}

//region 导入
private backup_magic: number = 0x55aaeebb;
private mediaFileUri: MediaFileUri = new MediaFileUri();
private dialogController: CustomDialogController | null = new CustomDialogController({
private password_input_dialog: CustomDialogController | null = new CustomDialogController({
builder: EncryptionPassWordDialog({
cancel: () => {
},
cancel: () => {},
confirm: (password: string) => {
this.readContentFromSelectedFileEncryption(this.backup_select_uri, password);
restoreFromBackup(this.backup_select_uri, true, password).then((backup) => {
this.updateTokenConfigs(backup.configs).then(() => {
tkStore.sortTokens();
});
});
},
textValue: "",
inputValue: ""
}),
cancel: () => {
},
cancel: () => {},
autoCancel: true,
onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
console.info("reason=" + JSON.stringify(dismissDialogAction.reason))
Expand All @@ -226,71 +213,6 @@ struct Index {
customStyle: false,
cornerRadius: 10,
})
// 加密导入
async readContentFromSelectedFileEncryption(myUri: string, password: string): Promise<void> {
let backup_string = this.mediaFileUri.readFileContent(myUri);
try {
this.decryptFile(backup_string, password).then((backup_string) => {
let backup: backup_file = JSON.parse(backup_string);
if (backup.magic == this.backup_magic) {
this.updateTokenConfigs(backup.configs).then(()=>{
tkStore.sortTokens();
});
} else {
promptAction.showToast({ message: 'Error: invalid backup file!' })
}
})
} catch (err) {
promptAction.showToast({ message: err.message })
}

}
async decryptFile(file_enc: string, user_key: string): Promise<string> {
let aes_decoder = cryptoFramework.createCipher('AES128|CBC|PKCS7');
let aes_iv: cryptoFramework.IvParamsSpec = {
algName: "IvParamsSpec",
iv: { data: stringToIntArray('ohtotptokenaesiv') }
};
let spec: cryptoFramework.PBKDF2Spec = {
algName: 'PBKDF2',
password: user_key,
salt: new Uint8Array(16),
iterations: 10000,
keySize: 16
};
let kdf = cryptoFramework.createKdf('PBKDF2|SHA256');
let symKeyBlob = kdf.generateSecretSync(spec);
let aesGenerator = cryptoFramework.createSymKeyGenerator('AES128');
let aes_key = aesGenerator.convertKeySync(symKeyBlob);
await aes_decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, aes_key, aes_iv).catch((reason: string) => {
promptAction.showToast({ message: reason });
});
return new Promise<string>((resolve) => {
let file_buf = base32Decode(file_enc);
aes_decoder.doFinal({ data: file_buf }).then((decryptData) => {
let decoder = new util.TextDecoder()
resolve(decoder.decodeToString(decryptData.data));
}).catch((reason: BusinessError) => {
promptAction.showToast({ message: reason.message });
});
});
}
async readContentFromSelectedFile(myUri: string): Promise<void> {
let backup_string = this.mediaFileUri.readFileContent(myUri);
try {
let backup: backup_file = JSON.parse(intArrayToString(base32Decode(backup_string).buffer as ArrayBuffer));
if (backup.magic == this.backup_magic) {
this.updateTokenConfigs(backup.configs).then(()=>{
tkStore.sortTokens();
});
} else {
promptAction.showToast({ message: 'Error: invalid backup file!' })
}
} catch (err) {
promptAction.showToast({ message: err.message })
}

}
//endregion

async onTokenChanged(): Promise<void> {
Expand Down
Loading

0 comments on commit 6ff65c5

Please sign in to comment.