Prettify.

This commit is contained in:
Tipx-L 2024-04-16 00:51:44 -07:00
parent dd923ea3e6
commit d664165c26
3 changed files with 95 additions and 68 deletions

View File

@ -65,6 +65,10 @@ export class GamePromises {
game.download(url, folder, resolve, reject, dev, onprogress); game.download(url, folder, resolve, reject, dev, onprogress);
}); });
} }
/**
* @param {string} filename
* @returns {Promise<Buffer>}
*/
readFile(filename) { readFile(filename) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// @ts-ignore // @ts-ignore

View File

@ -386,7 +386,9 @@ export async function request(url, onProgress, options = {}) {
try { try {
// @ts-ignore // @ts-ignore
filename = response.headers.get("Content-Disposition").split(";")[1].split("=")[1]; filename = response.headers.get("Content-Disposition").split(";")[1].split("=")[1];
} catch { /* empty */ } } catch {
/* empty */
}
let receivedBytes = 0; let receivedBytes = 0;
let chunks = []; let chunks = [];
@ -527,20 +529,20 @@ export function createProgress(title, max, fileName, value) {
* or rejects with an error if the operation fails. * or rejects with an error if the operation fails.
* @throws {Error} Will throw an error if the fetch operation fails or if no valid tags are found. * @throws {Error} Will throw an error if the fetch operation fails or if no valid tags are found.
*/ */
export async function getLatestVersionFromGitHub(owner = 'libccy', repo = 'noname') { export async function getLatestVersionFromGitHub(owner = "libccy", repo = "noname") {
if (!localStorage.getItem('noname_authorization')) await gainAuthorization(); if (!localStorage.getItem("noname_authorization")) await gainAuthorization();
const tags = await getRepoTags({ const tags = await getRepoTags({
username: owner, username: owner,
repository: repo repository: repo,
}); });
for (const tag of tags) { for (const tag of tags) {
const tagName = tag.name; const tagName = tag.name;
if (tagName !== 'v1998') return tagName; if (tagName !== "v1998") return tagName;
} }
throw new Error('No valid tags found in the repository'); throw new Error("No valid tags found in the repository");
} }
/** /**
@ -559,14 +561,18 @@ export async function getLatestVersionFromGitHub(owner = 'libccy', repo = 'nonam
* }[][]>} A promise that resolves with trees from the specified directories. * }[][]>} A promise that resolves with trees from the specified directories.
* @throws {Error} Will throw an error if unable to fetch the repository tree from GitHub. * @throws {Error} Will throw an error if unable to fetch the repository tree from GitHub.
*/ */
export async function getTreesFromGithub(directories, version, owner = 'libccy', repo = 'noname') { export async function getTreesFromGithub(directories, version, owner = "libccy", repo = "noname") {
if (!localStorage.getItem('noname_authorization')) await gainAuthorization(); if (!localStorage.getItem("noname_authorization")) await gainAuthorization();
const treesResponse = await fetch(`https://api.github.com/repos/${owner}/${repo}/git/trees/${version}?recursive=1`, { const treesResponse = await fetch(
headers: defaultHeaders `https://api.github.com/repos/${owner}/${repo}/git/trees/${version}?recursive=1`,
}); {
headers: defaultHeaders,
}
);
if (!treesResponse.ok) throw new Error(`Failed to fetch the GitHub repository tree: HTTP status ${treesResponse.status}`); if (!treesResponse.ok)
throw new Error(`Failed to fetch the GitHub repository tree: HTTP status ${treesResponse.status}`);
/** /**
* @type {{ * @type {{
* sha: string; * sha: string;
@ -584,5 +590,7 @@ export async function getTreesFromGithub(directories, version, owner = 'libccy',
*/ */
const trees = await treesResponse.json(); const trees = await treesResponse.json();
const tree = trees.tree; const tree = trees.tree;
return directories.map(directory => tree.filter(({ type, path }) => type === 'blob' && path.startsWith(directory))); return directories.map((directory) =>
tree.filter(({ type, path }) => type === "blob" && path.startsWith(directory))
);
} }

View File

@ -21,7 +21,7 @@ import {
createProgress, createProgress,
gainAuthorization, gainAuthorization,
getLatestVersionFromGitHub, getLatestVersionFromGitHub,
getTreesFromGithub getTreesFromGithub,
} from "../../../../library/update.js"; } from "../../../../library/update.js";
export const otherMenu = function (/** @type { boolean | undefined } */ connectMenu) { export const otherMenu = function (/** @type { boolean | undefined } */ connectMenu) {
@ -333,7 +333,7 @@ export const otherMenu = function (/** @type { boolean | undefined } */ connectM
.then(() => { .then(() => {
cp.exec( cp.exec(
`start /b ${__dirname}\\noname-server.exe -platform=electron`, `start /b ${__dirname}\\noname-server.exe -platform=electron`,
() => { } () => {}
); );
function loadURL() { function loadURL() {
let myAbortController = let myAbortController =
@ -412,9 +412,9 @@ export const otherMenu = function (/** @type { boolean | undefined } */ connectM
} }
const assetDirectories = []; const assetDirectories = [];
if (lib.config.asset_font) assetDirectories.push('font'); if (lib.config.asset_font) assetDirectories.push("font");
if (lib.config.asset_audio) assetDirectories.push('audio'); if (lib.config.asset_audio) assetDirectories.push("audio");
if (lib.config.asset_image) assetDirectories.push('image'); if (lib.config.asset_image) assetDirectories.push("image");
const version = await getLatestVersionFromGitHub(); const version = await getLatestVersionFromGitHub();
const files = await getTreesFromGithub(assetDirectories, version); const files = await getTreesFromGithub(assetDirectories, version);
@ -459,13 +459,16 @@ export const otherMenu = function (/** @type { boolean | undefined } */ connectM
* @type {progress} * @type {progress}
*/ */
let unZipProgress; let unZipProgress;
request('api.unitedrhythmized.club/noname', (receivedBytes, total, filename) => { request(
if (typeof filename == 'string') { "api.unitedrhythmized.club/noname",
(receivedBytes, total, filename) => {
if (typeof filename == "string") {
progress.setFileName(filename); progress.setFileName(filename);
} }
let received = 0, max = 0; let received = 0,
max = 0;
if (total) { if (total) {
max = +(total / (1024 * 1024)).toFixed(1) max = +(total / (1024 * 1024)).toFixed(1);
} else { } else {
max = 1000; max = 1000;
} }
@ -473,38 +476,51 @@ export const otherMenu = function (/** @type { boolean | undefined } */ connectM
if (received > max) max = received; if (received > max) max = received;
progress.setProgressMax(max); progress.setProgressMax(max);
progress.setProgressValue(received); progress.setProgressValue(received);
}, { },
method: 'POST', {
method: "POST",
body: JSON.stringify({ body: JSON.stringify({
action: 'downloadAssets', action: "downloadAssets",
version, version,
fileList: result.concat('game/asset.js') fileList: result.concat("game/asset.js"),
}) }),
}).then(async blob => { }
)
.then(async (blob) => {
progress.remove(); progress.remove();
const zip = await get.promises.zip(); const zip = await get.promises.zip();
zip.load(await blob.arrayBuffer()); zip.load(await blob.arrayBuffer());
const entries = Object.entries(zip.files); const entries = Object.entries(zip.files);
let root; let root;
const hiddenFileFlags = ['.', '_']; const hiddenFileFlags = [".", "_"];
unZipProgress = createProgress('正在解压' + progress.getFileName(), entries.length); unZipProgress = createProgress(
"正在解压" + progress.getFileName(),
entries.length
);
let i = 0; let i = 0;
for (const [key, value] of entries) { for (const [key, value] of entries) {
unZipProgress.setProgressValue(i++); unZipProgress.setProgressValue(i++);
const fileName = typeof root == 'string' && key.startsWith(root) ? key.replace(root, '') : key; const fileName =
typeof root == "string" && key.startsWith(root)
? key.replace(root, "")
: key;
if (hiddenFileFlags.includes(fileName[0])) continue; if (hiddenFileFlags.includes(fileName[0])) continue;
if (value.dir) { if (value.dir) {
await game.promises.createDir(fileName); await game.promises.createDir(fileName);
continue; continue;
} }
unZipProgress.setFileName(fileName); unZipProgress.setFileName(fileName);
const [path, name] = [fileName.split('/').slice(0, -1).join('/'), fileName.split('/').slice(-1).join('/')]; const [path, name] = [
fileName.split("/").slice(0, -1).join("/"),
fileName.split("/").slice(-1).join("/"),
];
game.print(`${fileName}(${i}/${entries.length})`); game.print(`${fileName}(${i}/${entries.length})`);
await game.promises.writeFile(value.asArrayBuffer(), path, name); await game.promises.writeFile(value.asArrayBuffer(), path, name);
} }
unZipProgress.remove(); unZipProgress.remove();
await finish(); await finish();
}).catch(e => { })
.catch((e) => {
if (progress.parentNode) progress.remove(); if (progress.parentNode) progress.remove();
if (unZipProgress && unZipProgress.parentNode) unZipProgress.remove(); if (unZipProgress && unZipProgress.parentNode) unZipProgress.remove();
refresh(); refresh();
@ -1646,4 +1662,3 @@ export const otherMenu = function (/** @type { boolean | undefined } */ connectM
if (!active.link) active._initLink(); if (!active.link) active._initLink();
rightPane.appendChild(active.link); rightPane.appendChild(active.link);
}; };