import type { FetchFn, GoogleAuth } from "./google.js"; export interface MailAttachment { filename: string; mime: string; getBytes(): Promise; } 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; } 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): 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>; fetchFn?: FetchFn; query?: string; }, ) {} private async get(path: string, params: Record = {}): Promise { 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 { const out: MailMessage[] = []; let pageToken: string | undefined; do { const params: Record = { 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(); for (const id of ids) { if (done.has(id)) continue; const m = await this.get(`/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 { const a = await this.get<{ data?: string }>(`/messages/${messageId}/attachments/${attachmentId}`); return Buffer.from(a.data ?? "", "base64url"); } }