Working state for attachments and buckets

This commit is contained in:
2024-06-12 18:08:08 +02:00
parent e84ce38604
commit c72ac5e67f
5 changed files with 156 additions and 56 deletions
+60 -33
View File
@@ -4,19 +4,65 @@ import { APIError, attemptAPIAction } from "@/util/api/error";
import { Auth, Post, PostTag, Tag, User } from "@/model/Models";
import { cookies } from "next/headers";
import { Attachment } from "@/model/Attachment";
import { randomUUID } from "crypto";
import { UUID, randomUUID } from "crypto";
import { mkdir, mkdirSync, writeFile } from "fs";
import { Bucket } from "@/model/Bucket";
import { where } from "@sequelize/core";
import { PostBucket } from "@/model/Post";
async function writeFilesToBucket(uuid: UUID, files:any[]) {
const fileArray:{name:string, content:Promise<ReadableStreamReadResult<Uint8Array>>|ReadableStreamReadResult<Uint8Array>}[] = await Promise.all( files.map((file:File) => {
return {'name':( ()=>file.name)(), 'content':file.stream().getReader().read()};
}));
let finalFileArray:{name:string,content:ReadableStreamReadResult<Uint8Array>}[] = await (async () => {
for(let file in fileArray){
fileArray[file].content = await fileArray[file].content
}
return [...fileArray as {name:string,content:ReadableStreamReadResult<Uint8Array>}[]]
})() ;
mkdirSync(`./bucket/${uuid}/`)
for(let file in finalFileArray){
writeFile(`./bucket/${uuid}/${finalFileArray[file].name}`,Buffer.from(finalFileArray[file].content.value as Uint8Array),(e)=>{console.log(e)})
const attachment = await Attachment.create({bucket_id:uuid, filename:finalFileArray[file].name}, {include: Attachment.associations.bucket});
console.log(attachment);
}
}
async function addToPost(postid:number):Promise<UUID>
{
const post = await Post.findOne({where: {id:postid}, include: {association: Post.associations.postBuckets}});
if (!post) throw new APIError({ status: 500, responseText: "invalid postid" });
const bucket = await Bucket.create({id:randomUUID()});
const bucketPost = await PostBucket.create({bucketId: bucket.id, postId: postid})
console.log(bucketPost);
return bucket.id
}
async function addToBucket(bucketid:number):Promise<UUID> {
const bucket = await Bucket.findOne({where: {id: bucketid}});
if (!bucket) throw new APIError({ status: 500, responseText: "invalid bucketid" });
return bucket.id
}
async function tryCreateAttachment(request: Request) {
// Make sure the DB is ready
await Attachment.sync();
await Bucket.sync();
await Post.sync();
// Prepare data
const formData = await request.formData();
const requestData:string | Object | undefined = formData.get('data')?.valueOf();
const files:FormDataEntryValue[] = formData.getAll('files')
const authCkie = await cookies().get("auth");
// Sanity check auth cookie
@@ -39,46 +85,27 @@ async function tryCreateAttachment(request: Request) {
where: { token: authObject.token }
});
// Sanity check the auth and associated user
// Sanity check the auth and associated user for authorization
if (!auth || !auth.user) throw new APIError({ status: 401, responseText: "Authentication Error" });
// Handle incomplete data or other problems
if (!formData) throw new APIError({ status: 500, responseText: "Empty request body" });
const files:any[] = formData.getAll('files')
if (!files) throw new APIError({ status: 500, responseText: "Missing file" });
if (!auth.user.id) throw new APIError({ status: 500, responseText: "Missing user id" });
if (!auth.user.perms || !auth.user.perms.isAdmin) throw new APIError({ status: 401, responseText: `Unauthorized ${JSON.stringify(auth.user)}` });
// peepee
const uuid = randomUUID()
const fileArray:{name:string, content:Promise<ReadableStreamReadResult<Uint8Array>>|ReadableStreamReadResult<Uint8Array>}[] = await Promise.all( files.map((file:File) => {
return {'name':( ()=>file.name)(), 'content':file.stream().getReader().read()};
}));
// Handle incomplete data or other problems
if (!files) throw new APIError({ status: 500, responseText: "Missing file" });
if (!formData) throw new APIError({ status: 500, responseText: "Empty request body" });
if (!requestData) throw new APIError({ status: 500, responseText: "Missing request data" });
if (!(typeof requestData == "string")) throw new APIError({ status: 500, responseText: "Malformed request data" });
let finalFileArray:{name:string,content:ReadableStreamReadResult<Uint8Array>}[] = await (async () => {
for(let file in fileArray){
fileArray[file].content = await fileArray[file].content
}
return [...fileArray as {name:string,content:ReadableStreamReadResult<Uint8Array>}[]]
})() ;
mkdirSync(`./bucket/${uuid}/`)
for(let file in finalFileArray){
writeFile(`./bucket/${uuid}/${finalFileArray[file].name}`,Buffer.from(finalFileArray[file].content.value as Uint8Array),(e)=>{console.log(e)})
}
// const kanker = files.map(parseFiles)
const data = JSON.parse(requestData);
let uuid:UUID = (data.postid && !data.bucketid)? await addToPost(data.postid) : await addToBucket(data.bucketid)
writeFilesToBucket(uuid, files);
// console.log(await kanker[0]);
return new Response(JSON.stringify({
'files': fileArray,
'files': 'ya yeet',
'uuid': uuid,
}), { status: 200 });