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

109 lines
4.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { FetchFn, GoogleAuth } from "./google.js";
export interface MailAttachment {
filename: string;
mime: string;
getBytes(): Promise<Buffer>;
}
export interface MailMessage {
id: string;
from: string;
subject: string;
receivedAt: Date;
attachments: MailAttachment[];
}
export interface MailSource {
/** Письма ящика invoices@ с PDF-вложениями, которых нет в acc_mail_processed. */
listUnprocessed(limit: number): Promise<MailMessage[]>;
}
export const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.readonly";
const API = "https://gmail.googleapis.com/gmail/v1/users/me";
interface GmailPart {
filename?: string;
mimeType?: string;
body?: { attachmentId?: string; data?: string; size?: number };
parts?: GmailPart[];
}
export interface GmailMessageJson {
id: string;
internalDate?: string;
payload?: GmailPart & { headers?: { name: string; value: string }[] };
}
/** Разбор ответа messages.get (format=full) в MailMessage; байты вложений берутся через fetchAttachment. */
export function parseGmailMessage(m: GmailMessageJson, fetchAttachment: (attachmentId: string) => Promise<Buffer>): MailMessage {
const header = (n: string) => m.payload?.headers?.find((h) => h.name.toLowerCase() === n)?.value ?? "";
const attachments: MailAttachment[] = [];
const walk = (p: GmailPart | undefined): void => {
if (!p) return;
const name = p.filename ?? "";
const isPdf = (p.mimeType ?? "").toLowerCase() === "application/pdf" || name.toLowerCase().endsWith(".pdf");
if (name && isPdf && p.body) {
const { attachmentId, data } = p.body;
if (data) attachments.push({ filename: name, mime: "application/pdf", getBytes: async () => Buffer.from(data, "base64url") });
else if (attachmentId) attachments.push({ filename: name, mime: "application/pdf", getBytes: () => fetchAttachment(attachmentId) });
}
for (const c of p.parts ?? []) walk(c);
};
walk(m.payload);
return {
id: m.id,
from: header("from"),
subject: header("subject"),
receivedAt: new Date(Number(m.internalDate ?? 0)),
attachments,
};
}
/** Gmail REST API: читаем ящик invoices@ от имени пользователя (делегирование домена). */
export class GmailClient implements MailSource {
constructor(
private o: {
auth: GoogleAuth;
/** Ящик (google.gmailUser). */
user: string;
/** Какие из id писем уже разобраны (acc_mail_processed, result invoice/skipped). */
processedIds: (ids: string[]) => Promise<Set<string>>;
fetchFn?: FetchFn;
query?: string;
},
) {}
private async get<T>(path: string, params: Record<string, string> = {}): Promise<T> {
const token = await this.o.auth.getAccessToken([GMAIL_SCOPE], this.o.user);
const url = `${API}${path}${Object.keys(params).length ? "?" + new URLSearchParams(params) : ""}`;
const res = await (this.o.fetchFn ?? fetch)(url, { headers: { authorization: `Bearer ${token}` } });
const text = await res.text();
if (!res.ok) throw new Error(`Gmail ${path} ${res.status}: ${text.slice(0, 300)}`);
return JSON.parse(text) as T;
}
async listUnprocessed(limit: number): Promise<MailMessage[]> {
const out: MailMessage[] = [];
let pageToken: string | undefined;
do {
const params: Record<string, string> = { q: this.o.query ?? "has:attachment filename:pdf", maxResults: "50" };
if (pageToken) params.pageToken = pageToken;
const list = await this.get<{ messages?: { id: string }[]; nextPageToken?: string }>("/messages", params);
const ids = (list.messages ?? []).map((x) => x.id);
const done = ids.length ? await this.o.processedIds(ids) : new Set<string>();
for (const id of ids) {
if (done.has(id)) continue;
const m = await this.get<GmailMessageJson>(`/messages/${id}`, { format: "full" });
const msg = parseGmailMessage(m, (aid) => this.fetchAttachment(id, aid));
if (msg.attachments.length) out.push(msg);
if (out.length >= limit) return out;
}
pageToken = list.nextPageToken;
} while (pageToken);
return out;
}
private async fetchAttachment(messageId: string, attachmentId: string): Promise<Buffer> {
const a = await this.get<{ data?: string }>(`/messages/${messageId}/attachments/${attachmentId}`);
return Buffer.from(a.data ?? "", "base64url");
}
}