Files
khb_microservices/packages/accounting_automation/src/drive.ts

133 lines
6.4 KiB
TypeScript

import type { FetchFn, GoogleAuth } from "./google.js";
export interface DriveStore {
/** Путь папок внутри корневой папки; создаёт недостающие, возвращает id последней. */
ensureFolder(pathParts: string[]): Promise<string>;
upload(name: string, mime: string, bytes: Buffer, folderId: string): Promise<{ id: string }>;
/** Текст Google-документа (export text/plain). */
exportDocText(docId: string): Promise<string>;
}
export const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
const API = "https://www.googleapis.com/drive/v3";
const UPLOAD = "https://www.googleapis.com/upload/drive/v3/files";
/** Drive REST API v3, общие диски включены (supportsAllDrives). */
export class DriveClient implements DriveStore {
private folderCache = new Map<string, string>();
constructor(private o: { auth: GoogleAuth; rootFolderId: string; fetchFn?: FetchFn }) {}
private async call(url: string, init: RequestInit = {}): Promise<Response> {
const token = await this.o.auth.getAccessToken([DRIVE_SCOPE]);
const res = await (this.o.fetchFn ?? fetch)(url, { ...init, headers: { ...(init.headers ?? {}), authorization: `Bearer ${token}` } });
if (!res.ok) throw new Error(`Drive ${res.status}: ${(await res.text()).slice(0, 300)}`);
return res;
}
async ensureFolder(pathParts: string[]): Promise<string> {
let parent = this.o.rootFolderId;
for (const raw of pathParts) {
const name = raw.trim() || "_";
const ck = `${parent}/${name}`;
const cached = this.folderCache.get(ck);
if (cached) {
parent = cached;
continue;
}
const esc = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
const q = `name='${esc}' and mimeType='application/vnd.google-apps.folder' and '${parent}' in parents and trashed=false`;
const params = new URLSearchParams({ q, fields: "files(id,name)", supportsAllDrives: "true", includeItemsFromAllDrives: "true", pageSize: "2" });
const found = (await (await this.call(`${API}/files?${params}`)).json()) as { files?: { id: string }[] };
let id = found.files?.[0]?.id;
if (!id) {
const created = (await (
await this.call(`${API}/files?supportsAllDrives=true&fields=id`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ name, mimeType: "application/vnd.google-apps.folder", parents: [parent] }),
})
).json()) as { id: string };
id = created.id;
}
this.folderCache.set(ck, id);
parent = id;
}
return parent;
}
async upload(name: string, mime: string, bytes: Buffer, folderId: string): Promise<{ id: string }> {
const boundary = "khb" + Math.random().toString(36).slice(2);
const meta = JSON.stringify({ name, parents: [folderId] });
const body = Buffer.concat([
Buffer.from(`--${boundary}\r\ncontent-type: application/json; charset=UTF-8\r\n\r\n${meta}\r\n--${boundary}\r\ncontent-type: ${mime}\r\n\r\n`),
bytes,
Buffer.from(`\r\n--${boundary}--`),
]);
const res = await this.call(`${UPLOAD}?uploadType=multipart&supportsAllDrives=true&fields=id`, {
method: "POST",
headers: { "content-type": `multipart/related; boundary=${boundary}` },
body,
});
const j = (await res.json()) as { id: string };
return { id: j.id };
}
/** Файлы PDF в папке (по пути от корня) и во вложенных папках (глубина 1); отсутствующая папка - пустой список. */
async listPdfFiles(pathParts: string[]): Promise<{ id: string; name: string }[]> {
const root = await this.ensureFolder(pathParts);
const out: { id: string; name: string }[] = [];
const listIn = async (folder: string, depth: number): Promise<void> => {
let pageToken: string | undefined;
do {
const params = new URLSearchParams({
q: `'${folder}' in parents and trashed=false`,
fields: "nextPageToken,files(id,name,mimeType)",
supportsAllDrives: "true",
includeItemsFromAllDrives: "true",
pageSize: "200",
...(pageToken ? { pageToken } : {}),
});
const j = (await (await this.call(`${API}/files?${params}`)).json()) as { files?: { id: string; name: string; mimeType: string }[]; nextPageToken?: string };
for (const f of j.files ?? []) {
if (f.mimeType === "application/vnd.google-apps.folder") {
if (depth > 0) await listIn(f.id, depth - 1);
} else if (f.mimeType === "application/pdf" || f.name.toLowerCase().endsWith(".pdf")) out.push({ id: f.id, name: f.name });
}
pageToken = j.nextPageToken;
} while (pageToken);
};
await listIn(root, 1);
return out;
}
/** Имя и тип файла. */
async meta(fileId: string): Promise<{ name: string; mimeType: string }> {
const res = await this.call(`${API}/files/${encodeURIComponent(fileId)}?fields=name,mimeType&supportsAllDrives=true`);
return (await res.json()) as { name: string; mimeType: string };
}
/** Переносит файл в другую папку (и при необходимости переименовывает). */
async move(fileId: string, folderId: string, newName?: string): Promise<void> {
const id = encodeURIComponent(fileId);
const cur = (await (await this.call(`${API}/files/${id}?fields=parents&supportsAllDrives=true`)).json()) as { parents?: string[] };
const params = new URLSearchParams({ addParents: folderId, supportsAllDrives: "true", fields: "id" });
const remove = (cur.parents ?? []).filter((p) => p !== folderId);
if (remove.length) params.set("removeParents", remove.join(","));
await this.call(`${API}/files/${id}?${params}`, {
method: "PATCH",
headers: { "content-type": "application/json" },
body: JSON.stringify(newName ? { name: newName } : {}),
});
}
async download(fileId: string): Promise<Buffer> {
const res = await this.call(`${API}/files/${encodeURIComponent(fileId)}?alt=media&supportsAllDrives=true`);
return Buffer.from(await res.arrayBuffer());
}
async exportDocText(docId: string): Promise<string> {
const res = await this.call(`${API}/files/${encodeURIComponent(docId)}/export?mimeType=${encodeURIComponent("text/plain")}`);
return await res.text();
}
}