file.uts 2.53 KB
import services from "@/services";
import { checkFileExists, readDirectory } from "@/utils/plus-io.uts";

import { WsCommand } from "../../constants.uts";
import { asObject, asString, getUploadStrategy, isEmptyObject, sendError, sendOk, WsCommandRouter } from "../CommandCore.uts";

async function resolveEntryType(path: string): Promise<UTSJSONObject> {
	const result = {
		fullPath: path,
		isDirectory: false,
		isFile: false,
		name: ""
	} as UTSJSONObject;
	const lastSlash = path.lastIndexOf("/");
	result.name = lastSlash != -1 ? path.slice(lastSlash + 1) : path;
	let isDirectory = false;
	try {
		await readDirectory(path);
		isDirectory = true;
	} catch {}
	if (isDirectory) {
		result.isDirectory = true;
		return result;
	}
	const fileExists = await checkFileExists(path);
	if (fileExists) {
		result.isFile = true;
	}
	return result;
}

export function registerFileHandlers(router: WsCommandRouter, defaultRootPath: string): void {
	router.register(WsCommand.FileExplorer as string, async (ctx, payload): Promise<void> => {
		const targetPath = asString(payload.path, defaultRootPath);
		const exists = await checkFileExists(targetPath);
		if (!exists) {
			await sendError(ctx, `路径不存在: ${targetPath}`, payload);
			return;
		}
		const names = await readDirectory(targetPath).catch((): string[] => []);
		const files: UTSJSONObject[] = [];
		for (const name of names) {
			const fullPath = targetPath.endsWith("/") ? `${targetPath}${name}` : `${targetPath}/${name}`;
			const info = await resolveEntryType(fullPath);
			files.push(info);
		}
		await sendOk(ctx, "获取目录成功", {
			currentPath: targetPath,
			files
		} as UTSJSONObject, payload);
	});

	router.register(WsCommand.UploadFile as string, async (ctx, payload): Promise<void> => {
		const filePath = asString(payload.filePath);
		if (filePath == "") {
			await sendError(ctx, "文件路径不能为空", payload);
			return;
		}
		const options = {
			filePath
		} as UTSJSONObject;
		const uploadUrl = asString(payload.uploadUrl);
		if (uploadUrl != "") {
			options.uploadUrl = uploadUrl;
		}
		const formData = asObject(payload.formData);
		if (!isEmptyObject(formData)) {
			options.formData = formData;
		}
		const header = asObject(payload.header);
		if (!isEmptyObject(header)) {
			options.header = header;
		}
		const strategy = getUploadStrategy(asString(payload.strategy));
		const result = strategy == null
			? await services.fileUpload.upload(options)
			: await services.fileUpload.upload(options, strategy);
		await sendOk(ctx, "上传成功", result as UTSJSONObject, payload);
	});
}