Files
siftlode/frontend/src/lib/downloads.test.ts
T
peter 8383459f70 fix: share, upload, crop, auto-skip, tag chips and See all hold what they claim
- Share: a link that expired is never copied (the dialog and one-click Share pick a live one,
  else make one), says it expired, and the copy-on-open claim clears on the next copy.
- A password-protected file link asks to open a file, not to watch a video.
- Upload: Cancel, the close button or the backdrop while naming a folder makes no folder; a failed
  refetch keeps the target; a folder being made says so.
- Crop: an infinite number is dropped, not a 500; an unprobed clip's size follows a shown-size crop;
  the edit_spec docs name frame_w/frame_h; the join and rotated paths are tested.
- Auto-skip: the wait gives way on a marker too short for it, so the skip still fires.
- Tag chips count the followed channels (subscribed_count) and a toggled chip keeps the focus.
- Continue watching's See all sorts by last watched when in progress was already on.
2026-11-06 00:09:39 +01:00

174 lines
6.9 KiB
TypeScript

// @vitest-environment jsdom
//
// One-click share: quickShareLink turns the row's Share button into a single action —
// ensure a public link (mint on demand, downloadable), copy it, and toast with an "open in new
// tab" action. These pin the branch matrix: reuse-vs-mint, copy-ok-vs-fail, and the create-failure path.
import { describe, it, expect, beforeEach, vi } from "vitest";
import { QueryClient } from "@tanstack/react-query";
// vi.mock is hoisted above these consts, so the mock fns must live in a hoisted block too.
const { downloadLinks, createDownloadLink, folderLinks, createFolderLink, copyText, notify } =
vi.hoisted(() => ({
downloadLinks: vi.fn(),
createDownloadLink: vi.fn(),
folderLinks: vi.fn(),
createFolderLink: vi.fn(),
copyText: vi.fn(),
notify: vi.fn(),
}));
vi.mock("./api", () => ({
api: { downloadLinks, createDownloadLink, folderLinks, createFolderLink },
}));
vi.mock("./clipboard", () => ({ copyText }));
vi.mock("./notifications", async (importOriginal) => ({
...(await importOriginal<typeof import("./notifications")>()),
notify,
}));
import { quickShareLink } from "./downloads";
import { qk } from "./queryKeys";
import { msg, type NotifText } from "./notifications";
const origin = window.location.origin;
type ToastArg = {
level: string;
message: NotifText;
action?: { label: NotifText; onClick: () => void };
};
const firstToast = () => notify.mock.calls[0]![0] as ToastArg;
function qc() {
return new QueryClient({ defaultOptions: { queries: { retry: false } } });
}
beforeEach(() => {
downloadLinks.mockReset();
createDownloadLink.mockReset();
folderLinks.mockReset();
createFolderLink.mockReset();
copyText.mockReset().mockResolvedValue(true);
notify.mockReset();
});
describe("quickShareLink", () => {
it("mints a downloadable link on demand, copies it, and toasts with an open-in-new-tab action", async () => {
downloadLinks.mockResolvedValue([]); // none yet
createDownloadLink.mockResolvedValue({ id: 7, url: "/watch/tok7" });
const openSpy = vi.spyOn(window, "open").mockReturnValue(null);
const url = await quickShareLink(qc(), { kind: "file", id: 42 });
expect(url).toBe(`${origin}/watch/tok7`);
// Minted with an EMPTY body so the backend default (allow_download=true) applies.
expect(createDownloadLink).toHaveBeenCalledWith(42, {});
expect(copyText).toHaveBeenCalledWith(`${origin}/watch/tok7`);
const arg = firstToast();
expect(arg.level).toBe("success");
expect(arg.message).toEqual(msg("downloads.share.linkCopied"));
expect(arg.action!.label).toEqual(msg("downloads.share.openNewTab"));
arg.action!.onClick();
expect(openSpy).toHaveBeenCalledWith(`${origin}/watch/tok7`, "_blank", "noopener,noreferrer");
});
it("reuses an existing link instead of minting a duplicate", async () => {
downloadLinks.mockResolvedValue([{ id: 3, url: "/watch/old" }]);
const url = await quickShareLink(qc(), { kind: "file", id: 1 });
expect(url).toBe(`${origin}/watch/old`);
expect(createDownloadLink).not.toHaveBeenCalled();
expect(firstToast().level).toBe("success");
});
it("passes over a link whose address the server can no longer show", async () => {
downloadLinks.mockResolvedValue([
{ id: 4, url: null },
{ id: 3, url: "/watch/older" },
]);
const url = await quickShareLink(qc(), { kind: "file", id: 1 });
expect(url).toBe(`${origin}/watch/older`);
expect(createDownloadLink).not.toHaveBeenCalled();
});
// An expired link stays listed for its owner, but its recipient would land on "link gone".
it("passes over an expired link, and mints one when every link has expired", async () => {
const lastWeek = new Date(Date.now() - 7 * 86400_000).toISOString();
const nextWeek = new Date(Date.now() + 7 * 86400_000).toISOString();
downloadLinks.mockResolvedValue([
{ id: 5, url: "/watch/gone", expires_at: lastWeek },
{ id: 3, url: "/watch/live", expires_at: nextWeek },
]);
expect(await quickShareLink(qc(), { kind: "file", id: 1 })).toBe(`${origin}/watch/live`);
expect(createDownloadLink).not.toHaveBeenCalled();
downloadLinks.mockResolvedValue([{ id: 5, url: "/watch/gone", expires_at: lastWeek }]);
createDownloadLink.mockResolvedValue({ id: 9, url: "/watch/fresh" });
expect(await quickShareLink(qc(), { kind: "file", id: 2 })).toBe(`${origin}/watch/fresh`);
});
it("mints a new link when none it has can be shown, keeping the old ones listed", async () => {
const hidden = { id: 4, url: null };
downloadLinks.mockResolvedValue([hidden]);
createDownloadLink.mockResolvedValue({ id: 8, url: "/watch/new" });
const client = qc();
const url = await quickShareLink(client, { kind: "file", id: 6 });
expect(url).toBe(`${origin}/watch/new`);
expect(copyText).toHaveBeenCalledWith(`${origin}/watch/new`);
expect(client.getQueryData(qk.downloadLinks(6))).toEqual([
{ id: 8, url: "/watch/new" },
hidden,
]);
});
it("a folder's link is the folder's own: listed, made and cached under the folder", async () => {
folderLinks.mockResolvedValue([]);
createFolderLink.mockResolvedValue({ id: 9, url: "/watch/fold" });
const client = qc();
client.setQueryData(qk.fileFolders(), []);
const url = await quickShareLink(client, { kind: "folder", id: 5 });
expect(url).toBe(`${origin}/watch/fold`);
expect(folderLinks).toHaveBeenCalledWith(5);
expect(createFolderLink).toHaveBeenCalledWith(5, {});
expect(downloadLinks).not.toHaveBeenCalled();
expect(createDownloadLink).not.toHaveBeenCalled();
expect(client.getQueryData(qk.folderLinks(5))).toEqual([{ id: 9, url: "/watch/fold" }]);
// The rail's mark of a shared folder is asked for again.
expect(client.getQueryState(qk.fileFolders())!.isInvalidated).toBe(true);
});
it("still toasts (warning) with the open action when the clipboard copy fails", async () => {
downloadLinks.mockResolvedValue([{ id: 5, url: "/watch/x" }]);
copyText.mockResolvedValue(false);
const url = await quickShareLink(qc(), { kind: "file", id: 2 });
expect(url).toBe(`${origin}/watch/x`); // the link is never a dead end
const arg = firstToast();
expect(arg.level).toBe("warning");
expect(arg.message).toEqual(msg("downloads.share.copyFailed"));
expect(arg.action!.label).toEqual(msg("downloads.share.openNewTab"));
});
it("reports an error and returns null when link creation fails", async () => {
downloadLinks.mockResolvedValue([]);
createDownloadLink.mockRejectedValue(new Error("boom"));
const url = await quickShareLink(qc(), { kind: "file", id: 9 });
expect(url).toBeNull();
expect(copyText).not.toHaveBeenCalled();
// Titled with what failed, and carrying why (notifyActionError), not a bare message.
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ level: "error", title: msg("downloads.share.linkFailed") }),
);
});
});