Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add Loom video downloader tool
Richie McIlroy4ac3a4ef96b9
diff --git a/apps/web/actions/loom.ts b/apps/web/actions/loom.tsnew file mode 100644index 000000000..281ffd941--- /dev/null+++ b/apps/web/actions/loom.ts@@ -0,0 +1,147 @@+"use server";++import { randomUUID } from "node:crypto";++interface LoomUrlResponse {+ url?: string;+}++interface LoomDownloadResult {+ success: boolean;+ videoId?: string;+ videoName?: string;+ error?: string;+}++function extractLoomVideoId(url: string): string | null {+ try {+ const parsed = new URL(url);+ if (!parsed.hostname.includes("loom.com")) {+ return null;+ }++ const pathParts = parsed.pathname.split("/").filter(Boolean);+ const id = pathParts[pathParts.length - 1] ?? null;++ if (!id || id.length < 10) {+ return null;+ }++ return id.split("?")[0] ?? null;+ } catch {+ return null;+ }+}++async function fetchLoomEndpoint(+ videoId: string,+ endpoint: string,+): Promise<string | null> {+ try {+ 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,+ }),+ },+ );++ if (!response.ok || response.status === 204) {+ return null;+ }++ const text = await response.text();+ if (!text.trim()) {+ return null;+ }++ const data: LoomUrlResponse = JSON.parse(text);+ return data.url ?? null;+ } catch {+ return null;+ }+}++async function fetchVideoName(videoId: string): Promise<string | null> {+ try {+ const response = await fetch("https://www.loom.com/graphql", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Accept: "application/json",+ "x-loom-request-source": "loom_web",+ },+ body: JSON.stringify({+ operationName: "GetVideoName",+ variables: { videoId, password: null },+ query: `query GetVideoName($videoId: ID!, $password: String) {+ getVideo(id: $videoId, password: $password) {+ ... on RegularUserVideo { name }+ ... on PrivateVideo { id }+ ... on VideoPasswordMissingOrIncorrect { id }+ }+ }`,+ }),+ });++ if (!response.ok) return null;++ const data = await response.json();+ return data?.data?.getVideo?.name ?? null;+ } catch {+ return null;+ }+}++export async function downloadLoomVideo(+ url: string,+): Promise<LoomDownloadResult> {+ if (!url || typeof url !== "string") {+ return { success: false, error: "Please provide a valid URL." };+ }++ const videoId = extractLoomVideoId(url.trim());++ if (!videoId) {+ return {+ success: false,+ error:+ "Invalid Loom URL. Please paste a valid Loom video link (e.g. https://www.loom.com/share/abc123).",+ };+ }++ try {+ const transcodedUrl = await fetchLoomEndpoint(videoId, "transcoded-url");+ const rawUrl = await fetchLoomEndpoint(videoId, "raw-url");++ if (!transcodedUrl && !rawUrl) {+ return {+ success: false,+ error:+ "Could not retrieve a download URL. The video may be private, password-protected, or the link may have expired.",+ };+ }++ const videoName = await fetchVideoName(videoId);+ return {+ success: true,+ videoId,+ videoName: videoName ?? undefined,+ };+ } catch {+ return {+ success: false,+ error:+ "An unexpected error occurred. Please try again or check your internet connection.",+ };+ }+}diff --git a/apps/web/app/(site)/Footer.tsx b/apps/web/app/(site)/Footer.tsxindex 9e3362a73..90e0b9161 100644--- a/apps/web/app/(site)/Footer.tsx+++ b/apps/web/app/(site)/Footer.tsx@@ -95,6 +95,7 @@ const footerLinks = {},] as FooterLink[],additional: [+ { label: "Loom Video Downloader", href: "/tools/loom-downloader" },{ label: "Screen Recorder", href: "/screen-recorder" },{ label: "Free Screen Recorder", href: "/free-screen-recorder" },{ label: "Screen Recorder for Mac", href: "/screen-recorder-mac" },diff --git a/apps/web/app/(site)/tools/PageContent.tsx b/apps/web/app/(site)/tools/PageContent.tsxindex 3b1b24300..4e372de1e 100644--- a/apps/web/app/(site)/tools/PageContent.tsx+++ b/apps/web/app/(site)/tools/PageContent.tsx@@ -11,6 +11,13 @@ interface ToolCategory {}const toolCategories: ToolCategory[] = [+ {+ title: "Loom Video Downloader",+ description:+ "Download any public Loom video as an MP4 file — free and instant",+ href: "/tools/loom-downloader",+ icon: "M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3",+ },{title: "File Conversion",description:@@ -35,13 +42,13 @@ const toolCategories: ToolCategory[] = [export function PageContent() {return (<>- <div className="relative overflow-hidden pt-[100px] md:pt-[180px]">- <div className="relative z-10 px-5 w-full h-full flex flex-col justify-center">+ <div className="relative overflow-hidden pt-24 md:pt-[180px]">+ <div className="relative z-10 px-4 w-full h-full flex flex-col justify-center sm:px-5"><div className="mx-auto text-center wrapper wrapper-sm">- <h1 className="fade-in-down text-[2rem] leading-[2.5rem] md:text-[2.75rem] md:leading-[3.25rem] font-medium relative z-10 text-black mb-6">+ <h1 className="fade-in-down text-[1.75rem] leading-[2.25rem] sm:text-[2rem] sm:leading-[2.5rem] md:text-[2.75rem] md:leading-[3.25rem] font-medium relative z-10 text-black mb-4 md:mb-6">Try our free tools</h1>- <p className="mx-auto mb-10 max-w-2xl text-md sm:text-xl text-zinc-500 fade-in-down animate-delay-1">+ <p className="mx-auto mb-8 max-w-2xl text-sm sm:text-md md:text-xl text-zinc-500 fade-in-down animate-delay-1 md:mb-10">Powerful browser-based utilities that run directly on your device.No uploads, no installations, maximum privacy.</p>@@ -50,17 +57,17 @@ export function PageContent() {</div></div><div className="wrapper mx-auto">- <div className="grid grid-cols-1 gap-8 sm:grid-cols-2 lg:grid-cols-3 px-12 mt-16">+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 sm:gap-6 lg:grid-cols-3 lg:gap-8 px-0 sm:px-4 lg:px-12 mt-10 md:mt-16">{toolCategories.map((category) => (<Linkkey={category.href}href={category.href}- className="group block p-8 border border-gray-200 bg-gray-1 rounded-xl hover:border-blue-500 hover:shadow-md transition-all"+ className="group block p-6 sm:p-8 border border-gray-200 bg-gray-1 rounded-xl hover:border-blue-500 hover:shadow-md transition-all"><div className="flex flex-col items-center text-center">- <div className="flex-shrink-0 p-3 bg-blue-100 rounded-xl mb-5">+ <div className="flex-shrink-0 p-3 bg-blue-100 rounded-xl mb-4 sm:mb-5"><svg- className="w-8 h-8 text-blue-600"+ className="w-7 h-7 sm:w-8 sm:h-8 text-blue-600"fill="none"viewBox="0 0 24 24"stroke="currentColor"@@ -73,29 +80,31 @@ export function PageContent() {/></svg></div>- <h2 className="text-2xl font-semibold text-gray-900 group-hover:text-blue-600 transition-colors mb-3">+ <h2 className="text-xl sm:text-2xl font-semibold text-gray-900 group-hover:text-blue-600 transition-colors mb-2 sm:mb-3">{category.title}</h2>- <p className="text-gray-600">{category.description}</p>+ <p className="text-sm sm:text-base text-gray-600">+ {category.description}+ </p></div></Link>))}</div><div- className="mx-auto wrapper mt-16 mb-8 bg-white rounded-3xl overflow-hidden relative flex flex-col justify-center p-12"+ className="mx-auto wrapper mt-10 mb-8 bg-white rounded-2xl sm:rounded-3xl overflow-hidden relative flex flex-col justify-center p-6 sm:p-8 md:p-12 md:mt-16"style={{- minHeight: "300px",+ minHeight: "250px",backgroundImage: "url('/illustrations/ctabg.svg')",backgroundSize: "cover",backgroundRepeat: "no-repeat",}}>- <div className=" mx-auto h-full flex flex-col justify-center items-center relative z-10">- <div className="text-center max-w-[800px] mx-auto mb-8">- <h2 className="text-3xl md:text-4xl font-medium text-gray-12 mb-4 drop-shadow-md">+ <div className="mx-auto h-full flex flex-col justify-center items-center relative z-10">+ <div className="text-center max-w-[800px] mx-auto mb-6 md:mb-8">+ <h2 className="text-2xl sm:text-3xl md:text-4xl font-medium text-gray-12 mb-3 md:mb-4 drop-shadow-md">The open source Loom alternative</h2>- <p className="text-xl mb-6 text-gray-10">+ <p className="text-base sm:text-lg md:text-xl mb-5 md:mb-6 text-gray-10">Cap is lightweight, powerful, and cross-platform. Record andshare securely in seconds with custom S3 bucket support.</p>diff --git a/apps/web/app/(site)/tools/loom-downloader/page.tsx b/apps/web/app/(site)/tools/loom-downloader/page.tsxnew file mode 100644index 000000000..9cf7efece--- /dev/null+++ b/apps/web/app/(site)/tools/loom-downloader/page.tsx@@ -0,0 +1,146 @@+import type { Metadata } from "next";+import { LoomDownloader } from "@/components/tools/LoomDownloader";+import { ToolsPageTemplate } from "@/components/tools/ToolsPageTemplate";+import type { ToolPageContent } from "@/components/tools/types";++export const metadata: Metadata = {+ title: "Loom Video Downloader — Download Loom Videos Free Online | Cap",+ description:+ "Download any Loom video for free with Cap's online Loom video downloader. No signup, no software needed — just paste your Loom link and save the MP4 instantly.",+ keywords: [+ "loom video downloader",+ "download loom video",+ "loom downloader",+ "save loom video",+ "loom video download free",+ "loom to mp4",+ "download loom recording",+ "loom video saver",+ "free loom downloader",+ "loom download tool",+ ],+ openGraph: {+ title: "Loom Video Downloader — Download Loom Videos Free | Cap",+ description:+ "Download any Loom video for free. Paste the link, get the MP4. No signup required. Built by Cap, the open source Loom alternative.",+ url: "https://cap.so/tools/loom-downloader",+ siteName: "Cap",+ type: "website",+ images: [+ {+ url: "/og.png",+ width: 1200,+ height: 630,+ alt: "Cap — Free Loom Video Downloader",+ },+ ],+ },+ twitter: {+ card: "summary_large_image",+ title: "Loom Video Downloader — Download Loom Videos Free | Cap",+ description:+ "Download any Loom video for free. Paste the link, get the MP4. No signup required.",+ images: ["/og.png"],+ },+ alternates: {+ canonical: "https://cap.so/tools/loom-downloader",+ },+};++const pageContent: ToolPageContent = {+ title: "Loom Video Downloader",+ description:+ "Download any public Loom video as an MP4 file. Just paste the link — no account, no installs, completely free.",+ featuresTitle: "Why Use Cap's Loom Video Downloader?",+ featuresDescription:+ 'Cap\'s Loom downloader is fast, free, and requires zero setup. Built by the team behind <a href="/">Cap — the open source Loom alternative</a>.',+ features: [+ {+ title: "Instant Downloads",+ description:+ "Paste a Loom link and get your MP4 in seconds. No waiting, no queues, no processing delays.",+ },+ {+ title: "No Account Required",+ description:+ "No signup, no login, no email. Just paste your Loom URL and download the video immediately.",+ },+ {+ title: "100% Free",+ description:+ "Completely free to use with no limits. Download as many Loom videos as you need, whenever you need them.",+ },+ {+ title: "Works with Any Public Loom Video",+ description:+ "Supports all public Loom video links including share links, embed links, and direct URLs.",+ },+ {+ title: "Nothing Stored on Our Servers",+ description:+ "We only fetch the download URL from Loom's servers. Your videos are never uploaded to or stored on Cap.",+ },+ {+ title: "MP4 Format",+ description:+ "Videos are downloaded in MP4 format — the most widely supported video format across all devices and platforms.",+ },+ ],+ faqs: [+ {+ question: "How do I download a Loom video?",+ answer:+ 'Simply paste the Loom video URL into the input field above and click "Download Video". The MP4 file will start downloading automatically. You can find Loom URLs by clicking the share button on any Loom video.',+ },+ {+ question: "Is this Loom video downloader free?",+ answer:+ "Yes, 100% free with no limits. There's no signup required, no premium tier, and no restrictions on the number of downloads.",+ },+ {+ question: "Can I download private Loom videos?",+ answer:+ "No, this tool only works with publicly accessible Loom videos. If a video requires a password or is set to private, you'll need to ask the video creator to make it public or share the download directly.",+ },+ {+ question: "What video format are downloads in?",+ answer:+ "All Loom videos are downloaded in MP4 format, which is compatible with virtually every device, media player, and video editor.",+ },+ {+ question: "Is there a file size limit?",+ answer:+ "There's no file size limit on our end. The download size depends on the length and quality of the original Loom recording.",+ },+ {+ question: "Why can't I download a specific Loom video?",+ answer:+ "Some Loom videos may be restricted by the creator (private, password-protected, or expired links). Make sure the video is publicly accessible. If you see an error, double-check that the URL is correct and the video hasn't been deleted.",+ },+ {+ question: "Do you store my downloaded videos?",+ answer:+ "No. We never store, cache, or process your videos. Our server simply fetches the direct download URL from Loom and passes it to your browser. The video downloads directly from Loom's servers to your device.",+ },+ {+ question: "What is Cap?",+ answer:+ 'Cap is the <a href="/">open source alternative to Loom</a>. It\'s a lightweight, privacy-focused screen recorder that lets you record, edit, and share videos instantly. If you\'re looking for a Loom replacement, <a href="/download">download Cap for free</a>.',+ },+ ],+ cta: {+ title: "Looking for a Loom alternative?",+ description:+ "Cap is the open source screen recorder that gives you full control. Record, edit, and share — all for free.",+ buttonText: "Download Cap Free",+ },+};++export default function LoomDownloaderPage() {+ return (+ <ToolsPageTemplate+ content={pageContent}+ toolComponent={<LoomDownloader />}+ />+ );+}diff --git a/apps/web/app/api/tools/loom-download/route.ts b/apps/web/app/api/tools/loom-download/route.tsnew file mode 100644index 000000000..92e8d7936--- /dev/null+++ b/apps/web/app/api/tools/loom-download/route.ts@@ -0,0 +1,539 @@+import { randomUUID } from "node:crypto";+import { type NextRequest, NextResponse } from "next/server";++interface SegmentInfo {+ initUrl: string;+ mediaUrls: string[];+}++function isHlsUrl(url: string): boolean {+ return (url.split("?")[0] ?? "").toLowerCase().endsWith(".m3u8");+}++function isMpdUrl(url: string): boolean {+ return (url.split("?")[0] ?? "").toLowerCase().endsWith(".mpd");+}++function isStreamingUrl(url: string): boolean {+ return isHlsUrl(url) || isMpdUrl(url);+}++function parseMpdSegments(+ mpdXml: string,+ baseUrl: string,+ queryParams: string,+): { video: SegmentInfo | null; audio: SegmentInfo | null } {+ const result = {+ video: null as SegmentInfo | null,+ audio: null as SegmentInfo | 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" && contentType !== "audio") 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 (!bestRepContent) 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 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}`);+ }++ const info: SegmentInfo = { initUrl, mediaUrls };++ if (contentType === "video") result.video = info;+ else result.audio = info;+ }++ return result;+}++async function streamSegments(+ segments: SegmentInfo,+ controller: ReadableStreamDefaultController<Uint8Array>,+) {+ const initResponse = await fetch(segments.initUrl);+ if (!initResponse.ok || !initResponse.body) {+ throw new Error(`Failed to fetch init segment: ${initResponse.status}`);+ }+ const initReader = initResponse.body.getReader();+ let done = false;+ while (!done) {+ const result = await initReader.read();+ done = result.done;+ if (result.value) controller.enqueue(result.value);+ }++ for (const mediaUrl of segments.mediaUrls) {+ const mediaResponse = await fetch(mediaUrl);+ if (!mediaResponse.ok || !mediaResponse.body) {+ throw new Error(`Failed to fetch media segment: ${mediaResponse.status}`);+ }+ const mediaReader = mediaResponse.body.getReader();+ done = false;+ while (!done) {+ const result = await mediaReader.read();+ done = result.done;+ if (result.value) controller.enqueue(result.value);+ }+ }+}++function parseHlsMasterPlaylist(+ content: string,+ baseUrl: string,+ queryParams: string,+): { bestVariantUrl: string | null; audioRenditionUrl: string | null } {+ const lines = content.split("\n").map((l) => l.trim());+ let audioRenditionUrl: string | null = null;+ let bestBandwidth = 0;+ let bestVariantUrl: string | null = null;++ for (const line of lines) {+ if (line.startsWith("#EXT-X-MEDIA:") && line.includes("TYPE=AUDIO")) {+ const uriMatch = line.match(/URI="([^"]+)"/);+ if (uriMatch?.[1]) {+ const uri = uriMatch[1];+ audioRenditionUrl = uri.startsWith("http")+ ? uri+ : `${baseUrl}${uri}${queryParams}`;+ }+ }+ }++ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (line?.startsWith("#EXT-X-STREAM-INF:")) {+ const bwMatch = line.match(/BANDWIDTH=(\d+)/);+ const bandwidth = parseInt(bwMatch?.[1] ?? "0", 10);+ const nextLine = lines[i + 1]?.trim();+ if (nextLine && !nextLine.startsWith("#") && bandwidth > bestBandwidth) {+ bestBandwidth = bandwidth;+ bestVariantUrl = nextLine.startsWith("http")+ ? nextLine+ : `${baseUrl}${nextLine}${queryParams}`;+ }+ }+ }++ return { bestVariantUrl, audioRenditionUrl };+}++function parseHlsMediaPlaylist(+ content: string,+ baseUrl: string,+ queryParams: string,+): string[] {+ return content+ .split("\n")+ .map((l) => l.trim())+ .filter((l) => l && !l.startsWith("#"))+ .map((l) => {+ if (l.startsWith("http")) return l;+ return `${baseUrl}${l}${queryParams}`;+ });+}++async function fetchLoomCdnUrl(+ videoId: string,+ endpoint: string,+ body: Record<string, unknown> | null,+): Promise<string | null> {+ try {+ const options: RequestInit = { method: "POST" };+ if (body) {+ options.headers = {+ "Content-Type": "application/json",+ Accept: "application/json",+ };+ options.body = JSON.stringify(body);+ }++ 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 tryGetDirectMp4Url(videoId: string): Promise<string | null> {+ const requestVariants: Array<{+ endpoint: string;+ body: Record<string, unknown> | null;+ }> = [+ {+ endpoint: "transcoded-url",+ body: {+ anonID: randomUUID(),+ deviceID: null,+ force_original: false,+ password: null,+ },+ },+ {+ endpoint: "raw-url",+ body: {+ anonID: randomUUID(),+ deviceID: null,+ force_original: false,+ password: null,+ },+ },+ { endpoint: "transcoded-url", body: null },+ { endpoint: "raw-url", body: null },+ ];++ let fallbackStreamingUrl: string | null = null;++ for (const { endpoint, body } of requestVariants) {+ const url = await fetchLoomCdnUrl(videoId, endpoint, body);+ if (!url) continue;++ if (!isStreamingUrl(url)) return url;++ if (!fallbackStreamingUrl) fallbackStreamingUrl = url;+ }++ return fallbackStreamingUrl;+}++async function tryMp4CandidateDownload(+ resourceBaseUrl: string,+ queryParams: string,+ videoId: string,+ filename: string,+): Promise<NextResponse | null> {+ const mp4Candidates = [+ `${resourceBaseUrl}${videoId}.mp4${queryParams}`,+ `${resourceBaseUrl}output.mp4${queryParams}`,+ ];++ for (const mp4Url of mp4Candidates) {+ try {+ const headRes = await fetch(mp4Url, { method: "HEAD" });+ if (!headRes.ok) continue;++ const mp4Response = await fetch(mp4Url);+ if (!mp4Response.ok || !mp4Response.body) continue;++ const mp4Body = mp4Response.body;+ const mp4Stream = new ReadableStream<Uint8Array>({+ async start(controller) {+ try {+ const reader = mp4Body.getReader();+ let done = false;+ while (!done) {+ const chunk = await reader.read();+ done = chunk.done;+ if (chunk.value) controller.enqueue(chunk.value);+ }+ controller.close();+ } catch {+ controller.close();+ }+ },+ });++ return new NextResponse(mp4Stream, {+ headers: {+ "Content-Type": "video/mp4",+ "Content-Disposition": `attachment; filename="${filename}"`,+ "Cache-Control": "no-store",+ },+ });+ } catch {}+ }++ return null;+}++export async function GET(request: NextRequest) {+ const videoId = request.nextUrl.searchParams.get("id");+ const videoName = request.nextUrl.searchParams.get("name");++ if (!videoId || videoId.length < 10) {+ return NextResponse.json(+ { error: "Missing or invalid video ID" },+ { status: 400 },+ );+ }++ const cdnUrl = await tryGetDirectMp4Url(videoId);++ if (!cdnUrl) {+ return NextResponse.json(+ {+ error:+ "Could not retrieve video URL. The video may be private or the link may have expired.",+ },+ { status: 404 },+ );+ }++ const sanitizedName = videoName+ ? videoName.replace(/[^a-zA-Z0-9\s\-_.]/g, "").trim()+ : "";++ if (!isStreamingUrl(cdnUrl)) {+ const mp4Filename = sanitizedName+ ? `${sanitizedName}.mp4`+ : `loom-video-${videoId}.mp4`;++ const directResponse = await fetch(cdnUrl);+ if (directResponse.ok && directResponse.body) {+ const body = directResponse.body;+ const stream = new ReadableStream<Uint8Array>({+ async start(controller) {+ try {+ const reader = body.getReader();+ let done = false;+ while (!done) {+ const chunk = await reader.read();+ done = chunk.done;+ if (chunk.value) controller.enqueue(chunk.value);+ }+ controller.close();+ } catch {+ controller.close();+ }+ },+ });++ return new NextResponse(stream, {+ headers: {+ "Content-Type": "video/mp4",+ "Content-Disposition": `attachment; filename="${mp4Filename}"`,+ "Cache-Control": "no-store",+ },+ });+ }++ return NextResponse.redirect(cdnUrl);+ }++ const parsedUrl = new URL(cdnUrl);+ 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 mp4Filename = sanitizedName+ ? `${sanitizedName}.mp4`+ : `loom-video-${videoId}.mp4`;++ const mp4Result = await tryMp4CandidateDownload(+ resourceBaseUrl,+ queryParams,+ videoId,+ mp4Filename,+ );+ if (mp4Result) return mp4Result;++ if (isMpdUrl(cdnUrl)) {+ const mpdResponse = await fetch(cdnUrl);+ if (!mpdResponse.ok) {+ return NextResponse.json(+ { error: "Failed to fetch video manifest" },+ { status: 502 },+ );+ }++ const mpdXml = await mpdResponse.text();+ const { video } = parseMpdSegments(mpdXml, streamingBaseUrl, queryParams);++ if (!video || video.mediaUrls.length === 0) {+ return NextResponse.json(+ { error: "Could not parse video segments from manifest" },+ { status: 502 },+ );+ }++ const webmFilename = sanitizedName+ ? `${sanitizedName}.webm`+ : `loom-video-${videoId}.webm`;++ const stream = new ReadableStream<Uint8Array>({+ async start(controller) {+ try {+ await streamSegments(video, controller);+ controller.close();+ } catch {+ controller.close();+ }+ },+ });++ return new NextResponse(stream, {+ headers: {+ "Content-Type": "video/webm",+ "Content-Disposition": `attachment; filename="${webmFilename}"`,+ "Cache-Control": "no-store",+ },+ });+ }++ const masterResponse = await fetch(cdnUrl);+ if (!masterResponse.ok) {+ return NextResponse.json(+ { error: "Failed to fetch HLS playlist" },+ { status: 502 },+ );+ }++ 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 = masterLines+ .filter((l) => l && !l.startsWith("#"))+ .map((l) =>+ l.startsWith("http") ? l : `${streamingBaseUrl}${l}${queryParams}`,+ );+ } else {+ const { bestVariantUrl } = parseHlsMasterPlaylist(+ masterContent,+ streamingBaseUrl,+ queryParams,+ );++ if (!bestVariantUrl) {+ return NextResponse.json(+ { error: "No video variants found in HLS playlist" },+ { status: 502 },+ );+ }++ const variantResponse = await fetch(bestVariantUrl);+ if (!variantResponse.ok) {+ return NextResponse.json(+ { error: "Failed to fetch HLS variant playlist" },+ { status: 502 },+ );+ }++ const variantContent = await variantResponse.text();+ segmentUrls = parseHlsMediaPlaylist(+ variantContent,+ streamingBaseUrl,+ queryParams,+ );+ }++ if (segmentUrls.length === 0) {+ return NextResponse.json(+ { error: "No video segments found in HLS playlist" },+ { status: 502 },+ );+ }++ const tsFilename = sanitizedName+ ? `${sanitizedName}.ts`+ : `loom-video-${videoId}.ts`;++ const stream = new ReadableStream<Uint8Array>({+ async start(controller) {+ try {+ for (const segUrl of segmentUrls) {+ const segResponse = await fetch(segUrl);+ if (!segResponse.ok || !segResponse.body) continue;+ const reader = segResponse.body.getReader();+ let done = false;+ while (!done) {+ const result = await reader.read();+ done = result.done;+ if (result.value) controller.enqueue(result.value);+ }+ }+ controller.close();+ } catch {+ controller.close();+ }+ },+ });++ return new NextResponse(stream, {+ headers: {+ "Content-Type": "video/mp2t",+ "Content-Disposition": `attachment; filename="${tsFilename}"`,+ "Cache-Control": "no-store",+ },+ });+}diff --git a/apps/web/components/tools/LoomDownloader.tsx b/apps/web/components/tools/LoomDownloader.tsxnew file mode 100644index 000000000..763add2f9--- /dev/null+++ b/apps/web/components/tools/LoomDownloader.tsx@@ -0,0 +1,264 @@+"use client";++import { Button } from "@cap/ui";+import { useCallback, useId, useRef, useState } from "react";+import { downloadLoomVideo } from "@/actions/loom";++type Status = "idle" | "fetching" | "downloading" | "converting" | "error";++function triggerBlobDownload(blob: Blob, filename: string) {+ const blobUrl = URL.createObjectURL(blob);+ const link = document.createElement("a");+ link.href = blobUrl;+ link.download = filename;+ document.body.appendChild(link);+ link.click();+ document.body.removeChild(link);+ URL.revokeObjectURL(blobUrl);+}++function needsConversion(contentType: string): boolean {+ return (+ contentType.includes("mp2t") ||+ contentType.includes("mpeg") ||+ contentType.includes("webm")+ );+}++function getInputFilename(contentType: string): string {+ if (contentType.includes("mp2t") || contentType.includes("mpeg")) {+ return "video.ts";+ }+ if (contentType.includes("webm")) {+ return "video.webm";+ }+ return "video.mp4";+}++async function convertBlobToMp4(+ blob: Blob,+ contentType: string,+ onProgress: (percent: number) => void,+): Promise<Blob> {+ const file = new File([blob], getInputFilename(contentType), {+ type: contentType,+ });+ const { convertMedia } = await import("@remotion/webcodecs");++ const result = await convertMedia({+ src: file,+ container: "mp4",+ videoCodec: "h264",+ audioCodec: "aac" as const,+ onProgress: ({ overallProgress }) => {+ if (overallProgress !== null) {+ onProgress(+ Math.min(100, Math.max(0, Math.round(overallProgress * 100))),+ );+ }+ },+ });++ const saved = await result.save();+ if (saved.size === 0) {+ throw new Error("Conversion produced an empty file");+ }+ return saved;+}++export function LoomDownloader() {+ const inputId = useId();+ const [url, setUrl] = useState("");+ const [status, setStatus] = useState<Status>("idle");+ const [errorMessage, setErrorMessage] = useState("");+ const [convertProgress, setConvertProgress] = useState(0);+ const abortRef = useRef<AbortController | null>(null);++ const handleDownload = useCallback(async () => {+ if (!url.trim()) return;++ setStatus("fetching");+ setErrorMessage("");+ setConvertProgress(0);++ try {+ const result = await downloadLoomVideo(url.trim());++ if (!result.success || !result.videoId) {+ setStatus("error");+ setErrorMessage(result.error || "Something went wrong.");+ return;+ }++ const params = new URLSearchParams({ id: result.videoId });+ if (result.videoName) params.set("name", result.videoName);+ const proxyUrl = `/api/tools/loom-download?${params.toString()}`;++ setStatus("downloading");++ const controller = new AbortController();+ abortRef.current = controller;++ const response = await fetch(proxyUrl, {+ signal: controller.signal,+ });++ if (!response.ok) {+ setStatus("error");+ setErrorMessage("Failed to download the video. Please try again.");+ return;+ }++ const contentType = response.headers.get("Content-Type") ?? "video/mp4";+ const blob = await response.blob();++ const sanitizedName = result.videoName+ ? result.videoName.replace(/[^a-zA-Z0-9\s-]/g, "").trim()+ : `loom-video-${Date.now()}`;++ if (needsConversion(contentType)) {+ setStatus("converting");+ setConvertProgress(0);++ try {+ const mp4Blob = await convertBlobToMp4(+ blob,+ contentType,+ setConvertProgress,+ );+ triggerBlobDownload(mp4Blob, `${sanitizedName}.mp4`);+ } catch {+ const fallbackExt = contentType.includes("webm") ? "webm" : "ts";+ triggerBlobDownload(blob, `${sanitizedName}.${fallbackExt}`);+ }+ } else {+ triggerBlobDownload(blob, `${sanitizedName}.mp4`);+ }++ setStatus("idle");+ } catch (err) {+ if (err instanceof DOMException && err.name === "AbortError") {+ setStatus("idle");+ return;+ }+ setStatus("error");+ setErrorMessage("An unexpected error occurred. Please try again.");+ } finally {+ abortRef.current = null;+ }+ }, [url]);++ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {+ if (e.key === "Enter") {+ handleDownload();+ }+ };++ const isLoading =+ status === "fetching" ||+ status === "downloading" ||+ status === "converting";+ const isValidLoomUrl = url.trim().length > 0 && url.includes("loom.com");++ const buttonLabel =+ status === "fetching"+ ? "Fetching..."+ : status === "downloading"+ ? "Downloading..."+ : status === "converting"+ ? `Converting to MP4... ${convertProgress}%`+ : "Download Video";++ return (+ <div className="flex flex-col gap-5">+ <div className="flex flex-col gap-2 sm:gap-3">+ <label htmlFor={inputId} className="text-sm font-medium text-gray-700">+ Loom Video URL+ </label>+ <div className="flex flex-col gap-2 sm:flex-row sm:gap-3">+ <input+ id={inputId}+ type="url"+ value={url}+ onChange={(e) => {+ setUrl(e.target.value);+ if (status === "error") {+ setStatus("idle");+ setErrorMessage("");+ }+ }}+ onKeyDown={handleKeyDown}+ placeholder="https://www.loom.com/share/..."+ className="w-full sm:flex-1 px-3 sm:px-4 h-[48px] sm:h-[44px] text-[16px] sm:text-[14px] text-gray-12 bg-gray-1 border border-gray-4 rounded-xl outline-0 transition-all duration-200 hover:bg-gray-2 hover:border-gray-5 focus:bg-gray-2 focus:border-gray-5 focus:ring-1 focus:ring-gray-12 focus:ring-offset-2 ring-offset-gray-3 placeholder:text-gray-8"+ disabled={isLoading}+ />+ <Button+ onClick={handleDownload}+ disabled={!isValidLoomUrl || isLoading}+ variant="primary"+ size="md"+ spinner={isLoading}+ className="w-full h-[48px] sm:h-auto sm:w-auto"+ >+ {buttonLabel}+ </Button>+ </div>+ </div>++ {status === "converting" && (+ <div className="flex flex-col gap-2">+ <div className="w-full bg-gray-3 rounded-full h-2 overflow-hidden">+ <div+ className="bg-blue-9 h-2 rounded-full transition-all duration-300 ease-out"+ style={{ width: `${convertProgress}%` }}+ />+ </div>+ <p className="text-xs text-gray-500 text-center">+ Converting video to MP4 in your browser...+ </p>+ </div>+ )}++ {status === "error" && errorMessage && (+ <div className="flex items-start gap-2 p-3 text-sm text-red-700 bg-red-50 border border-red-200 rounded-xl">+ <svg+ className="w-5 h-5 flex-shrink-0 mt-0.5"+ fill="none"+ viewBox="0 0 24 24"+ stroke="currentColor"+ strokeWidth={1.5}+ role="img"+ >+ <title>Error</title>+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"+ />+ </svg>+ <span>{errorMessage}</span>+ </div>+ )}++ <div className="flex items-start gap-2 text-xs text-gray-500 sm:items-center">+ <svg+ className="w-4 h-4 flex-shrink-0 mt-0.5 sm:mt-0"+ fill="none"+ viewBox="0 0 24 24"+ stroke="currentColor"+ strokeWidth={1.5}+ role="img"+ >+ <title>Privacy</title>+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ d="M9 12.75L11.25 15 15 9.75m-3-7.036A11.959 11.959 0 013.598 6 11.99 11.99 0 003 9.749c0 5.592 3.824 10.29 9 11.623 5.176-1.332 9-6.03 9-11.622 0-1.31-.21-2.571-.598-3.751h-.152c-3.196 0-6.1-1.248-8.25-3.285z"+ />+ </svg>+ Paste any public Loom video link. We fetch the download URL server-side+ — your video is never stored on our servers.+ </div>+ </div>+ );+}diff --git a/apps/web/components/tools/ToolsPageTemplate.tsx b/apps/web/components/tools/ToolsPageTemplate.tsxindex 1c06bda22..72e96209a 100644--- a/apps/web/components/tools/ToolsPageTemplate.tsx+++ b/apps/web/components/tools/ToolsPageTemplate.tsx@@ -117,10 +117,8 @@ export const ToolsPageTemplate = ({return (<>- {/* Compact Hero Section */}- <div className="overflow-hidden relative py-32 md:py-40">- {/* Breadcrumbs */}- <div className="relative z-20 px-5 pt-4 text-center wrapper">+ <div className="overflow-hidden relative pt-24 pb-8 md:py-40">+ <div className="relative z-20 px-4 pt-4 text-center wrapper sm:px-5"><div className="flex justify-center items-center text-sm"><LinkclassName="text-sm font-semibold text-gray-500 hover:underline"@@ -133,36 +131,34 @@ export const ToolsPageTemplate = ({</div></div>- <div className="relative z-10 px-5 pt-8 pb-6 w-full md:pt-12 md:pb-8">+ <div className="relative z-10 px-4 pt-6 pb-4 w-full sm:px-5 md:pt-12 md:pb-8"><div className="mx-auto max-w-3xl text-center wrapper wrapper-sm">- <h1 className="fade-in-down text-[2rem] leading-[2.5rem] md:text-[2.75rem] md:leading-[3.25rem] relative z-10 text-black mb-4">+ <h1 className="fade-in-down text-[1.75rem] leading-[2.25rem] sm:text-[2rem] sm:leading-[2.5rem] md:text-[2.75rem] md:leading-[3.25rem] relative z-10 text-black mb-3 md:mb-4">{content.title}</h1>- <p className="mx-auto mb-6 max-w-2xl text-md sm:text-lg text-zinc-600 fade-in-down animate-delay-1">+ <p className="mx-auto mb-4 max-w-2xl text-sm sm:text-md md:text-lg text-zinc-600 fade-in-down animate-delay-1 md:mb-6">{content.description}</p></div></div>- <div className="relative z-10 py-10 wrapper">- <div className="p-6 mx-auto max-w-4xl bg-white rounded-2xl border border-gray-100 shadow-lg md:p-8">+ <div className="relative z-10 py-4 wrapper md:py-10">+ <div className="p-4 mx-auto max-w-4xl bg-white rounded-2xl border border-gray-100 shadow-lg sm:p-6 md:p-8">{toolComponent}</div></div>- {/* Main Content - Features & FAQ */}- <div className="relative z-10 py-16 wrapper">- {/* Features Section */}- <div className="mb-20">- <div className="text-center max-w-[800px] mx-auto mb-12">- <h2 className="inline-block relative mb-5 text-3xl font-medium text-gray-800">+ <div className="relative z-10 py-10 wrapper md:py-16">+ <div className="mb-12 md:mb-20">+ <div className="text-center max-w-[800px] mx-auto mb-8 px-2 md:mb-12">+ <h2 className="inline-block relative mb-5 text-2xl font-medium text-gray-800 sm:text-3xl">{content.featuresTitle}<span className="absolute -bottom-2 left-1/2 w-16 h-1 bg-blue-500 rounded-full transform -translate-x-1/2"></span></h2>- <p className="text-lg leading-relaxed text-gray-600">+ <p className="text-base leading-relaxed text-gray-600 sm:text-lg">{renderHTML(content.featuresDescription)}</p></div>- <div className="grid grid-cols-1 gap-6 md:grid-cols-3">+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 sm:gap-6 md:grid-cols-3">{content.features.map((feature: { title: string; description: string },@@ -170,14 +166,14 @@ export const ToolsPageTemplate = ({) => (<divkey={index}- className="p-6 bg-white rounded-xl border border-gray-100 shadow-sm transition-all duration-300 hover:shadow-md hover:border-blue-100"+ className="p-5 bg-white rounded-xl border border-gray-100 shadow-sm transition-all duration-300 sm:p-6 hover:shadow-md hover:border-blue-100"><div className="flex justify-center items-center mb-4 w-10 h-10 bg-blue-50 rounded-full"><span className="text-lg font-medium text-blue-500">{index + 1}</span></div>- <h3 className="mb-3 text-lg font-semibold text-gray-800">+ <h3 className="mb-2 text-base font-semibold text-gray-800 sm:mb-3 sm:text-lg">{feature.title}</h3><p className="text-sm leading-relaxed text-gray-600 md:text-base">@@ -189,11 +185,10 @@ export const ToolsPageTemplate = ({</div></div>- {/* FAQ Section */}{content.faqs && (- <div className="mb-20">- <div className="text-center max-w-[800px] mx-auto mb-12">- <h2 className="inline-block relative mb-5 text-3xl font-medium text-gray-800">+ <div className="mb-12 md:mb-20">+ <div className="text-center max-w-[800px] mx-auto mb-8 px-2 md:mb-12">+ <h2 className="inline-block relative mb-5 text-2xl font-medium text-gray-800 sm:text-3xl">Frequently Asked Questions<span className="absolute -bottom-2 left-1/2 w-16 h-1 bg-blue-500 rounded-full transform -translate-x-1/2"></span></h2>@@ -206,9 +201,9 @@ export const ToolsPageTemplate = ({) => (<divkey={index}- className="p-5 my-4 bg-white rounded-xl border border-gray-100 shadow-sm transition-all duration-300 hover:shadow-md"+ className="p-4 my-3 bg-white rounded-xl border border-gray-100 shadow-sm transition-all duration-300 sm:p-5 sm:my-4 hover:shadow-md">- <h2 className="mb-2 text-lg font-semibold text-gray-800">+ <h2 className="mb-2 text-base font-semibold text-gray-800 sm:text-lg">{faq.question}</h2><div className="text-sm leading-relaxed text-gray-600 md:text-base">@@ -221,9 +216,8 @@ export const ToolsPageTemplate = ({</div>)}- {/* Clean CTA Section */}<div- className="max-w-[900px] mx-auto rounded-2xl bg-white overflow-hidden relative flex flex-col justify-center p-8 md:p-10"+ className="max-w-[900px] mx-auto rounded-2xl bg-white overflow-hidden relative flex flex-col justify-center p-5 sm:p-8 md:p-10"style={{backgroundImage: "url('/illustrations/ctabg.svg')",backgroundSize: "cover",@@ -231,11 +225,11 @@ export const ToolsPageTemplate = ({}}><div className="flex relative z-10 flex-col justify-center items-center mx-auto h-full wrapper">- <div className="text-center max-w-[700px] mx-auto mb-6">- <h2 className="mb-3 text-2xl font-medium md:text-3xl text-gray-12">+ <div className="text-center max-w-[700px] mx-auto mb-5 md:mb-6">+ <h2 className="mb-3 text-xl font-medium sm:text-2xl md:text-3xl text-gray-12">{content.cta.title}</h2>- <p className="mb-5 text-lg text-gray-10">+ <p className="mb-4 text-base text-gray-10 sm:text-lg md:mb-5">{content.cta.description}</p></div>@@ -254,8 +248,6 @@ export const ToolsPageTemplate = ({</div></div>- {/* Tool Container - Now positioned for visibility above the fold */}-<style jsx global>{`@keyframes fade-in-down {0% {