|
| 1 | +import { db } from "@cap/database"; |
| 2 | +import { getCurrentUser } from "@cap/database/auth/session"; |
| 3 | +import { s3Buckets, videos } from "@cap/database/schema"; |
| 4 | +import { buildEnv, serverEnv } from "@cap/env"; |
| 5 | +import { S3_BUCKET_URL } from "@cap/utils"; |
| 6 | +import { eq } from "drizzle-orm"; |
| 7 | +import { createBucketProvider } from "@/utils/s3"; |
| 8 | + |
| 9 | +export async function getScreenshot(userId: string, screenshotId: string) { |
| 10 | + if (!userId || !screenshotId) { |
| 11 | + throw new Error("userId or screenshotId not supplied"); |
| 12 | + } |
| 13 | + |
| 14 | + const query = await db() |
| 15 | + .select({ video: videos, bucket: s3Buckets }) |
| 16 | + .from(videos) |
| 17 | + .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id)) |
| 18 | + .where(eq(videos.id, screenshotId)); |
| 19 | + |
| 20 | + if (query.length === 0) { |
| 21 | + throw new Error("Video does not exist"); |
| 22 | + } |
| 23 | + |
| 24 | + const result = query[0]; |
| 25 | + if (!result?.video) { |
| 26 | + throw new Error("Video not found"); |
| 27 | + } |
| 28 | + |
| 29 | + const { video, bucket } = result; |
| 30 | + |
| 31 | + if (video.public === false) { |
| 32 | + const user = await getCurrentUser(); |
| 33 | + |
| 34 | + if (!user || user.id !== video.ownerId) { |
| 35 | + throw new Error("Video is not public"); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + const bucketProvider = await createBucketProvider(bucket); |
| 40 | + const screenshotPrefix = `${userId}/${screenshotId}/`; |
| 41 | + |
| 42 | + try { |
| 43 | + const objects = await bucketProvider.listObjects({ |
| 44 | + prefix: screenshotPrefix, |
| 45 | + }); |
| 46 | + |
| 47 | + const screenshot = objects.Contents?.find((object) => |
| 48 | + object.Key?.endsWith(".png"), |
| 49 | + ); |
| 50 | + |
| 51 | + if (!screenshot) { |
| 52 | + throw new Error("Screenshot not found"); |
| 53 | + } |
| 54 | + |
| 55 | + let screenshotUrl: string; |
| 56 | + |
| 57 | + if (video.awsBucket !== serverEnv().CAP_AWS_BUCKET) { |
| 58 | + screenshotUrl = await bucketProvider.getSignedObjectUrl(screenshot.Key!); |
| 59 | + } else { |
| 60 | + screenshotUrl = `${S3_BUCKET_URL}/${screenshot.Key}`; |
| 61 | + } |
| 62 | + |
| 63 | + return { url: screenshotUrl }; |
| 64 | + } catch (error) { |
| 65 | + throw new Error(`Error generating screenshot URL: ${error}`); |
| 66 | + } |
| 67 | +} |
0 commit comments