Skip to content

Commit

Permalink
feat: file transfer
Browse files Browse the repository at this point in the history
  • Loading branch information
sdjdd committed Mar 30, 2024
1 parent 4d66199 commit be2e3f7
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
19 changes: 18 additions & 1 deletion next/api/src/controller/file.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { z } from 'zod';
import axios from 'axios';
import { Context } from 'koa';

import {
Body,
Controller,
Ctx,
CurrentUser,
Get,
Param,
Expand All @@ -14,7 +19,6 @@ import { auth, staffOnly } from '@/middleware';
import { File } from '@/model/File';
import { User } from '@/model/User';
import { FileResponse } from '@/response/file';
import { z } from 'zod';

@Controller('files')
export class FileController {
Expand All @@ -35,6 +39,19 @@ export class FileController {
async findOne(@Param('id', new FindModelPipe(File, { useMasterKey: true })) file: File) {
return file;
}

@Get(':id/content')
@UseMiddlewares(auth, staffOnly)
async getFileContent(
@Ctx() ctx: Context,
@Param('id', new FindModelPipe(File, { useMasterKey: true })) file: File
) {
const res = await axios.get(file.url, {
responseType: 'stream',
});
ctx.set('Content-Type', res.headers['content-type']);
return res.data;
}
}

const getFileNameFromURL = (url: string) => decodeURI(url).split('/').pop();
Expand Down
9 changes: 8 additions & 1 deletion next/api/src/response/file.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import crypto from 'crypto';
import { File } from '@/model/File';
import { config } from '@/config';

const SIGNATURE_TTL = 3600;

Expand Down Expand Up @@ -49,6 +50,8 @@ const getThumbnailURL = (file: File) => {
return url;
};

const ENABLE_FILE_TRANSFER = process.env.ENABLE_FILE_TRANSFER;

export class FileResponse {
constructor(readonly file: File) {}

Expand All @@ -61,7 +64,11 @@ export class FileResponse {
name,
mime,
metaData,
url: needSignature ? sign(url) : url,
url: needSignature
? sign(url)
: ENABLE_FILE_TRANSFER
? `${config.host}/api/2/files/${id}/content`
: url,
thumbnailUrl: needSignature ? sign(thumbnailURL) : thumbnailURL,
};
}
Expand Down

0 comments on commit be2e3f7

Please sign in to comment.