Monorepo for Aesthetic.Computer aesthetic.computer
at main 65 lines 2.4 kB view raw
1// Media Collection, 23.05.02.01.11 2// Returns collections of user data from S3 given an open path. 3// Example: https://aesthetic.computer/media-collection?for={path} 4 5import { getHandleOrEmail, userIDFromHandleOrEmail } from "../../backend/authorization.mjs"; 6import { respond } from "../../backend/http.mjs"; 7import { connect } from "../../backend/database.mjs"; 8 9// GET `/media/{@userHandleOrEmail}` will list files. 10export async function handler(event, context) { 11 // Make sure this is a GET request 12 if (event.httpMethod !== "GET") 13 return respond(405, { error: "Wrong request type!" }); 14 15 const path = decodeURIComponent(event.queryStringParameters.for); 16 const splitPath = path.split("/"); // Chop up the path. 17 const sub = splitPath[0]; 18 const mediaType = splitPath[1]; 19 20 let files; 21 try { 22 const { db, disconnect } = await connect(); 23 24 // Convert handle/email to actual Auth0 sub for database query 25 const userSub = await userIDFromHandleOrEmail(sub, { db }); 26 27 // Get human readable id (handle or email) for the response URLs 28 const userId = await getHandleOrEmail(userSub); 29 30 console.log("📕 Media collection query:", path, splitPath, sub, "->", userSub, "->", userId); 31 32 // const mediaCollection = db.collection(`${mediaType}s`); 33 const mediaCollection = db.collection( 34 mediaType.endsWith("s") ? mediaType : `${mediaType}s`, 35 ); 36 37 // Query the media collection for the specific user. 38 // (Ignoring the `nuked` flag.) 39 const media = await mediaCollection 40 .find({ user: userSub, nuked: { $ne: true } }) 41 .toArray(); 42 43 // Only expect `painting` and `piece` for now. 23.10.12.22.32 44 const extension = mediaType === "painting" ? "png" : "mjs"; 45 46 // Determine the base URL from the request headers 47 const protocol = event.headers["x-forwarded-proto"] || "https"; 48 const host = event.headers.host || "aesthetic.computer"; 49 const baseUrl = `${protocol}://${host}`; 50 51 // Format the response 52 files = media.map((file) => { 53 return `${baseUrl}/media/${userId}/${mediaType}/${file.slug}.${extension}`; 54 }); 55 56 disconnect(); 57 } catch (err) { 58 console.log("Error", err); 59 return respond(500, { 60 error: "Failed to fetch media from the database 😩", 61 }); 62 } 63 64 return respond(200, { files }); // Return a list of all the files. 65}