feat: add cap storage utilitys

This commit is contained in:
kwaroran
2024-05-24 23:14:44 +09:00
parent 38a7e514ac
commit 7e1f1dc1d2
3 changed files with 87 additions and 8 deletions

View File

@@ -1,12 +1,19 @@
import * as CapFS from '@capacitor/filesystem'
import { get } from 'svelte/store';
import { DataBase } from './database';
import { getUnpargeables } from './globalApi';
function encodeKeySafe(oldKey:string){
return oldKey.replace(/_/g, '__').replace(/\//g, '_s').replace(/\./g, '_d').replace(/\$/g, '_t').replace(/-/g, '_h').replace(/:/g, '_c') + '.bin'
}
function decodeKeySafe(newKey:string){
newKey = newKey.substring(0, newKey.length-4)
return newKey.replace(/_c/g, ':').replace(/_h/g, '-').replace(/_t/g, '$').replace(/_d/g, '.').replace(/_s/g, '/').replace(/__/g, '_')
}
export class MobileStorage{
async setItem(key:string, value:Uint8Array) {
await CapFS.Filesystem.writeFile({
path: key,
path: encodeKeySafe(key),
data: Buffer.from(value).toString('base64'),
directory: CapFS.Directory.External,
recursive: true,
@@ -15,7 +22,7 @@ export class MobileStorage{
async getItem(key:string):Promise<Buffer> {
try {
const b64 = await CapFS.Filesystem.readFile({
path: key,
path: encodeKeySafe(key),
directory: CapFS.Directory.External,
})
return Buffer.from(b64.data as string, 'base64')
@@ -29,15 +36,58 @@ export class MobileStorage{
}
}
async keys():Promise<string[]>{
let db = get(DataBase)
return getUnpargeables(db, 'pure')
const files = await CapFS.Filesystem.readdir({
path: '',
directory: CapFS.Directory.External,
})
return files.files.map(f=>decodeKeySafe(f.name))
}
async removeItem(key:string){
await CapFS.Filesystem.deleteFile({
path: key,
path: encodeKeySafe(key),
directory: CapFS.Directory.External,
})
}
listItem = this.keys
}
function byteLengthToString(byteLength:number):string{
if(byteLength < 1024){
return byteLength + ' B'
}
if(byteLength < 1024*1024){
return (byteLength/1024).toFixed(2) + ' KB'
}
if(byteLength < 1024*1024*1024){
return (byteLength/1024/1024).toFixed(2) + ' MB'
}
return (byteLength/1024/1024/1024).toFixed(2) + ' GB'
}
export async function capStorageInvestigation(){
const investResults:{
key:string,
size:string,
}[] = []
const files = await CapFS.Filesystem.readdir({
path: '',
directory: CapFS.Directory.External,
})
for(const file of files.files){
const key = decodeKeySafe(file.name)
const size = file.size
investResults.push({key, size: byteLengthToString(size)})
}
const estimated = await navigator.storage.estimate()
if(estimated){
investResults.push({key:'webstorage', size:byteLengthToString(estimated.usage)})
}
return investResults
}