s3si.ts/src/exporters/file.ts

80 lines
2.0 KiB
TypeScript
Raw Normal View History

2022-10-20 22:47:56 -04:00
import { BattleExporter, VsBattle } from "../types.ts";
2022-10-21 07:09:30 -04:00
import { base64, path } from "../../deps.ts";
2022-10-20 09:45:59 -04:00
import { NSOAPP_VERSION, S3SI_VERSION } from "../constant.ts";
type FileExporterType = {
type: "VS" | "COOP";
nsoVersion: string;
s3siVersion: string;
exportTime: string;
2022-10-20 22:47:56 -04:00
data: VsBattle;
2022-10-20 09:45:59 -04:00
};
2022-10-21 03:56:43 -04:00
/**
* Don't save url in exported file
*/
function replacer(key: string, value: unknown): unknown {
return ["url", "maskImageUrl", "overlayImageUrl"].includes(key)
? undefined
: value;
}
2022-10-20 09:45:59 -04:00
/**
* Exporter to file.
*
* This is useful for debugging. It will write each battle detail to a file.
2022-10-20 23:14:29 -04:00
* Timestamp is used as filename. Example: 20210101T000000Z.json
2022-10-20 09:45:59 -04:00
*/
2022-10-20 22:47:56 -04:00
export class FileExporter implements BattleExporter<VsBattle> {
2022-10-20 09:45:59 -04:00
name = "file";
constructor(private exportPath: string) {
}
2022-10-20 23:14:29 -04:00
getFilenameById(id: string) {
const fullId = base64.decode(id);
const ts = new TextDecoder().decode(
fullId.slice(fullId.length - 52, fullId.length - 37),
);
2022-10-21 03:56:43 -04:00
if (!/\d{8}T\d{6}/.test(ts)) {
throw new Error("Invalid battle ID");
}
2022-10-20 23:14:29 -04:00
return `${ts}Z.json`;
}
2022-10-20 22:47:56 -04:00
async exportBattle(battle: VsBattle) {
2022-10-20 09:45:59 -04:00
await Deno.mkdir(this.exportPath, { recursive: true });
2022-10-20 23:14:29 -04:00
const filename = this.getFilenameById(battle.detail.id);
2022-10-20 09:45:59 -04:00
const filepath = path.join(this.exportPath, filename);
const body: FileExporterType = {
type: "VS",
nsoVersion: NSOAPP_VERSION,
s3siVersion: S3SI_VERSION,
exportTime: new Date().toISOString(),
2022-10-20 22:47:56 -04:00
data: battle,
2022-10-20 09:45:59 -04:00
};
2022-10-21 03:56:43 -04:00
await Deno.writeTextFile(
filepath,
JSON.stringify(body, replacer),
);
2022-10-20 09:45:59 -04:00
}
async notExported(list: string[]): Promise<string[]> {
const out: string[] = [];
for (const id of list) {
2022-10-20 23:14:29 -04:00
const filename = this.getFilenameById(id);
const filepath = path.join(this.exportPath, filename);
const isFile = await Deno.stat(filepath).then((f) => f.isFile).catch(() =>
false
);
2022-10-20 22:57:08 -04:00
if (!isFile) {
out.push(id);
}
}
return out;
2022-10-20 09:45:59 -04:00
}
}