monofile/src/index.ts

149 lines
4.9 KiB
TypeScript
Raw Normal View History

/*
i really should split this up into different modules
*/
2022-09-26 22:09:38 -07:00
import bodyParser from "body-parser"
2022-09-27 16:39:25 -07:00
import multer, {memoryStorage} from "multer"
2022-12-29 13:03:33 -08:00
import Discord, { IntentsBitField, Client } from "discord.js"
2022-09-26 22:09:38 -07:00
import express from "express"
import fs from "fs"
2022-12-26 20:59:16 -08:00
import axios, { AxiosResponse } from "axios"
2022-09-26 22:09:38 -07:00
2023-01-20 13:23:45 -08:00
import Files from "./lib/files"
2022-09-26 22:09:38 -07:00
require('dotenv').config()
2023-01-20 13:23:45 -08:00
2022-12-27 11:52:11 -08:00
let pkg = require(`${process.cwd()}/package.json`)
2022-09-26 22:09:38 -07:00
let app = express()
2022-09-27 16:39:25 -07:00
const multerSetup = multer({storage:memoryStorage()})
let config = require(`${process.cwd()}/config.json`)
app.use("/static",express.static("assets"))
2022-12-26 20:59:16 -08:00
app.use(bodyParser.text({limit:(config.maxDiscordFileSize*config.maxDiscordFiles)+1048576,type:["application/json","text/plain"]}))
2023-01-26 16:33:41 -08:00
//let files:{[key:string]:{filename:string,mime:string,messageids:string[]}} = {}
2022-09-26 22:09:38 -07:00
// funcs
function ThrowError(response:express.Response,code:number,errorMessage:string) {
fs.readFile(__dirname+"/../pages/error.html",(err,buf) => {
if (err) {response.sendStatus(500);console.log(err);return}
response.status(code)
2022-12-27 11:52:11 -08:00
response.send(buf.toString().replace(/\$ErrorCode/g,code.toString()).replace(/\$ErrorMessage/g,errorMessage).replace(/\$Version/g,pkg.version))
2022-09-26 22:09:38 -07:00
})
}
// init data
if (!fs.existsSync(__dirname+"/../.data/")) fs.mkdirSync(__dirname+"/../.data/")
2023-01-26 16:33:41 -08:00
2022-09-26 22:09:38 -07:00
// discord
let client = new Client({intents:[
2022-12-29 13:03:33 -08:00
IntentsBitField.Flags.GuildMessages,
IntentsBitField.Flags.MessageContent
],rest:{timeout:config.requestTimeout}})
2022-09-26 22:09:38 -07:00
2023-01-26 16:33:41 -08:00
let files = new Files(client,config)
2022-09-26 22:09:38 -07:00
2022-12-26 20:28:33 -08:00
app.get("/", function(req,res) {
fs.readFile(__dirname+"/../pages/base.html",(err,buf) => {
2022-12-26 20:28:33 -08:00
if (err) {res.sendStatus(500);console.log(err);return}
res.send(
buf.toString()
.replace("$MaxInstanceFilesize",`${(config.maxDiscordFileSize*config.maxDiscordFiles)/1048576}MB`)
.replace(/\$Version/g,pkg.version)
.replace(/\$Handler/g,"upload_file")
.replace(/\$UploadButtonText/g,"Upload file")
.replace(/\$otherPath/g,"/clone")
.replace(/\$otherText/g,"clone from url...")
2022-12-31 20:06:09 -08:00
.replace(/\$FileNum/g,Object.keys(files).length.toString())
)
2022-12-26 20:28:33 -08:00
})
})
2022-12-26 21:13:55 -08:00
app.get("/clone", function(req,res) {
fs.readFile(__dirname+"/../pages/base.html",(err,buf) => {
2022-12-26 21:13:55 -08:00
if (err) {res.sendStatus(500);console.log(err);return}
res.send(
buf.toString()
.replace("$MaxInstanceFilesize",`${(config.maxDiscordFileSize*config.maxDiscordFiles)/1048576}MB`)
.replace(/\$Version/g,pkg.version)
.replace(/\$Handler/g,"clone_file")
.replace(/\$UploadButtonText/g,"Input a URL")
.replace(/\$otherPath/g,"/")
.replace(/\$otherText/g,"upload file...")
2022-12-31 20:06:09 -08:00
.replace(/\$FileNum/g,Object.keys(files).length.toString())
)
2022-12-26 21:13:55 -08:00
})
})
2022-12-26 20:28:33 -08:00
app.post("/upload",multerSetup.single('file'),async (req,res) => {
if (req.file) {
try {
2023-01-26 16:33:41 -08:00
files.uploadFile({name:req.file.originalname,mime:req.file.mimetype,uploadId:req.header("monofile-upload-id")},req.file.buffer)
.then((uID) => res.send(uID))
.catch((stat) => {res.status(stat.status);res.send(`[err] ${stat.message}`)})
} catch {
res.status(400)
res.send("[err] bad request")
}
2022-09-27 16:10:23 -07:00
} else {
res.status(400)
res.send("[err] bad request")
}
2022-09-26 22:09:38 -07:00
})
2022-12-26 20:28:33 -08:00
app.post("/clone",(req,res) => {
try {
let j = JSON.parse(req.body)
if (!j.url) {
res.status(400)
res.send("[err] invalid url")
}
axios.get(j.url,{responseType:"arraybuffer"}).then((data:AxiosResponse) => {
uploadFile({name:req.body.split("/")[req.body.split("/").length-1] || "generic",mime:data.headers["content-type"],uploadId:j.uploadId},Buffer.from(data.data))
.then((uID) => res.send(uID))
.catch((stat) => {res.status(stat.status);res.send(`[err] ${stat.message}`)})
}).catch((err) => {
res.status(400)
res.send(`[err] failed to fetch data`)
})
} catch {
res.status(500)
res.send("[err] an error occured")
}
2022-12-26 20:28:33 -08:00
})
2022-09-26 22:09:38 -07:00
app.get("/download/:fileId",(req,res) => {
if (files[req.params.fileId]) {
let file = files[req.params.fileId]
fs.readFile(__dirname+"/../pages/download.html",(err,buf) => {
if (err) {res.sendStatus(500);console.log(err);return}
2022-12-27 11:52:11 -08:00
res.send(buf.toString().replace(/\$FileName/g,file.filename).replace(/\$FileId/g,req.params.fileId).replace(/\$Version/g,pkg.version))
2022-09-26 22:09:38 -07:00
})
} else {
ThrowError(res,404,"File not found.")
2022-09-26 22:09:38 -07:00
}
})
app.get("/file/:fileId",async (req,res) => {
2023-01-26 16:33:41 -08:00
2022-09-26 22:09:38 -07:00
})
app.get("/server",(req,res) => {
res.send(JSON.stringify({...config,version:pkg.version}))
})
2022-09-26 22:09:38 -07:00
app.get("*",(req,res) => {
ThrowError(res,404,"Page not found.")
2022-09-26 22:09:38 -07:00
})
app.listen(3000,function() {
console.log("Web OK!")
})
client.login(process.env.TOKEN)