feat: add charx import

This commit is contained in:
kwaroran
2024-06-03 16:59:44 +09:00
parent 8dff1a6cde
commit ad7ce3f0d1
3 changed files with 118 additions and 7 deletions

View File

@@ -1,5 +1,6 @@
import { AppendableBuffer, type LocalWriter, type VirtualWriter } from "../storage/globalApi";
import { AppendableBuffer, saveAsset, type LocalWriter, type VirtualWriter } from "../storage/globalApi";
import * as fflate from "fflate";
import { sleep } from "../util";
export async function processZip(dataArray: Uint8Array): Promise<string> {
const jszip = await import("jszip");
@@ -69,4 +70,74 @@ export class CharXWriter{
await this.writer.close()
}
}
}
export class CharXReader{
unzip:fflate.Unzip
assets:{[key:string]:string} = {}
assetBuffers:{[key:string]:AppendableBuffer} = {}
assetPromises:Promise<void>[] = []
excludedFiles:string[] = []
cardData:string|undefined
constructor(){
this.unzip = new fflate.Unzip()
this.unzip.register(fflate.UnzipInflate)
this.unzip.onfile = (file) => {
const assetIndex = file.name
this.assetBuffers[assetIndex] = new AppendableBuffer()
file.ondata = (err, dat, final) => {
this.assetBuffers[assetIndex].append(dat)
if(final){
const assetData = this.assetBuffers[assetIndex].buffer
if(assetData.byteLength > 50 * 1024 * 1024){
this.excludedFiles.push(assetIndex)
}
else if(file.name === 'card.json'){
this.cardData = new TextDecoder().decode(assetData)
}
else{
this.assetPromises.push((async () => {
const assetId = await saveAsset(assetData)
this.assets[assetIndex] = assetId
})())
}
}
}
if(file.originalSize ?? 0 < 50 * 1024 * 1024){
file.start()
}
}
}
async read(data:Uint8Array|File|ReadableStream<Uint8Array>){
if(data instanceof Uint8Array){
this.unzip.push(data, true)
}
if(data instanceof File){
const reader = data.stream().getReader()
while(true){
const {done, value} = await reader.read()
if(done){
break
}
this.unzip.push(value, false)
}
this.unzip.push(new Uint8Array(0), true)
}
if(data instanceof ReadableStream){
const reader = data.getReader()
while(true){
const {done, value} = await reader.read()
if(done){
break
}
this.unzip.push(value, false)
}
this.unzip.push(new Uint8Array(0), true)
}
await sleep(500)
await Promise.all(this.assetPromises)
}
}