This commit is contained in:
oitsjustjose 2020-10-16 01:31:59 -05:00
commit 25f973e2b3
37 changed files with 812 additions and 470 deletions

View file

@ -0,0 +1,50 @@
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'
const app = express()
app.use(cors())
app.use(requestIpMw())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
const uploadPath = '/tmp/ImgUploads'
if (!existsSync(uploadPath)) {
mkdirSync(uploadPath)
}
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadPath)
},
filename: (req, file, cb) => {
cb(null, `${file.fieldname}-${moment().toISOString()}`)
}
})
const uploader = multer({ storage })
// 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
app.put("/api/url", putUrlHandler)
app.get("/u/:slug", getUrlHandler)
export default app

View file

@ -0,0 +1,20 @@
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
})
}
}

View file

@ -0,0 +1,37 @@
import { Request, Response } from 'express'
import Images from '../../db/img.schema'
import fs from 'fs'
import path from 'path'
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
})
}
}

View file

@ -0,0 +1,34 @@
import { Request, Response } from 'express'
import Pastes from '../../db/txt.schema'
import moment from 'moment-timezone'
export default async (req: Request, res: Response) => {
try {
const paste = await Pastes.findById(req.params.slug)
if (paste) {
// Check for an expired link
if (moment().isAfter(moment(paste.expiresAt))) {
await Pastes.findByIdAndDelete(paste._id)
return res.status(404).send("PASTE_EXPIRED")
}
if (req.query && paste.syntax === null) {
paste.syntax = Object.keys(req.query)[0]
await paste.save()
}
return res.json({
paste: paste.paste,
syntax: paste.syntax
})
} else {
return res.status(404).end()
}
} catch (ex) {
console.error(ex)
return res.status(500).send({
error: ex
})
}
}

View file

@ -0,0 +1,20 @@
import { Request, Response } from 'express'
import Pastes from '../../db/txt.schema'
import moment from 'moment-timezone'
export default async (req: Request, res: Response) => {
try {
const paste = new Pastes()
paste.paste = req.body.paste
paste.syntax = req.body.syntax
paste.expiresAt = moment().add(req.body.expiry).toDate()
await paste.save()
return res.status(200).send(paste._id)
} catch (ex) {
console.error(ex)
return res.status(500).send({
error: ex
})
}
}

View file

@ -0,0 +1,19 @@
import { Request, Response } from 'express'
import URLs from '../../db/url.schema'
export default async (req: Request, res: Response) => {
try {
const url = await URLs.findById(req.params.slug)
if (url) {
res.redirect(url.url);
} else {
res.status(404).send()
}
} catch (ex) {
console.error(ex)
return res.status(500).send({
error: ex
})
}
}

View file

@ -0,0 +1,17 @@
import { Request, Response } from 'express'
import URLs from '../../db/url.schema'
export default async (req: Request, res: Response) => {
try {
const url = new URLs()
url.url = req.body.url
await url.save()
return res.status(200).send(url._id);
} catch (ex) {
console.error(ex)
return res.status(500).send({
error: ex
})
}
}

View file

@ -0,0 +1,31 @@
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<ImgModel>("images", ImgSchema, "images")

View file

@ -0,0 +1,31 @@
import { Schema, model, Document } from 'mongoose'
import shortid from 'shortid'
const PasteSchema = new Schema({
_id: {
type: String,
default: shortid.generate
},
paste: { type: String },
syntax: {
type: String,
default: null
},
expiresAt: {
type: Date,
expires: 0,
default: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7)
},
}, {
timestamps: true
})
export type PasteModel = Document & {
_id: string,
paste: string,
syntax: string,
expiresAt: Date,
timestamps: Date
}
export default model<PasteModel>('Paste', PasteSchema)

View file

@ -0,0 +1,17 @@
import mongoose, { Document, Schema, Types } from 'mongoose'
import shortid from 'shortid'
const UrlSchema: Schema = new Schema({
_id: {
type: String,
default: shortid.generate
},
url: String
})
export type UrlModel = Document & {
_id: string,
url: string
}
export default mongoose.model<UrlModel>('urls', UrlSchema, 'urls')

View file

@ -0,0 +1,9 @@
import mongoose from 'mongoose'
export default async () => {
await mongoose.connect(`mongodb://${process.env.MONGO_URI}/Utils`, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
}

View file

@ -0,0 +1,13 @@
import { config as LoadDotenv } from 'dotenv'
import app from './app'
import connectDB from './db'
if(process.env.NODE_ENV !== "production") {
LoadDotenv()
}
connectDB()
const port = process.env.PORT || 3000
app.listen(port, () => console.log(`Listening at http://127.0.0.1:${port}`))