109 lines
2.8 KiB
TypeScript
109 lines
2.8 KiB
TypeScript
import { app, db, schema } from '@/app.ts';
|
||
import { oss } from '@/app.ts';
|
||
import { User } from '@/models/user.ts';
|
||
import { customAlphabet } from 'nanoid';
|
||
import dayjs from 'dayjs';
|
||
|
||
const letter = 'abcdefghijklmnopqrstuvwxyz';
|
||
const number = '0123456789';
|
||
const randomId = customAlphabet(letter + number, 16);
|
||
const getShareUser = async () => {
|
||
const shareUser = await User.findOne({
|
||
username: 'share',
|
||
});
|
||
return shareUser?.id || '';
|
||
};
|
||
app
|
||
.route({
|
||
path: 'app',
|
||
key: 'public-upload-html',
|
||
middleware: ['auth-can'],
|
||
})
|
||
.define(async (ctx) => {
|
||
const tokenUser = ctx.state.tokenUser || {};
|
||
|
||
let uid = tokenUser?.id;
|
||
let username = tokenUser?.username;
|
||
if (!uid) {
|
||
uid = await getShareUser();
|
||
username = 'share';
|
||
}
|
||
if (!uid) {
|
||
ctx.throw(403, 'No permission to upload');
|
||
}
|
||
let { title, description, version = '1.0.0', key, content } = ctx.query.data || {};
|
||
if (!content) {
|
||
ctx.throw(400, 'Content is required');
|
||
}
|
||
if (!key) {
|
||
key = randomId(16);
|
||
}
|
||
if (!title) {
|
||
const day = dayjs().format('YYYY-MM-DD HH:mm');
|
||
const time = dayjs().format('YYYY-MM-DD HH:mm:ss');
|
||
title = `分享应用 - ${day}`;
|
||
|
||
description = `创建于 ${time},分享应用,key: ${key},用户: ${username}`;
|
||
if (!tokenUser) {
|
||
description = description + `,会自动删除,过期时间为30天`;
|
||
}
|
||
}
|
||
const urlPath = `${username}/${key}/${version}/index.html`;
|
||
await oss.putObject(urlPath, content, {
|
||
'Content-Type': 'text/html; charset=utf-8',
|
||
'app-source': 'user-app',
|
||
'Cache-Control': 'no-cache',
|
||
});
|
||
const files = [
|
||
{
|
||
name: 'index.html',
|
||
path: urlPath,
|
||
},
|
||
];
|
||
const appModels = await db.insert(schema.kvApp).values({
|
||
title,
|
||
description,
|
||
version,
|
||
key,
|
||
user: username,
|
||
uid,
|
||
proxy: true,
|
||
data: {
|
||
delete: 'share',
|
||
permission: {
|
||
share: 'public',
|
||
},
|
||
files: files,
|
||
},
|
||
}).returning();
|
||
const appModel = appModels[0];
|
||
const appVersionModels = await db.insert(schema.kvAppList).values({
|
||
data: {
|
||
files: files,
|
||
},
|
||
version: appModel.version,
|
||
key: appModel.key,
|
||
uid: appModel.uid,
|
||
}).returning();
|
||
const appVersionModel = appVersionModels[0];
|
||
|
||
ctx.body = {
|
||
url: `/${username}/${key}/`,
|
||
username: username,
|
||
appModel: {
|
||
id: appModel.id,
|
||
title: appModel.title,
|
||
description: appModel.description,
|
||
version: appModel.version,
|
||
data: appModel.data,
|
||
},
|
||
appVersionModel: {
|
||
id: appVersionModel.id,
|
||
version: appVersionModel.version,
|
||
key: appVersionModel.key,
|
||
data: appVersionModel.data,
|
||
},
|
||
};
|
||
})
|
||
.addTo(app);
|