feat: 添加头文件信息,添加图床工具。
This commit is contained in:
1 parent
f8fba79d55
commit
fda826a272
12 files changed
+515
-13
No files matched your search
@@ -1,5 +1,4 @@
|
||||
// @ts-ignore
|
||||
import testData from "~/public/testData/test.md"
|
||||
import DB from 'better-sqlite3';
|
||||
import { postItem } from "~/types/post";
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
// @ts-ignore
|
||||
import DB from 'better-sqlite3';
|
||||
import { defineEventHandler, getRouterParam } from 'h3';
|
||||
import fs from 'fs';
|
||||
import { sendStream } from 'h3';
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const hash = getRouterParam(event, 'hash');
|
||||
if (!hash) {
|
||||
return { code: 400, msg: 'Invalid hash parameter' };
|
||||
}
|
||||
const db = new DB('./userData/db/imgBed.db');
|
||||
// 从数据库中查询文件信息
|
||||
const fileInfo = db.prepare(`
|
||||
SELECT name, expire FROM imgBed WHERE hash =?
|
||||
`).get(hash) as { name: string, expire: number };
|
||||
db.close();
|
||||
|
||||
if (!fileInfo) {
|
||||
return { code: 404, msg: 'File not found' };
|
||||
}
|
||||
|
||||
const fileName = fileInfo.name;
|
||||
const filePath = `./userData/imgBed/${hash}`;
|
||||
// 检查文件是否存在
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return { code: 404, msg: 'File not found on disk' };
|
||||
}
|
||||
const fileStream = fs.createReadStream(filePath);
|
||||
|
||||
setResponseHeader(event, 'Content-Disposition', `attachment; filename="${fileName}"`);
|
||||
// 发送文件流
|
||||
return sendStream(event, fileStream);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return { code: 500, msg: 'Internal Server Error' };
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
// @ts-ignore
|
||||
import DB from 'better-sqlite3';
|
||||
import { defineEventHandler, readBody } from 'h3';
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const data = await readFormData(event)
|
||||
const file = data.get('file') as File
|
||||
const expire = data.get('expire') as string
|
||||
console.log({
|
||||
file: file.name,
|
||||
expire,
|
||||
})
|
||||
const fileBuffer = Buffer.from(await file.arrayBuffer());
|
||||
// 计算文件的 MD5 哈希值
|
||||
const hash = crypto.createHash('md5').update(fileBuffer).digest('hex');
|
||||
const fileName = file.name;
|
||||
const filePath = `./userData/imgBed/${hash}`;
|
||||
// 将文件写入磁盘
|
||||
await fs.promises.writeFile(filePath, fileBuffer);
|
||||
// 获取文件大小
|
||||
const fileSize = fileBuffer.length;
|
||||
|
||||
const db = new DB('./userData/db/imgBed.db');
|
||||
// 插入数据到数据库
|
||||
db.prepare(`
|
||||
INSERT INTO imgBed (name, hash, size, expire)
|
||||
VALUES (?,?,?,?)
|
||||
`).run([fileName, hash, fileSize, expire]);
|
||||
db.close();
|
||||
|
||||
return { code: 200, hash, fileName, fileSize, expire: Number(expire) + Date.now() };
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return { code: 500, msg: 'Internal Server Error' };
|
||||
}
|
||||
});
|
||||
@@ -7,12 +7,10 @@ const pathNeedAuth = serverConfig.auth.api
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const path = getRequestURL(event).pathname
|
||||
// console.log(path)
|
||||
if (pathNeedAuth.has(path)) {
|
||||
const key = getKey()
|
||||
// @ts-ignore
|
||||
const authHeader = event.headers.get('authorization');
|
||||
// console.log(authHeader)
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
throw createError({ statusCode: 401, statusMessage: 'Unauthorized' })
|
||||
}
|
||||
@@ -20,7 +18,6 @@ export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const decoded = jwt.verify(token, key) as { userId: number, password: string, username: string, exp: number }
|
||||
if (decoded.exp > Date.now()) {
|
||||
// console.log('token expired')
|
||||
throw createError({ statusCode: 401, statusMessage: 'Token invalid or expired', data: { err: 'token expired', token } })
|
||||
}
|
||||
// console.log(decoded)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import mkfileIfNotExist from "./mkfileIfNotExist"
|
||||
import db from 'better-sqlite3'
|
||||
import DB from 'better-sqlite3'
|
||||
import fs from 'fs'
|
||||
|
||||
let checked = false
|
||||
|
||||
@@ -14,6 +15,7 @@ function checkUserData() {
|
||||
const dirList = [
|
||||
'./userData/',
|
||||
'./userData/db/',
|
||||
'./userData/imgBed/',
|
||||
]
|
||||
dirList.forEach(mkdirIfNotExist)
|
||||
|
||||
@@ -24,9 +26,14 @@ function checkUserData() {
|
||||
}
|
||||
|
||||
function createDB() {
|
||||
const userDB = new db('./userData/db/user.db');
|
||||
const postsDB = new db('./userData/db/posts.db');
|
||||
createUserDB();
|
||||
createPostsDB();
|
||||
createImgBedDB();
|
||||
}
|
||||
|
||||
|
||||
const createUserDB = () => {
|
||||
const userDB = new DB('./userData/db/user.db');
|
||||
userDB.exec(`
|
||||
CREATE TABLE IF NOT EXISTS user (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
@@ -36,7 +43,11 @@ function createDB() {
|
||||
lastLoginTime INTEGER NOT NULL
|
||||
);
|
||||
`);
|
||||
userDB.close();
|
||||
}
|
||||
|
||||
const createPostsDB = () => {
|
||||
const postsDB = new DB('./userData/db/posts.db');
|
||||
postsDB.exec(`
|
||||
CREATE TABLE IF NOT EXISTS posts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
@@ -49,14 +60,12 @@ function createDB() {
|
||||
FOREIGN KEY(tag_id) REFERENCES tags(id)
|
||||
);
|
||||
`);
|
||||
|
||||
postsDB.exec(`
|
||||
CREATE TABLE IF NOT EXISTS postContent (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
content TEXT NOT NULL
|
||||
);
|
||||
`);
|
||||
|
||||
postsDB.exec(`
|
||||
CREATE TABLE IF NOT EXISTS tags (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
@@ -77,9 +86,56 @@ function createDB() {
|
||||
tag15 TEXT
|
||||
);
|
||||
`);
|
||||
|
||||
postsDB.close();
|
||||
userDB.close();
|
||||
}
|
||||
|
||||
const createImgBedDB = () => {
|
||||
const imgBedDB = new DB('./userData/db/imgBed.db');
|
||||
imgBedDB.exec(`
|
||||
CREATE TABLE IF NOT EXISTS imgBed (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
hash TEXT NOT NULL,
|
||||
size INTEGER NOT NULL,
|
||||
expire INTEGER NOT NULL
|
||||
);
|
||||
`);
|
||||
imgBedDB.close();
|
||||
setInterval(cleanExpiredFiles_imgBed, 1000 * 30 * 60 );
|
||||
// cleanExpiredFiles_imgBed()
|
||||
}
|
||||
|
||||
const cleanExpiredFiles_imgBed = async () => {
|
||||
try {
|
||||
const db = new DB('./userData/db/imgBed.db');
|
||||
const currentTime = Date.now();
|
||||
// 从数据库中查询过期文件的哈希
|
||||
const expiredFiles = db.prepare(`
|
||||
SELECT hash FROM imgBed WHERE expire <?
|
||||
`).all(currentTime) as {
|
||||
hash: string;
|
||||
}[];
|
||||
db.close();
|
||||
|
||||
for (const file of expiredFiles) {
|
||||
const hash = file.hash;
|
||||
const filePath = useRuntimeConfig().public.userDataPath + `/imgBed/${hash}`;
|
||||
// 检查文件是否存在
|
||||
if (fs.existsSync(filePath)) {
|
||||
// 删除文件
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
// 从数据库中删除过期文件的记录
|
||||
const db2 = new DB('./userData/db/imgBed.db');
|
||||
db2.prepare(`
|
||||
DELETE FROM imgBed WHERE expire <?
|
||||
`).run(currentTime);
|
||||
db2.close();
|
||||
} catch (error) {
|
||||
console.error('Error cleaning expired files:', error);
|
||||
}
|
||||
};
|
||||
|
||||
export default checkUserData
|
||||
Reference in new issue
Block a user