fantus/pages/api/form.tsx

78 lines
1.9 KiB
TypeScript
Raw Normal View History

2020-01-12 18:34:27 +01:00
import { createReadStream, statSync, unlinkSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
2021-01-02 00:21:29 +01:00
import type { NextApiRequest, NextApiResponse } from 'next'
2020-01-12 18:34:27 +01:00
import Formidable from 'formidable'
import axios from 'axios'
const sendFileAndDelete = async (name: string, path: string) => {
2021-01-02 00:21:29 +01:00
const stat = statSync(path)
const stream = createReadStream(path)
await axios({
url: 'https://cloud.nicco.io/public.php/webdav/' + name,
method: 'put',
auth: {
username: process.env.NEXTCLOUD_TOKEN || '',
password: '',
},
headers: {
'Content-Length': stat.size,
},
data: stream,
maxContentLength: Infinity,
})
2020-01-12 18:34:27 +01:00
2021-01-02 00:21:29 +01:00
unlinkSync(path)
2020-01-12 18:34:27 +01:00
}
export default async (req: NextApiRequest, res: NextApiResponse) => {
2021-01-02 00:21:29 +01:00
try {
// @ts-ignore
const form = new Formidable()
form.maxFileSize = 300 * 1024 * 1024 // 300MiB
const body = await new Promise<any>((resolve, reject) => {
form.parse(req, (err: any, fields: any, files: any) => {
if (err) reject()
else
resolve({
fields: JSON.parse(fields.json),
files: Object.values(files),
})
})
})
2020-01-12 18:34:27 +01:00
2021-01-02 00:21:29 +01:00
const { token, ...rest } = body.fields
2020-01-12 18:34:27 +01:00
2021-01-02 00:21:29 +01:00
const { data } = await axios({
url: 'https://www.google.com/recaptcha/api/siteverify',
method: 'post',
params: {
secret: process.env.RECAPTCHA_SERVER,
response: token,
},
})
2020-01-12 18:34:27 +01:00
2021-01-02 00:21:29 +01:00
if (!data.success) throw new Error()
2020-01-12 18:34:27 +01:00
2021-01-02 00:21:29 +01:00
const now = Date.now()
for (const file of body.files) await sendFileAndDelete(`${now}_${file.name}`, file.path)
2020-01-12 18:34:27 +01:00
2021-01-02 00:21:29 +01:00
const txtFile = `${tmpdir()}/text`
writeFileSync(txtFile, `${rest.contact}\n${rest.description}`)
await sendFileAndDelete(`${now}_details.txt`, txtFile)
2020-01-12 18:34:27 +01:00
2021-01-02 00:21:29 +01:00
res.status(200).end()
} catch {
res.status(400).end()
}
2020-01-12 18:34:27 +01:00
}
export const config = {
2021-01-02 00:21:29 +01:00
api: {
bodyParser: false,
},
}