Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: handle web status and sign-in failures and batch analytics

Richie McIlroyb553b4bb0a52
diff --git a/apps/web/__tests__/unit/oauth-sign-in-errors.test.ts b/apps/web/__tests__/unit/oauth-sign-in-errors.test.ts
new file mode 100644
index 000000000..6b79281c8
--- /dev/null
+++ b/apps/web/__tests__/unit/oauth-sign-in-errors.test.ts
@@ -0,0 +1,146 @@
+// @vitest-environment jsdom
+
+import {
+ act,
+ type ButtonHTMLAttributes,
+ createElement,
+ type ElementType,
+ type ReactNode,
+} from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ signIn: vi.fn(),
+ error: vi.fn(),
+ captureException: vi.fn(),
+ searchParams: new URLSearchParams(),
+}));
+vi.mock("next-auth/react", () => ({ signIn: mocks.signIn }));
+vi.mock("@sentry/nextjs", () => ({ captureException: mocks.captureException }));
+vi.mock("sonner", () => ({ toast: { error: mocks.error } }));
+vi.mock("next/navigation", () => ({
+ useSearchParams: () => mocks.searchParams,
+ useRouter: () => ({ push: vi.fn() }),
+}));
+vi.mock("@cap/ui", () => ({
+ Button: ({
+ spinner: _spinner,
+ variant: _variant,
+ ...props
+ }: ButtonHTMLAttributes<HTMLButtonElement> & {
+ spinner?: boolean;
+ variant?: string;
+ }) => createElement("button", { type: "button", ...props }),
+ Input: "input",
+ LogoBadge: "div",
+}));
+vi.mock("framer-motion", () => ({
+ AnimatePresence: ({ children }: { children: ReactNode }) => children,
+ motion: Object.assign((component: ElementType) => component, {
+ button: "button",
+ div: "div",
+ form: "form",
+ h1: "h1",
+ p: "p",
+ span: "span",
+ }),
+}));
+vi.mock("next/image", () => ({ default: "img" }));
+vi.mock("next/link", () => ({ default: "a" }));
+vi.mock("@fortawesome/react-fontawesome", () => ({
+ FontAwesomeIcon: () => null,
+}));
+vi.mock("@/actions/organization/get-organization-sso-data", () => ({
+ getOrganizationSSOData: vi.fn(),
+}));
+vi.mock("@/app/utils/analytics", () => ({ trackEvent: vi.fn() }));
+vi.mock("@/utils/public-env", () => ({
+ usePublicEnv: () => ({
+ googleAuthAvailable: true,
+ workosAuthAvailable: false,
+ }),
+}));
+vi.mock("@/app/(org)/auth-email", () => ({
+ getEmailCodeCooldownSeconds: () => 0,
+ requestEmailCode: vi.fn(),
+}));
+
+const { LoginForm } = await import("@/app/(org)/login/form");
+const { SignupForm } = await import("@/app/(org)/signup/form");
+let container: HTMLDivElement;
+let root: Root;
+const actEnvironment = globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT?: boolean;
+};
+
+beforeEach(() => {
+ actEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
+ vi.stubGlobal("localStorage", {
+ getItem: () => null,
+ setItem: vi.fn(),
+ removeItem: vi.fn(),
+ });
+ mocks.searchParams = new URLSearchParams();
+ mocks.signIn.mockReset().mockResolvedValue(undefined);
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+ delete actEnvironment.IS_REACT_ACT_ENVIRONMENT;
+});
+
+async function clickGoogle() {
+ const button = [...container.querySelectorAll("button")].find((element) =>
+ element.textContent?.includes("Google"),
+ );
+ expect(button).toBeDefined();
+ await act(async () => button?.click());
+}
+
+describe.each([
+ ["login", LoginForm],
+ ["signup", SignupForm],
+] as const)("%s OAuth failures", (surface, Form) => {
+ it("shows a retry message after a failed request and allows another attempt", async () => {
+ mocks.signIn.mockRejectedValueOnce(new TypeError("Load failed"));
+ await act(async () => root.render(createElement(Form)));
+ await clickGoogle();
+ expect(mocks.error).toHaveBeenCalledWith(
+ "Could not start sign-in. Check your connection and try again.",
+ );
+ expect(mocks.captureException).toHaveBeenCalledWith(expect.any(TypeError), {
+ tags: { auth_provider: "google", auth_surface: surface },
+ });
+ await clickGoogle();
+ expect(mocks.signIn).toHaveBeenCalledTimes(2);
+ });
+
+ it("preserves the callback and does not show an error after success", async () => {
+ mocks.searchParams.set("next", "/dashboard/caps");
+ await act(async () => root.render(createElement(Form)));
+ await clickGoogle();
+ expect(mocks.signIn).toHaveBeenCalledWith("google", {
+ callbackUrl: "/dashboard/caps",
+ });
+ expect(mocks.error).not.toHaveBeenCalled();
+ });
+});
+
+it.each(["apple", "google"])(
+ "handles failed automatic mobile %s sign-in without an unhandled rejection",
+ async (provider) => {
+ mocks.searchParams.set("mobileProvider", provider);
+ mocks.signIn.mockRejectedValueOnce(new TypeError("Load failed"));
+ await act(async () => root.render(createElement(LoginForm)));
+ expect(mocks.signIn).toHaveBeenCalledWith(provider, {});
+ expect(mocks.error).toHaveBeenCalledWith(
+ "Could not start sign-in. Check your connection and try again.",
+ );
+ },
+);
diff --git a/apps/web/__tests__/unit/sentry-browser-filter.test.ts b/apps/web/__tests__/unit/sentry-browser-filter.test.ts
new file mode 100644
index 000000000..144f1313e
--- /dev/null
+++ b/apps/web/__tests__/unit/sentry-browser-filter.test.ts
@@ -0,0 +1,54 @@
+import { type Client, type Event, eventFiltersIntegration } from "@sentry/core";
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ init: vi.fn() }));
+vi.mock("@sentry/nextjs", () => ({
+ init: mocks.init,
+ captureRouterTransitionStart: vi.fn(),
+}));
+
+vi.stubEnv("NEXT_PUBLIC_SENTRY_DSN", "https://[email protected]/1");
+await import("../../instrumentation-client");
+const options = mocks.init.mock.calls[0]?.[0];
+afterAll(() => vi.unstubAllEnvs());
+
+function filter(filename: string, message = "Failed to connect to MetaMask") {
+ const event: Event = {
+ exception: {
+ values: [
+ {
+ type: "Error",
+ value: message,
+ stacktrace: { frames: [{ filename, lineno: 7 }] },
+ },
+ ],
+ },
+ };
+ return eventFiltersIntegration().processEvent?.(event, {}, {
+ getOptions: () => options,
+ } as Client);
+}
+
+describe("Sentry browser extension filtering", () => {
+ it.each(["chrome", "moz", "safari", "safari-web"])(
+ "drops errors originating in %s extensions",
+ (scheme) => {
+ expect(filter(`${scheme}-extension://extension/scripts/inpage.js`)).toBe(
+ null,
+ );
+ },
+ );
+
+ it.each(["Load failed", "La", "Failed to connect to MetaMask"])(
+ "retains application errors named %s",
+ (message) => {
+ expect(filter("https://cap.so/_next/static/chunk.js", message)).not.toBe(
+ null,
+ );
+ },
+ );
+
+ it("retains unknown sources instead of guessing from the message", () => {
+ expect(filter("app:///assets/js/content.js")).not.toBe(null);
+ });
+});
diff --git a/apps/web/__tests__/unit/video-analytics-bulk.test.ts b/apps/web/__tests__/unit/video-analytics-bulk.test.ts
new file mode 100644
index 000000000..4d68e8d13
--- /dev/null
+++ b/apps/web/__tests__/unit/video-analytics-bulk.test.ts
@@ -0,0 +1,156 @@
+import { CurrentUser, Organisation, User, Video } from "@cap/web-domain";
+import { Effect, Exit, Option } from "effect";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ rows: [] as Record<string, unknown>[],
+ select: vi.fn(),
+ query: vi.fn(),
+ readError: undefined as Error | undefined,
+}));
+
+vi.mock("@cap/database", () => ({
+ db: () => ({
+ select: (columns: unknown) => {
+ mocks.select(columns);
+ return {
+ from: () => ({
+ where: async () => {
+ if (mocks.readError) throw mocks.readError;
+ return mocks.rows;
+ },
+ }),
+ };
+ },
+ }),
+}));
+vi.mock("@cap/utils", () => ({ dub: {} }));
+vi.mock("@cap/web-backend/src/Storage/index", async () => {
+ const { Effect } = await import("effect");
+ class Storage extends Effect.Service<Storage>()("Storage", {
+ sync: () => ({}),
+ }) {}
+ return { Storage };
+});
+vi.mock("@cap/web-backend/src/Tinybird/index", async () => {
+ const { Effect } = await import("effect");
+ class Tinybird extends Effect.Service<Tinybird>()("Tinybird", {
+ sync: () => ({
+ querySql: (sql: string) => {
+ mocks.query(sql);
+ return Effect.succeed({
+ data: [{ pathname: "/s/owned", views: 12 }],
+ });
+ },
+ }),
+ }) {}
+ return { Tinybird };
+});
+
+const { Videos } = await import("@cap/web-backend/src/Videos/index");
+const { VideosPolicy } = await import(
+ "@cap/web-backend/src/Videos/VideosPolicy"
+);
+const { VideosRepo } = await import("@cap/web-backend/src/Videos/VideosRepo");
+const { Database } = await import("@cap/web-backend/src/Database");
+const { Storage } = await import("@cap/web-backend/src/Storage/index");
+const { Tinybird } = await import("@cap/web-backend/src/Tinybird/index");
+const { Policy } = await import("@cap/web-domain");
+const check = vi.fn((video: { id: string }) =>
+ video.id === "denied"
+ ? Effect.fail(new Policy.PolicyDeniedError())
+ : video.id === "protected"
+ ? Effect.fail(
+ new Video.VerifyVideoPasswordError({
+ id: Video.VideoId.make(video.id),
+ cause: "not-provided",
+ }),
+ )
+ : Effect.void,
+);
+const user: CurrentUser["Type"] = {
+ id: User.UserId.make("owner"),
+ email: "[email protected]",
+ activeOrganizationId: Organisation.OrganisationId.make("org"),
+ iconUrlOrKey: Option.none(),
+};
+
+function run(ids: string[]) {
+ return Effect.runPromise(
+ Effect.flatMap(Videos, (videos) =>
+ videos.getAnalyticsBulk(ids.map((id) => Video.VideoId.make(id))),
+ ).pipe(
+ Effect.provide(Videos.DefaultWithoutDependencies),
+ Effect.provideService(
+ VideosPolicy,
+ VideosPolicy.make({
+ canViewLoaded: check,
+ canView: vi.fn(),
+ isOwner: vi.fn(),
+ isOwnerLoaded: vi.fn(),
+ getViewableById: vi.fn(),
+ getOwnedById: vi.fn(),
+ }),
+ ),
+ Effect.provide([
+ Database.Default,
+ VideosRepo.Default,
+ Storage.Default,
+ Tinybird.Default,
+ ]),
+ Effect.provideService(CurrentUser, user),
+ ),
+ );
+}
+
+beforeEach(() => {
+ mocks.readError = undefined;
+ mocks.rows = ["owned", "denied", "protected"].map((id) => ({
+ id,
+ ownerId: "owner",
+ orgId: "org",
+ public: false,
+ password: id === "protected" ? "password-hash" : null,
+ }));
+});
+
+describe("bulk video analytics", () => {
+ it("batches lookups and preserves order, duplicates and missing results", async () => {
+ const results = await run(["missing", "owned", "owned"]);
+ expect(results.map((result) => Exit.getOrElse(result, () => null))).toEqual(
+ [{ count: 0 }, { count: 12 }, { count: 12 }],
+ );
+ expect(mocks.select).toHaveBeenCalledTimes(1);
+ expect(mocks.query).toHaveBeenCalledTimes(1);
+ });
+
+ it("preserves per-video access and password failures", async () => {
+ const results = await run(["denied", "owned", "protected"]);
+ expect(results.map((result) => Exit.isFailure(result))).toEqual([
+ true,
+ false,
+ true,
+ ]);
+ expect(results.map((result) => Exit.getOrElse(result, () => null))).toEqual(
+ [null, { count: 12 }, null],
+ );
+ expect(mocks.query.mock.calls[0]?.[0]).not.toContain("/s/denied");
+ expect(mocks.query.mock.calls[0]?.[0]).not.toContain("/s/protected");
+ expect(check).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "protected" }),
+ Option.some("password-hash"),
+ );
+ });
+
+ it("does not read the database for an empty batch", async () => {
+ expect(await run([])).toEqual([]);
+ expect(mocks.select).not.toHaveBeenCalled();
+ expect(mocks.query).not.toHaveBeenCalled();
+ });
+
+ it("reports database failures instead of returning zero views", async () => {
+ mocks.readError = new Error("Database unavailable");
+ await expect(run(["owned"])).rejects.toThrow();
+ expect(mocks.query).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/__tests__/unit/video-status.test.ts b/apps/web/__tests__/unit/video-status.test.ts
new file mode 100644
index 000000000..ee8a08589
--- /dev/null
+++ b/apps/web/__tests__/unit/video-status.test.ts
@@ -0,0 +1,115 @@
+import { Video } from "@cap/web-domain";
+import { QueryClient } from "@tanstack/react-query";
+import { Effect } from "effect";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ rows: [] as Record<string, unknown>[],
+ allowed: true,
+ read: vi.fn(),
+ transcribe: vi.fn(),
+ generate: vi.fn(),
+}));
+
+vi.mock("@cap/database", () => ({
+ db: () => ({
+ select: () => ({
+ from: () => ({
+ where: async () => {
+ mocks.read();
+ return mocks.rows;
+ },
+ }),
+ }),
+ }),
+}));
+vi.mock("@cap/env", () => ({ serverEnv: () => ({}) }));
+vi.mock("@cap/web-backend", async () => {
+ const { Effect } = await import("effect");
+ const { Policy } = await import("@cap/web-domain");
+ class VideosPolicy extends Effect.Service<VideosPolicy>()("VideosPolicy", {
+ sync: () => ({
+ canView: () =>
+ mocks.allowed
+ ? Effect.void
+ : Effect.fail(new Policy.PolicyDeniedError()),
+ }),
+ }) {}
+ return {
+ VideosPolicy,
+ provideOptionalAuth: Effect.provide(VideosPolicy.Default),
+ };
+});
+vi.mock("@/lib/server", () => ({ runPromiseExit: Effect.runPromiseExit }));
+vi.mock("@/lib/ai/provider", () => ({ isAiConfigured: () => false }));
+vi.mock("@/lib/desktop-segments-finalization", () => ({
+ isRetryableDesktopSegmentsFinalizationError: () => false,
+ queueDesktopSegmentsFinalization: vi.fn(),
+}));
+vi.mock("@/lib/generate-ai", () => ({ startAiGeneration: mocks.generate }));
+vi.mock("@/lib/transcribe", () => ({ transcribeVideo: mocks.transcribe }));
+vi.mock("@/utils/flags", () => ({ isAiGenerationEnabled: () => false }));
+
+const { getVideoStatus } = await import("@/actions/videos/get-status");
+const { videoStatusQueryOptions, VideoStatusNotFoundError } = await import(
+ "@/lib/video-status-query"
+);
+const videoId = Video.VideoId.make("missing-video");
+
+beforeEach(() => {
+ mocks.rows = [];
+ mocks.allowed = true;
+});
+
+describe("video status", () => {
+ it("returns an expected missing result without triggering processing", async () => {
+ await expect(getVideoStatus(videoId)).resolves.toEqual({
+ success: false,
+ reason: "not_found",
+ });
+ expect(mocks.transcribe).not.toHaveBeenCalled();
+ expect(mocks.generate).not.toHaveBeenCalled();
+ });
+
+ it("keeps access denial separate from a missing video", async () => {
+ mocks.allowed = false;
+ await expect(getVideoStatus(videoId)).resolves.toEqual({ success: false });
+ expect(mocks.read).not.toHaveBeenCalled();
+ });
+
+ it("preserves metadata for an available video", async () => {
+ mocks.rows = [{ name: "Recording", transcriptionStatus: "COMPLETE" }];
+ await expect(getVideoStatus(videoId)).resolves.toMatchObject({
+ name: "Recording",
+ transcriptionStatus: "COMPLETE",
+ });
+ });
+
+ it("does not retry missing videos even when initial data is cached", async () => {
+ const client = new QueryClient();
+ const options = videoStatusQueryOptions(videoId);
+ client.setQueryData(options.queryKey, { name: "Old recording" });
+ await expect(
+ client.fetchQuery({ ...options, retryDelay: 0 }),
+ ).rejects.toBeInstanceOf(VideoStatusNotFoundError);
+ expect(mocks.read).toHaveBeenCalledTimes(1);
+ client.clear();
+ });
+
+ it("still retries other failures", async () => {
+ const client = new QueryClient();
+ let attempts = 0;
+ const result = await client.fetchQuery({
+ ...videoStatusQueryOptions(videoId),
+ retryDelay: 0,
+ queryFn: async () => {
+ attempts++;
+ if (attempts < 3) throw new TypeError("Failed to fetch");
+ return "recovered";
+ },
+ });
+ expect(result).toBe("recovered");
+ expect(attempts).toBe(3);
+ client.clear();
+ });
+});
diff --git a/apps/web/actions/videos/get-status.ts b/apps/web/actions/videos/get-status.ts
index 282ad7488..ba7ac039b 100644
--- a/apps/web/actions/videos/get-status.ts
+++ b/apps/web/actions/videos/get-status.ts
@@ -44,7 +44,7 @@ export interface VideoStatusResult {
export async function getVideoStatus(
videoId: Video.VideoId,
-): Promise<VideoStatusResult | { success: false }> {
+): Promise<VideoStatusResult | { success: false; reason?: "not_found" }> {
if (!videoId) throw new Error("Video ID not provided");
const exit = await Effect.gen(function* () {
@@ -58,7 +58,7 @@ export async function getVideoStatus(
if (Exit.isFailure(exit)) return { success: false };
const video = exit.value[0];
- if (!video) throw new Error("Video not found");
+ if (!video) return { success: false, reason: "not_found" };
const metadata: VideoMetadata = (video.metadata as VideoMetadata) || {};
diff --git a/apps/web/app/(org)/login/form.tsx b/apps/web/app/(org)/login/form.tsx
index 5172e8ae5..49ddf9640 100644
--- a/apps/web/app/(org)/login/form.tsx
+++ b/apps/web/app/(org)/login/form.tsx
@@ -7,6 +7,7 @@ import {
faExclamationCircle,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { captureException } from "@sentry/nextjs";
import { AnimatePresence, motion } from "framer-motion";
import Cookies from "js-cookie";
import { LucideArrowUpRight } from "lucide-react";
@@ -162,6 +163,13 @@ export function LoginForm() {
});
signIn("google", {
...(nextPath ? { callbackUrl: nextPath } : {}),
+ }).catch((error) => {
+ captureException(error, {
+ tags: { auth_provider: "google", auth_surface: "login" },
+ });
+ toast.error(
+ "Could not start sign-in. Check your connection and try again.",
+ );
});
}, [getNextPath]);
@@ -174,6 +182,13 @@ export function LoginForm() {
});
signIn("apple", {
...(nextPath ? { callbackUrl: nextPath } : {}),
+ }).catch((error) => {
+ captureException(error, {
+ tags: { auth_provider: "apple", auth_surface: "login" },
+ });
+ toast.error(
+ "Could not start sign-in. Check your connection and try again.",
+ );
});
}, [getNextPath]);
diff --git a/apps/web/app/(org)/signup/form.tsx b/apps/web/app/(org)/signup/form.tsx
index ab81a3579..5380dec7c 100644
--- a/apps/web/app/(org)/signup/form.tsx
+++ b/apps/web/app/(org)/signup/form.tsx
@@ -7,6 +7,7 @@ import {
faExclamationCircle,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { captureException } from "@sentry/nextjs";
import { AnimatePresence, motion } from "framer-motion";
import Cookies from "js-cookie";
import { LucideArrowUpRight } from "lucide-react";
@@ -169,6 +170,13 @@ export function SignupForm() {
});
signIn("google", {
...(nextPath ? { callbackUrl: nextPath } : {}),
+ }).catch((error) => {
+ captureException(error, {
+ tags: { auth_provider: "google", auth_surface: "signup" },
+ });
+ toast.error(
+ "Could not start sign-in. Check your connection and try again.",
+ );
});
};
diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx
index 92cf33f03..8b7ca30f9 100644
--- a/apps/web/app/s/[videoId]/Share.tsx
+++ b/apps/web/app/s/[videoId]/Share.tsx
@@ -20,12 +20,12 @@ import {
useRef,
useState,
} from "react";
-import {
- getVideoStatus,
- type VideoStatusResult,
-} from "@/actions/videos/get-status";
import type { OrganizationSettings } from "@/app/(org)/dashboard/dashboard-data";
import { SignedImageUrl } from "@/components/SignedImageUrl";
+import {
+ VideoStatusNotFoundError,
+ videoStatusQueryOptions,
+} from "@/lib/video-status-query";
import { CaptionProvider } from "./_components/CaptionContext";
import { PlaybackProvider } from "./_components/playback/PlaybackContext";
import { ShareVideo } from "./_components/ShareVideo";
@@ -235,13 +235,7 @@ const useVideoStatus = (
enabled: boolean = true,
) => {
return useQuery({
- queryKey: ["videoStatus", videoId],
- queryFn: async (): Promise<VideoStatusResult> => {
- const res = await getVideoStatus(videoId);
- if ("success" in res && res.success === false)
- throw new Error("Failed to fetch video status");
- return res as VideoStatusResult;
- },
+ ...videoStatusQueryOptions(videoId),
initialData: initialData
? {
transcriptionStatus:
@@ -257,6 +251,7 @@ const useVideoStatus = (
: undefined,
enabled,
refetchInterval: (query) => {
+ if (query.state.error instanceof VideoStatusNotFoundError) return false;
const data = query.state.data;
if (!data) return 2000;
diff --git a/apps/web/instrumentation-client.ts b/apps/web/instrumentation-client.ts
index 408230ef5..401283631 100644
--- a/apps/web/instrumentation-client.ts
+++ b/apps/web/instrumentation-client.ts
@@ -10,6 +10,7 @@ if (dsn) {
replaysSessionSampleRate: 0,
replaysOnErrorSampleRate: 0,
maxBreadcrumbs: 30,
+ denyUrls: [/^(?:chrome|moz|safari(?:-web)?)-extension:\/\//i],
integrations: (integrations) =>
integrations.filter(
({ name }) => name !== "BrowserTracing" && name !== "BrowserSession",
diff --git a/apps/web/lib/video-status-query.ts b/apps/web/lib/video-status-query.ts
new file mode 100644
index 000000000..722dcbbe4
--- /dev/null
+++ b/apps/web/lib/video-status-query.ts
@@ -0,0 +1,28 @@
+import type { Video } from "@cap/web-domain";
+import {
+ getVideoStatus,
+ type VideoStatusResult,
+} from "@/actions/videos/get-status";
+
+export class VideoStatusNotFoundError extends Error {
+ constructor() {
+ super("This video is no longer available");
+ this.name = "VideoStatusNotFoundError";
+ }
+}
+
+export function videoStatusQueryOptions(videoId: Video.VideoId) {
+ return {
+ queryKey: ["videoStatus", videoId],
+ queryFn: async (): Promise<VideoStatusResult> => {
+ const result = await getVideoStatus(videoId);
+ if ("success" in result) {
+ if (result.reason === "not_found") throw new VideoStatusNotFoundError();
+ throw new Error("Failed to fetch video status");
+ }
+ return result;
+ },
+ retry: (failureCount: number, error: Error) =>
+ !(error instanceof VideoStatusNotFoundError) && failureCount < 3,
+ };
+}
diff --git a/packages/web-backend/src/Videos/index.ts b/packages/web-backend/src/Videos/index.ts
index 1b15fa49e..8dd18bcb0 100644
--- a/packages/web-backend/src/Videos/index.ts
+++ b/packages/web-backend/src/Videos/index.ts
@@ -241,14 +241,36 @@ export class Videos extends Effect.Service<Videos>()("Videos", {
if (videoIds.length === 0)
return [] as Array<Exit.Exit<{ count: number }, unknown>>;
+ const rows = yield* db.use((database) =>
+ database
+ .select({
+ id: Db.videos.id,
+ orgId: Db.videos.orgId,
+ ownerId: Db.videos.ownerId,
+ public: Db.videos.public,
+ password: Db.videos.password,
+ })
+ .from(Db.videos)
+ .where(Dz.inArray(Db.videos.id, [...new Set(videoIds)])),
+ );
+ const videosById = new Map(rows.map((video) => [video.id, video]));
const videoExits = yield* Effect.forEach(
videoIds,
- (videoId) => getByIdForViewing(videoId).pipe(Effect.exit),
+ (videoId) => {
+ const video = videosById.get(videoId);
+ if (!video)
+ return Effect.succeed(
+ Exit.succeed(Option.none<(typeof rows)[number]>()),
+ );
+ return policy
+ .canViewLoaded(video, Option.fromNullable(video.password))
+ .pipe(Effect.as(Option.some(video)), Effect.exit);
+ },
{ concurrency: 10 },
);
const analyticsVideos = videoExits.flatMap((exit) => {
if (!Exit.isSuccess(exit) || Option.isNone(exit.value)) return [];
- const [video] = exit.value.value;
+ const video = exit.value.value;
return [{ id: video.id, orgId: video.orgId }];
});
const countsByPathname = yield* getAnalyticsCounts(analyticsVideos);