105 lines
5.4 KiB
TypeScript
105 lines
5.4 KiB
TypeScript
import { createHash, createSign } from "node:crypto";
|
||
import { readFile } from "node:fs/promises";
|
||
|
||
const API = "https://www.googleapis.com/drive/v3";
|
||
const UPLOAD = "https://www.googleapis.com/upload/drive/v3";
|
||
export const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
|
||
|
||
export interface ServiceAccountKey { client_email: string; private_key: string; token_uri?: string }
|
||
export interface DriveFile { id: string; name: string; size?: string; md5Checksum?: string; createdTime?: string }
|
||
|
||
/** Минимальный интерфейс Drive для сервиса (подменяется в тестах). */
|
||
export interface DriveLike {
|
||
upload(name: string, filePath: string, folderId: string): Promise<DriveFile>;
|
||
list(folderId: string): Promise<DriveFile[]>;
|
||
trash(id: string): Promise<void>;
|
||
}
|
||
|
||
const b64 = (x: string) => Buffer.from(x).toString("base64url");
|
||
|
||
/** Токен доступа сервисного аккаунта (JWT -> токен, кэш до истечения). */
|
||
export function createTokenProvider(key: ServiceAccountKey, fetchFn: typeof fetch = fetch, now: () => number = () => Date.now()): () => Promise<string> {
|
||
let cached: { token: string; expiresAt: number } | null = null;
|
||
return async () => {
|
||
if (cached && cached.expiresAt - now() > 60_000) return cached.token;
|
||
const iat = Math.floor(now() / 1000);
|
||
const uri = key.token_uri ?? "https://oauth2.googleapis.com/token";
|
||
const head = b64(JSON.stringify({ alg: "RS256", typ: "JWT" }));
|
||
const claim = b64(JSON.stringify({ iss: key.client_email, scope: DRIVE_SCOPE, aud: uri, iat, exp: iat + 3000 }));
|
||
const sig = createSign("RSA-SHA256").update(`${head}.${claim}`).sign(key.private_key, "base64url");
|
||
const res = await fetchFn(uri, {
|
||
method: "POST",
|
||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||
body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: `${head}.${claim}.${sig}` }),
|
||
});
|
||
const j = (await res.json()) as { access_token?: string; expires_in?: number; error?: string };
|
||
if (!j.access_token) throw new Error(`токен Google не получен: ${j.error ?? res.status}`);
|
||
cached = { token: j.access_token, expiresAt: now() + (j.expires_in ?? 3600) * 1000 };
|
||
return j.access_token;
|
||
};
|
||
}
|
||
|
||
export class DriveError extends Error {
|
||
constructor(message: string, readonly status: number) {
|
||
super(message);
|
||
}
|
||
}
|
||
|
||
/** Клиент Drive API v3 под сервисным аккаунтом (общие диски: supportsAllDrives). */
|
||
export class DriveClient implements DriveLike {
|
||
constructor(private token: () => Promise<string>, private fetchFn: typeof fetch = fetch) {}
|
||
|
||
private async call(method: string, url: string, init: { headers?: Record<string, string>; body?: BodyInit } = {}): Promise<Response> {
|
||
const res = await this.fetchFn(url, { method, headers: { authorization: `Bearer ${await this.token()}`, ...(init.headers ?? {}) }, body: init.body });
|
||
if (!res.ok) {
|
||
let msg = String(res.status);
|
||
try {
|
||
const j = (await res.json()) as { error?: { message?: string } };
|
||
msg = `${res.status} ${j.error?.message ?? ""}`.trim();
|
||
} catch {
|
||
/* тело не JSON */
|
||
}
|
||
throw new DriveError(`Drive ${method}: ${msg}`, res.status);
|
||
}
|
||
return res;
|
||
}
|
||
|
||
/** Загрузка файла (resumable одним запросом; архивы - единицы или десятки мегабайт). */
|
||
async upload(name: string, filePath: string, folderId: string): Promise<DriveFile> {
|
||
const data = await readFile(filePath);
|
||
const start = await this.call("POST", `${UPLOAD}/files?uploadType=resumable&supportsAllDrives=true&fields=id,name,size,md5Checksum,createdTime`, {
|
||
headers: { "content-type": "application/json; charset=UTF-8", "x-upload-content-type": "application/octet-stream", "x-upload-content-length": String(data.length) },
|
||
body: JSON.stringify({ name, parents: [folderId] }),
|
||
});
|
||
const location = start.headers.get("location");
|
||
if (!location) throw new DriveError("Drive: нет адреса сессии загрузки", 502);
|
||
const done = await this.call("PUT", location, { headers: { "content-type": "application/octet-stream", "content-length": String(data.length) }, body: new Uint8Array(data) });
|
||
return (await done.json()) as DriveFile;
|
||
}
|
||
|
||
async list(folderId: string): Promise<DriveFile[]> {
|
||
const out: DriveFile[] = [];
|
||
let page = "";
|
||
do {
|
||
const q = encodeURIComponent(`'${folderId}' in parents and trashed = false`);
|
||
const res = await this.call(
|
||
"GET",
|
||
`${API}/files?q=${q}&pageSize=1000&supportsAllDrives=true&includeItemsFromAllDrives=true&fields=nextPageToken,files(id,name,size,md5Checksum,createdTime)${page ? `&pageToken=${encodeURIComponent(page)}` : ""}`,
|
||
);
|
||
const j = (await res.json()) as { files?: DriveFile[]; nextPageToken?: string };
|
||
out.push(...(j.files ?? []));
|
||
page = j.nextPageToken ?? "";
|
||
} while (page);
|
||
return out;
|
||
}
|
||
|
||
/** В корзину (не удаление навсегда). */
|
||
async trash(id: string): Promise<void> {
|
||
await this.call("PATCH", `${API}/files/${id}?supportsAllDrives=true`, { headers: { "content-type": "application/json" }, body: JSON.stringify({ trashed: true }) });
|
||
}
|
||
}
|
||
|
||
export async function md5File(path: string): Promise<string> {
|
||
return createHash("md5").update(await readFile(path)).digest("hex");
|
||
}
|