Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Improve Loom download and streaming support
Richie McIlroydb9c78e69930
diff --git a/apps/web/actions/loom.ts b/apps/web/actions/loom.tsindex fb5ca173d..795339519 100644--- a/apps/web/actions/loom.ts+++ b/apps/web/actions/loom.ts@@ -59,23 +59,26 @@ function extractLoomVideoId(url: string): string | null {async function fetchLoomEndpoint(videoId: string,endpoint: string,+ includeBody = true,): Promise<string | null> {try {+ const options: RequestInit = { method: "POST" };+ if (includeBody) {+ options.headers = {+ "Content-Type": "application/json",+ Accept: "application/json",+ };+ options.body = JSON.stringify({+ anonID: randomUUID(),+ deviceID: null,+ force_original: false,+ password: null,+ });+ }+const response = await fetch(`https://www.loom.com/api/campaigns/sessions/${videoId}/${endpoint}`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- Accept: "application/json",- },- body: JSON.stringify({- anonID: randomUUID(),- deviceID: null,- force_original: false,- password: null,- }),- },+ options,);if (!response.ok || response.status === 204) {@@ -131,16 +134,25 @@ function isStreamingUrl(url: string): boolean {}async function getLoomDownloadUrl(loomVideoId: string): Promise<string | null> {- const endpoints = ["transcoded-url", "raw-url"] as const;+ const requestVariants: Array<{ endpoint: string; includeBody: boolean }> = [+ { endpoint: "transcoded-url", includeBody: true },+ { endpoint: "raw-url", includeBody: true },+ { endpoint: "transcoded-url", includeBody: false },+ { endpoint: "raw-url", includeBody: false },+ ];- for (const endpoint of endpoints) {- const url = await fetchLoomEndpoint(loomVideoId, endpoint);+ let fallbackStreamingUrl: string | null = null;++ for (const { endpoint, includeBody } of requestVariants) {+ const url = await fetchLoomEndpoint(loomVideoId, endpoint, includeBody);if (!url) continue;if (!isStreamingUrl(url)) return url;++ if (!fallbackStreamingUrl) fallbackStreamingUrl = url;}- return null;+ return fallbackStreamingUrl;}async function fetchLoomOEmbed(@@ -181,10 +193,9 @@ export async function downloadLoomVideo(}try {- const transcodedUrl = await fetchLoomEndpoint(videoId, "transcoded-url");- const rawUrl = await fetchLoomEndpoint(videoId, "raw-url");+ const downloadUrl = await getLoomDownloadUrl(videoId);- if (!transcodedUrl && !rawUrl) {+ if (!downloadUrl) {return {success: false,error:diff --git a/apps/web/workflows/import-loom-video.ts b/apps/web/workflows/import-loom-video.tsindex 19113bd0b..47f2c18a8 100644--- a/apps/web/workflows/import-loom-video.ts+++ b/apps/web/workflows/import-loom-video.ts@@ -20,47 +20,343 @@ interface ImportLoomPayload {const MINIMUM_VIDEO_SIZE = 1024;+function isStreamingUrl(url: string): boolean {+ const path = (url.split("?")[0] ?? "").toLowerCase();+ return path.endsWith(".m3u8") || path.endsWith(".mpd");+}++function isMpdUrl(url: string): boolean {+ return (url.split("?")[0] ?? "").toLowerCase().endsWith(".mpd");+}++async function fetchLoomCdnUrl(+ videoId: string,+ endpoint: string,+ includeBody: boolean,+): Promise<string | null> {+ try {+ const options: RequestInit = { method: "POST" };+ if (includeBody) {+ options.headers = {+ "Content-Type": "application/json",+ Accept: "application/json",+ };+ options.body = JSON.stringify({+ anonID: randomUUID(),+ deviceID: null,+ force_original: false,+ password: null,+ });+ }++ const response = await fetch(+ `https://www.loom.com/api/campaigns/sessions/${videoId}/${endpoint}`,+ options,+ );++ if (!response.ok || response.status === 204) return null;++ const text = await response.text();+ if (!text.trim()) return null;++ const data = JSON.parse(text) as { url?: string };+ return data.url ?? null;+ } catch {+ return null;+ }+}+async function fetchFreshLoomDownloadUrl(loomVideoId: string): Promise<string> {- const endpoints = ["transcoded-url", "raw-url"] as const;+ const requestVariants: Array<{ endpoint: string; includeBody: boolean }> = [+ { endpoint: "transcoded-url", includeBody: true },+ { endpoint: "raw-url", includeBody: true },+ { endpoint: "transcoded-url", includeBody: false },+ { endpoint: "raw-url", includeBody: false },+ ];- for (const endpoint of endpoints) {- try {- const response = await fetch(- `https://www.loom.com/api/campaigns/sessions/${loomVideoId}/${endpoint}`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- Accept: "application/json",- },- body: JSON.stringify({- anonID: randomUUID(),- deviceID: null,- force_original: false,- password: null,- }),- },+ let fallbackStreamingUrl: string | null = null;++ for (const { endpoint, includeBody } of requestVariants) {+ const url = await fetchLoomCdnUrl(loomVideoId, endpoint, includeBody);+ if (!url) continue;++ if (!isStreamingUrl(url)) return url;++ if (!fallbackStreamingUrl) fallbackStreamingUrl = url;+ }++ if (fallbackStreamingUrl) return fallbackStreamingUrl;++ throw new FatalError(+ "Could not retrieve a download URL from Loom. The video may be private, password-protected, or the link may have expired.",+ );+}++function parseMpdVideoSegments(+ mpdXml: string,+ baseUrl: string,+ queryParams: string,+): { initUrl: string; mediaUrls: string[] } | null {+ const adaptationSets = [+ ...mpdXml.matchAll(/<AdaptationSet([^>]*)>([\s\S]*?)<\/AdaptationSet>/g),+ ];++ for (const asMatch of adaptationSets) {+ const attrs = asMatch[1] ?? "";+ const content = asMatch[2] ?? "";+ const contentType = attrs.match(/contentType="([^"]+)"/)?.[1];++ if (contentType !== "video") continue;++ const representations = [+ ...content.matchAll(+ /<Representation([^>]*)>([\s\S]*?)<\/Representation>/g,+ ),+ ];+ let bestBandwidth = 0;+ let bestRepContent = "";++ for (const repMatch of representations) {+ const repAttrs = repMatch[1] ?? "";+ const repContent = repMatch[2] ?? "";+ const bandwidth = parseInt(+ repAttrs.match(/bandwidth="(\d+)"/)?.[1] ?? "0",+ 10,);+ if (bandwidth > bestBandwidth) {+ bestBandwidth = bandwidth;+ bestRepContent = repContent;+ }+ }- if (!response.ok || response.status === 204) continue;+ if (!bestRepContent) continue;- const text = await response.text();- if (!text.trim()) continue;+ const templateMatch = bestRepContent.match(+ /<SegmentTemplate([^>]*)>([\s\S]*?)<\/SegmentTemplate>/,+ );+ if (!templateMatch) continue;++ const templateAttrs = templateMatch[1] ?? "";+ const templateContent = templateMatch[2] ?? "";++ const initFilename = templateAttrs.match(/initialization="([^"]+)"/)?.[1];+ const mediaTemplate = templateAttrs.match(/media="([^"]+)"/)?.[1];+ const startNumber = parseInt(+ templateAttrs.match(/startNumber="(\d+)"/)?.[1] ?? "0",+ 10,+ );++ if (!initFilename || !mediaTemplate) continue;++ const sElements = [...templateContent.matchAll(/<S\s([^/]*?)\/>/g)];+ let segmentCount = 0;++ for (const sEl of sElements) {+ const r = parseInt(sEl[1]?.match(/r="(\d+)"/)?.[1] ?? "0", 10);+ segmentCount += 1 + r;+ }- const data = JSON.parse(text) as { url?: string };- const url = data.url;- if (!url) continue;+ const initUrl = `${baseUrl}${initFilename}${queryParams}`;+ const mediaUrls: string[] = [];+ for (let i = startNumber; i < startNumber + segmentCount; i++) {+ const filename = mediaTemplate.replace("$Number$", String(i));+ mediaUrls.push(`${baseUrl}${filename}${queryParams}`);+ }++ return { initUrl, mediaUrls };+ }++ return null;+}- const path = (url.split("?")[0] ?? "").toLowerCase();- if (path.endsWith(".m3u8") || path.endsWith(".mpd")) continue;+function parseHlsMediaPlaylist(+ content: string,+ baseUrl: string,+ queryParams: string,+): string[] {+ return content+ .split("\n")+ .map((l) => l.trim())+ .filter((l) => l && !l.startsWith("#"))+ .map((l) => (l.startsWith("http") ? l : `${baseUrl}${l}${queryParams}`));+}- return url;+async function downloadSegmentsToBuffer(urls: string[]): Promise<Buffer> {+ const chunks: Buffer[] = [];+ for (const url of urls) {+ const response = await fetch(url);+ if (!response.ok) continue;+ chunks.push(Buffer.from(await response.arrayBuffer()));+ }+ return Buffer.concat(chunks);+}++async function tryMp4Candidates(+ resourceBaseUrl: string,+ queryParams: string,+ loomVideoId: string,+): Promise<Buffer | null> {+ const mp4Candidates = [+ `${resourceBaseUrl}${loomVideoId}.mp4${queryParams}`,+ `${resourceBaseUrl}output.mp4${queryParams}`,+ ];++ for (const mp4Url of mp4Candidates) {+ try {+ const headRes = await fetch(mp4Url, { method: "HEAD" });+ if (!headRes.ok) continue;++ const response = await fetch(mp4Url);+ if (!response.ok) continue;++ const buffer = Buffer.from(await response.arrayBuffer());+ if (buffer.length >= MINIMUM_VIDEO_SIZE) return buffer;} catch {}}- throw new FatalError(- "Could not retrieve a direct download URL from Loom. The video may only be available as a stream.",+ return null;+}++async function downloadFromStreamingUrl(+ streamingUrl: string,+ loomVideoId: string,+): Promise<Buffer> {+ const parsedUrl = new URL(streamingUrl);+ const queryParams = parsedUrl.search;+ const pathUpToSlash = parsedUrl.pathname.substring(+ 0,+ parsedUrl.pathname.lastIndexOf("/") + 1,);+ const streamingBaseUrl = `${parsedUrl.origin}${pathUpToSlash}`;++ let resourceBaseUrl = streamingBaseUrl;+ if (pathUpToSlash.endsWith("/hls/")) {+ resourceBaseUrl = `${parsedUrl.origin}${pathUpToSlash.slice(0, -4)}`;+ }++ const mp4Buffer = await tryMp4Candidates(+ resourceBaseUrl,+ queryParams,+ loomVideoId,+ );+ if (mp4Buffer) return mp4Buffer;++ if (isMpdUrl(streamingUrl)) {+ const mpdResponse = await fetch(streamingUrl);+ if (!mpdResponse.ok) {+ throw new FatalError("Failed to fetch video manifest from Loom");+ }++ const mpdXml = await mpdResponse.text();+ const segments = parseMpdVideoSegments(+ mpdXml,+ streamingBaseUrl,+ queryParams,+ );++ if (!segments || segments.mediaUrls.length === 0) {+ throw new FatalError("Could not parse video segments from Loom manifest");+ }++ return await downloadSegmentsToBuffer([+ segments.initUrl,+ ...segments.mediaUrls,+ ]);+ }++ const masterResponse = await fetch(streamingUrl);+ if (!masterResponse.ok) {+ throw new FatalError("Failed to fetch HLS playlist from Loom");+ }++ const masterContent = await masterResponse.text();+ const masterLines = masterContent.split("\n").map((l) => l.trim());++ const isMediaPlaylist = masterLines.some(+ (l) => l.startsWith("#EXTINF:") || l.startsWith("#EXT-X-TARGETDURATION:"),+ );++ let segmentUrls: string[];++ if (isMediaPlaylist) {+ segmentUrls = parseHlsMediaPlaylist(+ masterContent,+ streamingBaseUrl,+ queryParams,+ );+ } else {+ let bestBandwidth = 0;+ let bestVariantUrl: string | null = null;++ for (let i = 0; i < masterLines.length; i++) {+ const line = masterLines[i];+ if (line?.startsWith("#EXT-X-STREAM-INF:")) {+ const bwMatch = line.match(/BANDWIDTH=(\d+)/);+ const bandwidth = parseInt(bwMatch?.[1] ?? "0", 10);+ const nextLine = masterLines[i + 1]?.trim();+ if (+ nextLine &&+ !nextLine.startsWith("#") &&+ bandwidth > bestBandwidth+ ) {+ bestBandwidth = bandwidth;+ bestVariantUrl = nextLine.startsWith("http")+ ? nextLine+ : `${streamingBaseUrl}${nextLine}${queryParams}`;+ }+ }+ }++ if (!bestVariantUrl) {+ throw new FatalError("No video variants found in HLS playlist");+ }++ const variantResponse = await fetch(bestVariantUrl);+ if (!variantResponse.ok) {+ throw new FatalError("Failed to fetch HLS variant playlist from Loom");+ }++ const variantContent = await variantResponse.text();+ segmentUrls = parseHlsMediaPlaylist(+ variantContent,+ streamingBaseUrl,+ queryParams,+ );+ }++ if (segmentUrls.length === 0) {+ throw new FatalError("No video segments found in HLS playlist");+ }++ return await downloadSegmentsToBuffer(segmentUrls);+}++async function downloadVideoContent(+ downloadUrl: string,+ loomVideoId: string,+): Promise<Buffer> {+ if (isStreamingUrl(downloadUrl)) {+ return await downloadFromStreamingUrl(downloadUrl, loomVideoId);+ }++ const loomResponse = await fetch(downloadUrl);+ if (!loomResponse.ok) {+ throw new FatalError(+ `Failed to download from Loom: ${loomResponse.status} ${loomResponse.statusText}`,+ );+ }++ const contentType = loomResponse.headers.get("content-type") ?? "";+ if (+ contentType.includes("text/html") ||+ contentType.includes("application/json")+ ) {+ throw new FatalError(+ `Loom returned non-video content (${contentType}). The download URL may have expired.`,+ );+ }++ return Buffer.from(await loomResponse.arrayBuffer());}interface VideoProcessingResult {@@ -121,24 +417,7 @@ async function downloadLoomToS3(payload: ImportLoomPayload): Promise<void> {});}).pipe(runPromise);- const loomResponse = await fetch(freshDownloadUrl);- if (!loomResponse.ok) {- throw new FatalError(- `Failed to download from Loom: ${loomResponse.status} ${loomResponse.statusText}`,- );- }-- const contentType = loomResponse.headers.get("content-type") ?? "";- if (- contentType.includes("text/html") ||- contentType.includes("application/json")- ) {- throw new FatalError(- `Loom returned non-video content (${contentType}). The download URL may have expired.`,- );- }-- const videoBuffer = Buffer.from(await loomResponse.arrayBuffer());+ const videoBuffer = await downloadVideoContent(freshDownloadUrl, loomVideoId);if (videoBuffer.length < MINIMUM_VIDEO_SIZE) {throw new FatalError(@@ -148,7 +427,7 @@ async function downloadLoomToS3(payload: ImportLoomPayload): Promise<void> {const uploadResponse = await fetch(presignedPutUrl, {method: "PUT",- body: videoBuffer,+ body: new Uint8Array(videoBuffer),headers: {"Content-Type": "video/mp4","Content-Length": videoBuffer.length.toString(),