Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion desktop/ui/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -525,10 +525,24 @@ async function prepareContract(id, resync = false) {
// Lấy cây thư mục hợp đồng — cache theo updated_at: hợp đồng không đổi thì dùng
// lại plan cũ (tối đa 6 giờ), đổi (đổi tên/ngày/loại dịch vụ…) thì gọi lại server.
// force=true (bấm tay) → luôn hỏi lại server.
// Hợp đồng vừa lỗi prepare (Drive lỗi, server 5xx) → nghỉ một lúc rồi mới hỏi
// lại. Trước đây vòng nhanh 10s gọi lại prepare liên tục cho hợp đồng lỗi (hàng
// trăm lần/ngày), vừa tốn server vừa ngập nhật ký lỗi. Bấm tay (force) bỏ qua.
const PLAN_FAIL_BACKOFF_MS = 10 * 60 * 1000;
const planFail = new Map(); // contractId → { at, msg }
async function getPlan(id, updatedAt, force = false) {
const c = planCache.get(id);
if (!force && c && Date.now() - c.at < PLAN_TTL_MS && (!updatedAt || c.updatedAt === updatedAt)) return c;
const plan = await prepareContract(id, false);
const f = planFail.get(id);
if (!force && f && Date.now() - f.at < PLAN_FAIL_BACKOFF_MS) throw new Error(f.msg);
let plan;
try {
plan = await prepareContract(id, false);
} catch (e) {
planFail.set(id, { at: Date.now(), msg: e instanceof Error ? e.message : String(e) });
throw e;
}
planFail.delete(id);
if (plan.skip) return { skip: plan.skip };
// pathSegments = [Gốc, Loại dịch vụ, Thang N, Tên hợp đồng]; bản server cũ chỉ
// có folderName (+ rootFolderName) → dựng tạm để vẫn chạy.
Expand Down
10 changes: 9 additions & 1 deletion src/app/api/desktop/drive/prepare/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,15 @@ export async function POST(req: Request) {
return NextResponse.json({ error: "not_signed" }, { status: 409 });
}

const tree = await ensureContractDriveTree(auth.ownerId, contract as ContractForDrive);
// Lỗi Drive (thư mục mất, token hết hạn…) trả JSON rõ ràng cho desktop thay vì
// ném 500 trần.
let tree: Awaited<ReturnType<typeof ensureContractDriveTree>>;
try {
tree = await ensureContractDriveTree(auth.ownerId, contract as ContractForDrive);
} catch (e) {
const msg = e instanceof Error ? e.message : "drive_failed";
return NextResponse.json({ error: `drive_failed: ${msg}` }, { status: 502 });
}
if ("error" in tree) return NextResponse.json({ error: tree.error }, { status: 409 });

const albums = await wireContractAlbums(auth.ownerId, contract as ContractForDrive, tree.tree);
Expand Down
24 changes: 24 additions & 0 deletions src/lib/studio-drive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,21 @@ async function findOrCreateFolder(drive: any, name: string, parentId: string): P
return mkFolder(drive, name, parentId);
}

/**
* Thư mục còn dùng được không. CHỈ trả `false` khi Drive nói rõ là mất (404) hoặc
* đã vào thùng rác; lỗi khác (mạng, quota, 5xx) coi như còn — tránh tạo gốc mới
* chỉ vì Drive chập chờn.
*/
async function folderAlive(drive: any, fileId: string): Promise<boolean> {
try {
const res = await drive.files.get({ fileId, fields: "id, trashed" });
return res?.data?.trashed !== true;
} catch (e: any) {
const code = e?.code ?? e?.status ?? e?.response?.status;
return !(code === 404 || code === "404");
}
}

/** Thư mục GỐC mặc định của studio (studio_drive). create=true → tạo nếu chưa có. */
async function ensureRootFolder(
db: any,
Expand All @@ -391,6 +406,15 @@ async function ensureRootFolder(
): Promise<{ rootId: string | null; rootName: string }> {
const rootName = cleanFolderName(row.root_folder_name || "") || ROOT_FOLDER_NAME;
let rid = row.root_folder_id;
// Thư mục gốc đã lưu có thể không còn: studio xoá/chuyển vào thùng rác, hoặc
// kết nối lại bằng tài khoản Google KHÁC (upsert giữ root cũ, scope drive.file
// không thấy thư mục của tài khoản trước). Khi đó mọi lần tạo thư mục con nổ
// "File not found: <rootId>" và /api/desktop/drive/prepare lỗi mãi. Soi trước,
// mất thật (404 / thùng rác) thì quên id cũ để tạo lại bên dưới.
if (rid && create && !(await folderAlive(drive, rid))) {
rid = null;
await db.from("studio_drive").update({ root_folder_id: null, updated_at: new Date().toISOString() }).eq("owner_id", ownerId);
}
if (!rid && create) {
rid = await mkFolder(drive, rootName, null);
await db.from("studio_drive").update({ root_folder_id: rid, updated_at: new Date().toISOString() }).eq("owner_id", ownerId);
Expand Down
Loading