Папка приёма Google Drive <id чата>: опрос раз в 10 секунд, файлы = сообщения менеджера; swap 32 ГБ; docs
All checks were successful
ci / test (push) Successful in 15s
ci / deploy (push) Successful in 1m9s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-12 09:38:48 +03:00
parent d14bc02661
commit 5718f0c10b
38 changed files with 247 additions and 113 deletions

View File

@@ -0,0 +1,91 @@
import { mkdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { createHash } from "node:crypto";
import { defaultExec, type ExecFn } from "./drive.js";
export interface InboxFile {
channel: string;
name: string;
id: string;
/** Локальный путь скачанного файла. */
localPath: string;
/** Для текстовых файлов (.txt/.md) - содержимое, воспринимается как текст сообщения. */
text?: string;
/** Псевдо-ts сообщения (секунды.дробь), уникален по id файла. */
ts: string;
}
export interface DriveInboxOpts {
rcloneBin: string;
remote: string;
folder: string;
/** Локальная папка для скачанных файлов: <localRoot>/<channel>/ . */
localRoot: string;
channels: () => Promise<string[]>;
/** Принять файл как сообщение чата; true - принят (не дубль). */
accept: (f: InboxFile) => Promise<boolean>;
exec?: ExecFn;
onError?: (e: unknown) => void;
}
const TEXT_EXT = /\.(txt|md)$/i;
/** Опрос папки `<folder>/<channel_id>` на Google Drive: новые файлы воспринимаются как сообщения менеджера в этом чате. */
export class DriveInbox {
private timer?: NodeJS.Timeout;
private busy = false;
private exec: ExecFn;
constructor(private o: DriveInboxOpts) {
this.exec = o.exec ?? defaultExec;
}
start(intervalMs: number): void {
this.timer = setInterval(() => void this.scan().catch((e) => this.o.onError?.(e)), intervalMs);
}
stop(): void {
clearInterval(this.timer);
}
/** Один проход по всем каналам; возвращает число принятых файлов. */
async scan(): Promise<number> {
if (this.busy) return 0;
this.busy = true;
try {
let accepted = 0;
for (const channel of await this.o.channels()) accepted += await this.scanChannel(channel).catch((e) => (this.o.onError?.(e), 0));
return accepted;
} finally {
this.busy = false;
}
}
private async scanChannel(channel: string): Promise<number> {
const { rcloneBin: bin, remote, folder } = this.o;
const dir = `${remote}:${folder}/${channel}`;
let listing: { Name: string; ID?: string; IsDir?: boolean; ModTime?: string }[];
try {
listing = JSON.parse(await this.exec(bin, ["lsjson", dir]));
} catch (e) {
if (/directory not found|not found/i.test(String(e))) return 0; // папка канала ещё не создана
throw e;
}
const files = listing.filter((f) => !f.IsDir && f.ID && !f.Name.startsWith("_") && !f.Name.startsWith("."));
if (!files.length) return 0;
const local = join(this.o.localRoot, channel);
mkdirSync(local, { recursive: true });
let accepted = 0;
for (const f of files.sort((a, b) => (a.ModTime ?? "").localeCompare(b.ModTime ?? ""))) {
const localPath = join(local, `${f.ID!.slice(0, 8)}_${f.Name.replace(/[^\w.\- ]/g, "_")}`);
await this.exec(bin, ["copyto", `${dir}/${f.Name}`, localPath]);
const frac = createHash("sha1").update(f.ID!).digest().readUInt32BE(0) % 1_000_000;
const ts = `${Math.floor(Date.parse(f.ModTime ?? "") / 1000) || Math.floor(Date.now() / 1000)}.${String(frac).padStart(6, "0")}`;
const text = TEXT_EXT.test(f.Name) ? readFileSync(localPath, "utf8").trim() : undefined;
if (await this.o.accept({ channel, name: f.Name, id: f.ID!, localPath, text, ts })) accepted++;
// обработанное убираем из папки приёма, чтобы не читать повторно
await this.exec(bin, ["moveto", `${dir}/${f.Name}`, `${dir}/_processed/${f.ID!.slice(0, 8)}_${f.Name}`]);
}
return accepted;
}
}

View File

@@ -54,12 +54,35 @@ export class SlackIntake {
if (!manager) return;
if (!this.opts.channelIds.includes(channel) && manager.slackChannelId !== channel) return;
const files = ((ev.files as { id?: string }[] | undefined) ?? []).map((f) => String(f.id)).filter(Boolean);
await this.accept(manager, { channel, ts, text: String(ev.text ?? ""), fileIds: files });
}
/** Менеджер чата (по slack_channel_id или единственный активный менеджер для каналов из настроек). */
async findManagerByChannel(channel: string): Promise<ManagerInfo | null> {
const { rows } = await this.pool.query(
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id
from construction_manager cm join person p on p.id = cm.person_id
where cm.slack_channel_id = $1 and cm.is_active and p.is_active order by cm.person_id limit 1`,
[channel],
);
const r = rows[0];
return r ? { personId: r.person_id, name: r.display_name, slackUserId: r.slack_user_id, slackChannelId: r.slack_channel_id } : null;
}
/** Файл из папки приёма на Drive = сообщение менеджера в чате (текстовые файлы - текст сообщения). */
async onDriveFile(f: { channel: string; name: string; id: string; localPath: string; text?: string; ts: string }): Promise<boolean> {
const manager = await this.findManagerByChannel(f.channel);
if (!manager) return false;
return this.accept(manager, { channel: f.channel, ts: f.ts, text: f.text ?? "", fileIds: [], localFiles: f.text === undefined ? [f.localPath] : [] });
}
/** Журнал (защита от дублей) + накопление в debounce-пакет менеджера. */
private async accept(manager: ManagerInfo, msg: IncomingMessage): Promise<boolean> {
const ins = await this.pool.query(
"insert into slack_message_log (channel_id, message_ts, manager_person_id, has_files, status) values ($1,$2,$3,$4,'received') on conflict do nothing returning message_ts",
[channel, ts, manager.personId, files.length > 0],
[msg.channel, msg.ts, manager.personId, msg.fileIds.length > 0 || (msg.localFiles?.length ?? 0) > 0],
);
if (!ins.rowCount) return; // дубль события
const msg: IncomingMessage = { channel, ts, text: String(ev.text ?? ""), fileIds: files };
if (!ins.rowCount) return false; // дубль
const cur = this.pending.get(manager.personId);
if (cur) clearTimeout(cur.timer);
clearTimeout(this.followups.get(manager.personId)); // новое сообщение отменяет ожидающий запрос "что-то ещё?"
@@ -67,6 +90,7 @@ export class SlackIntake {
const messages = [...(cur?.messages ?? []), msg];
const timer = setTimeout(() => this.track(this.flush(manager.personId)), this.opts.debounceMs);
this.pending.set(manager.personId, { manager, messages, timer });
return true;
}
private track(p: Promise<void>): void {