diff --git a/backend/src/app.ts b/backend/src/app.ts index 9678691..77a3e16 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -1,50 +1,54 @@ -import * as bodyParser from 'body-parser' -import cors from 'cors' -import express from 'express' -import { existsSync, mkdirSync } from 'fs' -import moment from 'moment-timezone' -import multer from 'multer' -import path from 'path' -import { mw as requestIpMw } from 'request-ip' -import getImageHandler from './app/controllers/img/getImageHandler' -import putImageHandler from './app/controllers/img/putImageHandler' -import getTxtHandler from './app/controllers/txt/getTxtHandler' -import putTxtHandler from './app/controllers/txt/putTxtHandler' -import getUrlHandler from './app/controllers/url/getUrlHandler' -import putUrlHandler from './app/controllers/url/putUrlHandler' +import * as bodyParser from "body-parser"; +import cors from "cors"; +import express from "express"; +import { existsSync, mkdirSync } from "fs"; +import moment from "moment-timezone"; +import multer from "multer"; +import { mw as requestIpMw } from "request-ip"; +import getFileHandler from "./app/controllers/file/getFileHandler"; +import putFileHandler from "./app/controllers/file/putFileHandler"; +import getTxtHandler from "./app/controllers/txt/getTxtHandler"; +import putTxtHandler from "./app/controllers/txt/putTxtHandler"; +import getUrlHandler from "./app/controllers/url/getUrlHandler"; +import putUrlHandler from "./app/controllers/url/putUrlHandler"; -const app = express() +const app = express(); -app.use(cors()) -app.use(requestIpMw()) -app.use(bodyParser.json()) -app.use(bodyParser.urlencoded({ - extended: true -})) +app.use(cors()); +app.use(requestIpMw()); +app.use(bodyParser.json()); +app.use( + bodyParser.urlencoded({ + extended: true, + }) +); -const uploadPath = '/tmp/ImgUploads' +const uploadPath = "/tmp/FileUploads"; if (!existsSync(uploadPath)) { - mkdirSync(uploadPath) + mkdirSync(uploadPath); } const storage = multer.diskStorage({ - destination: (req, file, cb) => { - cb(null, uploadPath) - }, - filename: (req, file, cb) => { - cb(null, `${file.fieldname}-${moment().toISOString()}`) - } -}) -// 52428800 = 50mb -const uploader = multer({ storage, limits: { fileSize: 52428800 } }) -// Image Uploader -app.put("/api/img", uploader.single("image"), putImageHandler) -app.get("/i/:slug", getImageHandler) -// Pastebin -app.put("/api/paste", putTxtHandler) -app.get("/p/:slug", getTxtHandler) -// URL Shortener -- LAST for a reason. -app.put("/api/url", putUrlHandler) -app.get("/:slug", getUrlHandler) + destination: (req, file, cb) => { + cb(null, uploadPath); + }, + filename: (req, file, cb) => { + cb(null, `${file.fieldname}-${moment().toISOString()}`); + }, +}); -export default app \ No newline at end of file +const uploader = multer({ + storage, + // limits: { fileSize: 17825792 }, +}).single("file"); +// Image Uploader +app.put("/api/file", uploader, putFileHandler); +app.get("/f/:slug", getFileHandler); +// Pastebin +app.put("/api/paste", putTxtHandler); +app.get("/p/:slug", getTxtHandler); +// URL Shortener -- LAST for a reason. +app.put("/api/url", putUrlHandler); +app.get("/:slug", getUrlHandler); + +export default app; diff --git a/backend/src/app/controllers/file/getFileHandler.ts b/backend/src/app/controllers/file/getFileHandler.ts new file mode 100644 index 0000000..50a3ab6 --- /dev/null +++ b/backend/src/app/controllers/file/getFileHandler.ts @@ -0,0 +1,28 @@ +import { Request, Response } from "express"; +import Files from "../../db/file.schema"; + +export default async (req: Request, res: Response) => { + try { + const file = await Files.findById(req.params.slug); + + if (file) { + // If it's an image, render it instead of DLing it + const isImage = file.img.contentType.startsWith("image/"); + + res.setHeader( + "Content-Disposition", + `${isImage ? "" : "attachment;"} filename=${file.img.name}` + ); + res.contentType(file.img.contentType); + return res.send(file.img.data); + } else { + console.log("did not find file"); + res.status(404).end(); + } + } catch (ex) { + console.error(ex); + return res.status(500).send({ + error: ex, + }); + } +}; diff --git a/backend/src/app/controllers/file/putFileHandler.ts b/backend/src/app/controllers/file/putFileHandler.ts new file mode 100644 index 0000000..339db1d --- /dev/null +++ b/backend/src/app/controllers/file/putFileHandler.ts @@ -0,0 +1,36 @@ +import { Request, Response } from "express"; +import fs from "fs"; +import Files from "../../db/file.schema"; + +export default async (req: Request, res: Response) => { + try { + const data = fs.readFileSync(req.file.path); + fs.unlinkSync(req.file.path); + + const files = await Files.find(); + + for (const file of files) { + if (file.img.data.compare(data) === 0) { + /* If some other IP uploads, we want to add them too */ + file.uploaders.push(req.clientIp as string); + await file.save(); + return res.status(200).send(file._id); + } + } + + const file = new Files(); + + file.img.contentType = req.file.mimetype; + file.img.name = req.file.originalname; + file.img.data = data; + file.uploaders = req.clientIp ? [req.clientIp as string] : []; + + await file.save(); + + return res.status(200).send(file._id); + } catch (ex) { + return res.status(500).send({ + error: ex, + }); + } +}; diff --git a/backend/src/app/controllers/img/getImageHandler.ts b/backend/src/app/controllers/img/getImageHandler.ts deleted file mode 100644 index 808c025..0000000 --- a/backend/src/app/controllers/img/getImageHandler.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { Request, Response } from 'express' -import Images from '../../db/img.schema' - -export default async (req: Request, res: Response) => { - try { - const img = await Images.findById(req.params.slug) - - if (img) { - res.contentType(img.img.contentType) - res.send(img.img.data) - } else { - res.status(404).end() - } - } catch (ex) { - console.error(ex) - return res.status(500).send({ - error: ex - }) - } -} \ No newline at end of file diff --git a/backend/src/app/controllers/img/putImageHandler.ts b/backend/src/app/controllers/img/putImageHandler.ts deleted file mode 100644 index f83fc1e..0000000 --- a/backend/src/app/controllers/img/putImageHandler.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { Request, Response } from 'express' -import fs from 'fs' -import Images from '../../db/img.schema' - -export default async (req: Request, res: Response) => { - try { - const data = fs.readFileSync(req.file.path) - fs.unlinkSync(req.file.path) - - const images = await Images.find() - - for (const img of images) { - if (img.img.data.compare(data) === 0) { - /* If some other IP uploads, we want to add them too */ - img.uploaders.push(req.clientIp as string) - await img.save() - return res.status(200).send(img._id) - } - } - - const img = new Images() - - img.img.contentType = req.file.mimetype - img.img.data = data - img.uploaders = req.clientIp ? [req.clientIp as string] : [] - - await img.save() - - return res.status(200).send(img._id) - } catch (ex) { - console.error(ex) - return res.status(500).send({ - error: ex - }) - } -} \ No newline at end of file diff --git a/backend/src/app/db/file.schema.ts b/backend/src/app/db/file.schema.ts new file mode 100644 index 0000000..ad74ea4 --- /dev/null +++ b/backend/src/app/db/file.schema.ts @@ -0,0 +1,34 @@ +import moment from "moment"; +import { Document, model, Schema } from "mongoose"; +import shortid from "shortid"; + +const FileSchema = new Schema({ + _id: { + type: String, + default: shortid.generate, + }, + createdAt: { + type: Date, + default: moment().toISOString(), + }, + uploaders: [String], + img: { + contentType: String, + data: Buffer, + name: String, + }, +}); + +export type FileModel = Document & { + _id: string; + createdAt: Date; + uploaders: string[]; + img: { + contentType: string; + data: Buffer; + name: string; + }; +}; + +// Left this as images to retain old data +export default model("images", FileSchema, "images"); diff --git a/backend/src/app/db/img.schema.ts b/backend/src/app/db/img.schema.ts deleted file mode 100644 index c2be2fe..0000000 --- a/backend/src/app/db/img.schema.ts +++ /dev/null @@ -1,31 +0,0 @@ -import moment from 'moment' -import { Document, model, Schema } from 'mongoose' -import shortid from 'shortid' - -const ImgSchema = new Schema({ - _id: { - type: String, - default: shortid.generate - }, - createdAt: { - type: Date, - default: moment().toISOString() - }, - uploaders: [String], - img: { - contentType: String, - data: Buffer, - } -}) - -export type ImgModel = Document & { - _id: string, - createdAt: Date, - uploaders: string[], - img: { - contentType: string, - data: Buffer - } -} - -export default model("images", ImgSchema, "images") diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 697bb1d..bc79694 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -2,10 +2,10 @@ import 'bootstrap/dist/css/bootstrap.min.css'; import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Route } from 'react-router-dom'; +import FileUpload from './components/FileUpload'; import NavBar from './components/modules/NavBar'; -import UrlShortener from './components/UrlShortener'; -import ImageUpload from './components/ImageUpload'; import TextUpload from './components/TextUpload'; +import UrlShortener from './components/UrlShortener'; export default () => { ReactDOM.render( @@ -14,7 +14,7 @@ export default () => {
- + , diff --git a/frontend/src/axios/putFileHandler.js b/frontend/src/axios/putFileHandler.js new file mode 100644 index 0000000..6f02aee --- /dev/null +++ b/frontend/src/axios/putFileHandler.js @@ -0,0 +1,13 @@ +import axios from 'axios'; + +export default (file) => { + if (file.size > 16000000) { + return { error: true, size: file.size }; + } + + const formData = new FormData(); + formData.append('file', file); + return axios.put('/api/file', formData) + .then((resp) => resp.data) + .catch((ex) => alert(ex)); +}; diff --git a/frontend/src/axios/putImgHandler.js b/frontend/src/axios/putImgHandler.js deleted file mode 100644 index dd6e338..0000000 --- a/frontend/src/axios/putImgHandler.js +++ /dev/null @@ -1,7 +0,0 @@ -import axios from 'axios'; - -export default (file) => { - const formData = new FormData(); - formData.append('image', file); - return axios.put('/api/img', formData).then((resp) => resp.data); -}; diff --git a/frontend/src/components/ImageUpload.jsx b/frontend/src/components/FileUpload.jsx similarity index 68% rename from frontend/src/components/ImageUpload.jsx rename to frontend/src/components/FileUpload.jsx index 72eefa7..752c7a3 100644 --- a/frontend/src/components/ImageUpload.jsx +++ b/frontend/src/components/FileUpload.jsx @@ -3,24 +3,37 @@ import { Button, Container, Form, InputGroup, } from 'react-bootstrap'; import { CSSTransition } from 'react-transition-group'; -import putImgHandler from '../axios/putImgHandler'; +import putImgHandler from '../axios/putFileHandler'; + +const toMb = (size) => (size / 1000000).toFixed(2); export default () => { const [state, setState] = useState({ loading: false, result: null, file: null, + error: null, }); const submit = (evt) => { evt.preventDefault(); if (state.file && state.file.name.length) { + if (state.file.size > 16000000) { + setState({ + loading: false, + result: null, + file: null, + error: `File size ${toMb(state.file.size)}MB is too large`, + }); + return; + } setState({ ...state, loading: true }); putImgHandler(state.file).then((data) => { setState({ - ...state, - result: `http://${window.location.host}/i/${data}`.replace('5000', '3000'), loading: false, + result: `${window.location.origin}/f/${data}`.replace('5000', '3000'), + file: null, + error: null, }); }); } @@ -29,7 +42,7 @@ export default () => { return ( -

Image Uploader

+

File Uploader

@@ -37,9 +50,8 @@ export default () => { setState({ ...state, file: evt.target.files[0] })} /> @@ -51,6 +63,12 @@ export default () => {
+ {state.error && ( +
+ {state.error} +
+ )} + {state.result && (
diff --git a/frontend/src/components/modules/NavBar.jsx b/frontend/src/components/modules/NavBar.jsx index 321c7b4..ac61f83 100644 --- a/frontend/src/components/modules/NavBar.jsx +++ b/frontend/src/components/modules/NavBar.jsx @@ -1,4 +1,4 @@ -import { faCode, faImage, faLink } from '@fortawesome/free-solid-svg-icons'; +import { faCode, faFile, faLink } from '@fortawesome/free-solid-svg-icons'; import React from 'react'; import { Nav, Navbar } from 'react-bootstrap'; import NavLinkItem from './NavLinkItem'; @@ -10,8 +10,8 @@ export default () => (