did some reformatting
This commit is contained in:
parent
cdfbadb805
commit
dff64b31a4
@ -8,37 +8,52 @@ import { UUID, randomUUID } from "crypto";
|
|||||||
import { mkdir, mkdirSync, writeFile } from "fs";
|
import { mkdir, mkdirSync, writeFile } from "fs";
|
||||||
import { where } from "@sequelize/core";
|
import { where } from "@sequelize/core";
|
||||||
|
|
||||||
async function writeFilesToBucket(uuid: UUID, files:any[]) {
|
|
||||||
const fileArray:{name:string, content:Promise<ReadableStreamReadResult<Uint8Array>>|ReadableStreamReadResult<Uint8Array>}[] = await Promise.all( files.map((file:File) => {
|
async function writeFilesToBucket(uuid: UUID, files: any[]) {
|
||||||
return {'name':( ()=>file.name)(), 'content':file.stream().getReader().read()};
|
|
||||||
|
type FileArrayEntry = {
|
||||||
|
name:string;
|
||||||
|
content: Promise<ReadableStreamReadResult<Uint8Array>> | ReadableStreamReadResult<Uint8Array>
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileArray:FileArrayEntry[] = 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 () => {
|
let finalFileArray: { name: string, content: ReadableStreamReadResult<Uint8Array> }[] = await (async () => {
|
||||||
for(let file in fileArray){
|
for (let file in fileArray) {
|
||||||
fileArray[file].content = await fileArray[file].content
|
fileArray[file].content = await fileArray[file].content
|
||||||
}
|
}
|
||||||
return [...fileArray as {name:string,content:ReadableStreamReadResult<Uint8Array>}[]]
|
return [...fileArray as { name: string, content: ReadableStreamReadResult<Uint8Array> }[]]
|
||||||
})() ;
|
})();
|
||||||
|
|
||||||
mkdirSync(`./bucket/${uuid}/`)
|
mkdirSync(`./bucket/${uuid}/`)
|
||||||
for(let file in finalFileArray){
|
for (let file in finalFileArray) {
|
||||||
writeFile(`./bucket/${uuid}/${finalFileArray[file].name}`,Buffer.from(finalFileArray[file].content.value as Uint8Array),(e)=>{console.log(e)})
|
writeFile(
|
||||||
const attachment = await Attachment.create({bucket_id:uuid, filename:finalFileArray[file].name}, {include: Attachment.associations.bucket});
|
`./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);
|
console.log(attachment);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function addToPost(postid:number):Promise<Bucket>
|
async function addToPost(postid: number): Promise<Bucket> {
|
||||||
{
|
|
||||||
Post.sync();
|
Post.sync();
|
||||||
const post = await Post.findOne({where: {id:postid}});
|
const post = await Post.findOne({ where: { id: postid } });
|
||||||
|
|
||||||
if (!post) throw new APIError({ status: 500, responseText: "invalid postid" });
|
if (!post) throw new APIError({ status: 500, responseText: "invalid postid" });
|
||||||
const bucket = await post.createBucket({id:randomUUID()});
|
const bucket = await post.createBucket({ id: randomUUID() });
|
||||||
return bucket;
|
return bucket;
|
||||||
}
|
}
|
||||||
async function addToBucket(bucketid:number):Promise<Bucket> {
|
async function addToBucket(bucketid: number): Promise<Bucket> {
|
||||||
const bucket = await Bucket.findOne({where: {id: bucketid}, include: {association: Bucket.associations.posts}});
|
const bucket = await Bucket.findOne({
|
||||||
|
where: { id: bucketid }, include: { association: Bucket.associations.posts }
|
||||||
|
});
|
||||||
if (!bucket) throw new APIError({ status: 500, responseText: "invalid bucketid" });
|
if (!bucket) throw new APIError({ status: 500, responseText: "invalid bucketid" });
|
||||||
return bucket;
|
return bucket;
|
||||||
}
|
}
|
||||||
@ -48,76 +63,77 @@ async function tryCreateAttachment(request: Request) {
|
|||||||
|
|
||||||
// Make sure the DB is ready
|
// Make sure the DB is ready
|
||||||
await dbSync;
|
await dbSync;
|
||||||
|
|
||||||
// Prepare data
|
// Prepare data
|
||||||
const formData = await request.formData();
|
const formData = await request.formData();
|
||||||
const requestData:string | Object | undefined = formData.get('data')?.valueOf();
|
const requestData: string | Object | undefined = formData.get('data')?.valueOf();
|
||||||
const files:FormDataEntryValue[] = formData.getAll('files')
|
const files: FormDataEntryValue[] = formData.getAll('files')
|
||||||
const authCkie = await cookies().get("auth");
|
const authCkie = await cookies().get("auth");
|
||||||
|
|
||||||
// Sanity check auth cookie
|
// Sanity check auth cookie
|
||||||
if ( !authCkie || !authCkie.value) throw new APIError({ status: 500, responseText: "missing auth cookie" });
|
if (!authCkie || !authCkie.value) throw new APIError({ status: 500, responseText: "missing auth cookie" });
|
||||||
|
|
||||||
// Get JSON from the Cookie
|
// Get JSON from the Cookie
|
||||||
const cookieJSON = authCkie.value;
|
const cookieJSON = authCkie.value;
|
||||||
const authObject = JSON.parse(cookieJSON);
|
const authObject = JSON.parse(cookieJSON);
|
||||||
|
|
||||||
// Fetch User Auth from the database
|
// Fetch User Auth from the database
|
||||||
const auth = await Auth.findOne({
|
const auth = await Auth.findOne({
|
||||||
include: [
|
include: [
|
||||||
{
|
{
|
||||||
model: User.withScope(['withPerms']),
|
model: User.withScope(['withPerms']),
|
||||||
attributes: {
|
attributes: {
|
||||||
exclude: ['username', 'password', 'updatedAt', 'createdAt']
|
exclude: ['username', 'password', 'updatedAt', 'createdAt']
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
where: { token: authObject.token }
|
where: { token: authObject.token }
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
// Sanity check the auth and associated user for authorization
|
// Sanity check the auth and associated user for authorization
|
||||||
if (!auth || !auth.user) throw new APIError({ status: 401, responseText: "Authentication Error" });
|
if (!auth || !auth.user) throw new APIError({ status: 401, responseText: "Authentication Error" });
|
||||||
if (!auth.user.id) throw new APIError({ status: 500, responseText: "Missing user id" });
|
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)}` });
|
if (!auth.user.perms || !auth.user.perms.isAdmin)
|
||||||
|
throw new APIError({ status: 401, responseText: `Unauthorized ${JSON.stringify(auth.user)}` });
|
||||||
// Handle incomplete data or other problems
|
// Handle incomplete data or other problems
|
||||||
if (!files) throw new APIError({ status: 500, responseText: "Missing file" });
|
if (!files) throw new APIError({ status: 500, responseText: "Missing file" });
|
||||||
if (!formData) throw new APIError({ status: 500, responseText: "Empty request body" });
|
if (!formData) throw new APIError({ status: 500, responseText: "Empty request body" });
|
||||||
if (!requestData) throw new APIError({ status: 500, responseText: "Missing request data" });
|
if (!requestData) throw new APIError({ status: 500, responseText: "Missing request data" });
|
||||||
if (!(typeof requestData == "string")) throw new APIError({ status: 500, responseText: "Malformed request data" });
|
if (!(typeof requestData == "string")) throw new APIError({ status: 500, responseText: "Malformed request data" });
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const data = JSON.parse(requestData);
|
const data = JSON.parse(requestData);
|
||||||
|
|
||||||
let bucket:Bucket = (data.postid && !data.bucketid)? await addToPost(data.postid) : await addToBucket(data.bucketid)
|
let bucket:Bucket = (data.postid && !data.bucketid) ? await addToPost(data.postid) : await addToBucket(data.bucketid)
|
||||||
writeFilesToBucket(bucket.id, files);
|
writeFilesToBucket(bucket.id, files);
|
||||||
|
|
||||||
|
|
||||||
const bucket2 = await Bucket.findOne({where: {id: bucket.id}, include: [Bucket.associations.posts, Bucket.associations.attachments]})
|
const bucket2 = await Bucket.findOne({
|
||||||
|
where: { id: bucket.id },
|
||||||
|
include: [Bucket.associations.posts, Bucket.associations.attachments]
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
return new Response(JSON.stringify({
|
return new Response(JSON.stringify({
|
||||||
bucket: bucket2
|
bucket: bucket2
|
||||||
}), { status: 200 });
|
}), { status: 200 });
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export async function tryFetchAttachments(request: Request) {
|
export async function tryFetchAttachments(request: Request) {
|
||||||
|
|
||||||
await Post.sync();
|
await Post.sync();
|
||||||
|
|
||||||
const foundPosts = await Post.findAll({
|
const foundPosts = await Post.findAll({
|
||||||
include: [
|
include: [
|
||||||
{
|
{
|
||||||
association: Post.associations.user,
|
association: Post.associations.user,
|
||||||
attributes: { exclude: ['password', 'createdAt', 'updatedAt'] }
|
attributes: { exclude: ['password', 'createdAt', 'updatedAt'] }
|
||||||
},{
|
}, {
|
||||||
association: Post.associations.postTags
|
association: Post.associations.postTags
|
||||||
}]
|
}]
|
||||||
});
|
});
|
||||||
|
|
||||||
return new Response(JSON.stringify(foundPosts), { status: 200 });
|
return new Response(JSON.stringify(foundPosts), { status: 200 });
|
||||||
@ -125,8 +141,9 @@ export async function tryFetchAttachments(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function GET(request: Request) {
|
export async function GET(request: Request) {
|
||||||
return await attemptAPIAction(tryFetchAttachments,request);
|
return await attemptAPIAction(tryFetchAttachments, request);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
return await attemptAPIAction(tryCreateAttachment,request);
|
return await attemptAPIAction(tryCreateAttachment, request);
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user