This commit is contained in:
Pitu 2017-03-17 01:14:24 -03:00
parent 8a96a0df1d
commit 1db1b06a48
5 changed files with 197 additions and 300 deletions

View File

@ -1,42 +1,39 @@
const config = require('../config.js')
const db = require('knex')(config.database)
const randomstring = require('randomstring')
const path = require('path')
const fs = require('fs')
const ffmpeg = require('fluent-ffmpeg')
const gm = require('gm')
const utils = require('utilsController.js')
let albumsController = {}
albumsController.list = function(req, res, next){
albumsController.list = function(req, res, next) {
let token = req.headers.token
if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
db.table('users').where('token', token).then((user) => {
if(user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
if (user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token' })
let fields = ['id', 'name']
if(req.params.sidebar === undefined){
if (req.params.sidebar === undefined) {
fields.push('timestamp')
fields.push('identifier')
}
db.table('albums').select(fields).where({enabled: 1, userid: user[0].id}).then((albums) => {
db.table('albums').select(fields).where({ enabled: 1, userid: user[0].id }).then((albums) => {
if(req.params.sidebar !== undefined)
if (req.params.sidebar !== undefined)
return res.json({ success: true, albums })
let ids = []
for(let album of albums){
for (let album of albums) {
album.date = new Date(album.timestamp * 1000)
album.date = album.date.getFullYear() + '-' + (album.date.getMonth() + 1) + '-' + album.date.getDate() + ' ' + (album.date.getHours() < 10 ? '0' : '') + album.date.getHours() + ':' + (album.date.getMinutes() < 10 ? '0' : '') + album.date.getMinutes() + ':' + (album.date.getSeconds() < 10 ? '0' : '') + album.date.getSeconds()
album.date = utils.getPrettyDate(album.date) // album.date.getFullYear() + '-' + (album.date.getMonth() + 1) + '-' + album.date.getDate() + ' ' + (album.date.getHours() < 10 ? '0' : '') + album.date.getHours() + ':' + (album.date.getMinutes() < 10 ? '0' : '') + album.date.getMinutes() + ':' + (album.date.getSeconds() < 10 ? '0' : '') + album.date.getSeconds()
let basedomain = req.get('host')
for(let domain of config.domains)
if(domain.host === req.get('host'))
if(domain.hasOwnProperty('resolve'))
for (let domain of config.domains)
if (domain.host === req.get('host'))
if (domain.hasOwnProperty('resolve'))
basedomain = domain.resolve
album.identifier = basedomain + '/a/' + album.identifier
@ -48,27 +45,27 @@ albumsController.list = function(req, res, next){
let albumsCount = {}
for(let id of ids) albumsCount[id] = 0
for(let file of files) albumsCount[file.albumid] += 1
for(let album of albums) album.files = albumsCount[album.id]
for (let id of ids) albumsCount[id] = 0
for (let file of files) albumsCount[file.albumid] += 1
for (let album of albums) album.files = albumsCount[album.id]
return res.json({ success: true, albums })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}
albumsController.create = function(req, res, next){
albumsController.create = function(req, res, next) {
let token = req.headers.token
if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
db.table('users').where('token', token).then((user) => {
if(user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
if (user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token' })
let name = req.body.name
if(name === undefined || name === '')
if (name === undefined || name === '')
return res.json({ success: false, description: 'No album name specified' })
db.table('albums').where({
@ -76,7 +73,7 @@ albumsController.create = function(req, res, next){
enabled: 1,
userid: user[0].id
}).then((album) => {
if(album.length !== 0) return res.json({ success: false, description: 'There\'s already an album with that name' })
if (album.length !== 0) return res.json({ success: false, description: 'There\'s already an album with that name' })
db.table('albums').insert({
name: name,
@ -87,120 +84,76 @@ albumsController.create = function(req, res, next){
}).then(() => {
return res.json({ success: true })
})
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}
albumsController.delete = function(req, res, next){
albumsController.delete = function(req, res, next) {
let token = req.headers.token
if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
db.table('users').where('token', token).then((user) => {
if(user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
if (user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
let id = req.body.id
if(id === undefined || id === '')
if (id === undefined || id === ''){
return res.json({ success: false, description: 'No album specified' })
}
db.table('albums').where({id: id, userid: user[0].id}).update({ enabled: 0 }).then(() => {
db.table('albums').where({ id: id, userid: user[0].id }).update({ enabled: 0 }).then(() => {
return res.json({ success: true })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}
albumsController.rename = function(req, res, next){
albumsController.rename = function(req, res, next) {
let token = req.headers.token
if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
db.table('users').where('token', token).then((user) => {
if(user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
if (user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
let id = req.body.id
if(id === undefined || id === '')
if (id === undefined || id === '')
return res.json({ success: false, description: 'No album specified' })
let name = req.body.name
if(name === undefined || name === '')
if (name === undefined || name === '')
return res.json({ success: false, description: 'No name specified' })
db.table('albums').where({name: name, userid: user[0].id}).then((results) => {
if(results.length !== 0) return res.json({ success: false, description: 'Name already in use' })
db.table('albums').where({ name: name, userid: user[0].id }).then((results) => {
if (results.length !== 0) return res.json({ success: false, description: 'Name already in use' })
db.table('albums').where({id: id, userid: user[0].id}).update({ name: name }).then(() => {
db.table('albums').where({ id: id, userid: user[0].id }).update({ name: name }).then(() => {
return res.json({ success: true })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}
albumsController.get = function(req, res, next){
albumsController.get = function(req, res, next) {
let identifier = req.params.identifier
if(identifier === undefined) return res.status(401).json({ success: false, description: 'No identifier provided' })
if (identifier === undefined) return res.status(401).json({ success: false, description: 'No identifier provided' })
db.table('albums')
.where('identifier', identifier)
.then((albums) => {
if(albums.length === 0) return res.json({ success: false, description: 'Album not found' })
if (albums.length === 0) return res.json({ success: false, description: 'Album not found' })
let title = albums[0].name
db.table('files').select('name').where('albumid', albums[0].id).orderBy('id', 'DESC').then((files) => {
let basedomain = req.get('host')
for(let domain of config.domains)
if(domain.host === req.get('host'))
if(domain.hasOwnProperty('resolve'))
for (let domain of config.domains)
if (domain.host === req.get('host'))
if (domain.hasOwnProperty('resolve'))
basedomain = domain.resolve
for(let file of files){
for (let file of files) {
file.file = basedomain + '/' + file.name
if(config.uploads.generateThumbnails === true){
let extensions = ['.jpg', '.jpeg', '.bmp', '.gif', '.png', '.webm', '.mp4']
for(let ext of extensions){
if(path.extname(file.name) === ext){
file.thumb = basedomain + '/thumbs/' + file.name.slice(0, -ext.length) + '.png'
let thumbname = path.join(__dirname, '..', config.uploads.folder, 'thumbs') + '/' + file.name.slice(0, -ext.length) + '.png'
fs.access(thumbname, function(err) {
if (err && err.code === 'ENOENT') {
// File doesnt exist
if (ext === '.webm' || ext === '.mp4') {
ffmpeg('./' + config.uploads.folder + '/' + file.name)
.thumbnail({
timestamps: [0],
filename: '%b.png',
folder: './' + config.uploads.folder + '/thumbs',
size: '200x?'
})
.on('error', function(error) {
console.log('Error - ', error.message)
})
}
else {
let size = {
width: 200,
height: 200
}
gm('./' + config.uploads.folder + '/' + file.name)
.resize(size.width, size.height + '>')
.gravity('Center')
.extent(size.width, size.height)
.background('transparent')
.write(thumbname, function (error) {
if (error) console.log('Error - ', error)
})
}
}
})
}
}
}
utils.generateThumbs(file)
}
return res.json({
@ -210,9 +163,8 @@ albumsController.get = function(req, res, next){
files
})
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}
module.exports = albumsController

View File

@ -6,46 +6,46 @@ const randomstring = require('randomstring')
let authController = {}
authController.verify = function(req, res, next){
authController.verify = function(req, res, next) {
let username = req.body.username
let password = req.body.password
if(username === undefined) return res.json({ success: false, description: 'No username provided' })
if(password === undefined) return res.json({ success: false, description: 'No password provided' })
if (username === undefined) return res.json({ success: false, description: 'No username provided' })
if (password === undefined) return res.json({ success: false, description: 'No password provided' })
db.table('users').where('username', username).then((user) => {
if(user.length === 0) return res.json({ success: false, description: 'Username doesn\'t exist' })
if (user.length === 0) return res.json({ success: false, description: 'Username doesn\'t exist' })
bcrypt.compare(password, user[0].password, function(err, result) {
if(result === false) return res.json({ success: false, description: 'Wrong password' })
if (result === false) return res.json({ success: false, description: 'Wrong password' })
return res.json({ success: true, token: user[0].token })
})
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}
authController.register = function(req, res, next){
authController.register = function(req, res, next) {
if(config.enableUserAccounts === false)
if (config.enableUserAccounts === false)
return res.json({ success: false, description: 'Register is disabled at the moment' })
let username = req.body.username
let password = req.body.password
if(username === undefined) return res.json({ success: false, description: 'No username provided' })
if(password === undefined) return res.json({ success: false, description: 'No password provided' })
if (username === undefined) return res.json({ success: false, description: 'No username provided' })
if (password === undefined) return res.json({ success: false, description: 'No password provided' })
if(username.length < 4 || username.length > 32)
if (username.length < 4 || username.length > 32)
return res.json({ success: false, description: 'Username must have 4-32 characters' })
if(password.length < 6 || password.length > 64)
if (password.length < 6 || password.length > 64)
return res.json({ success: false, description: 'Password must have 6-64 characters' })
db.table('users').where('username', username).then((user) => {
if(user.length !== 0) return res.json({ success: false, description: 'Username already exists' })
if (user.length !== 0) return res.json({ success: false, description: 'Username already exists' })
bcrypt.hash(password, saltRounds, function(err, hash) {
if(err) return res.json({ success: false, description: 'Error generating password hash (╯°□°)╯︵ ┻━┻' })
if (err) return res.json({ success: false, description: 'Error generating password hash (╯°□°)╯︵ ┻━┻' })
let token = randomstring.generate(64)
@ -54,36 +54,35 @@ authController.register = function(req, res, next){
password: hash,
token: token
}).then(() => {
return res.json({ success: true, token: token})
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
return res.json({ success: true, token: token })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
})
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}
authController.changePassword = function(req, res, next){
authController.changePassword = function(req, res, next) {
let token = req.headers.token
if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
db.table('users').where('token', token).then((user) => {
if(user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
if (user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
let password = req.body.password
if(password === undefined) return res.json({ success: false, description: 'No password provided' })
if(password.length < 6 || password.length > 64)
if (password === undefined) return res.json({ success: false, description: 'No password provided' })
if (password.length < 6 || password.length > 64)
return res.json({ success: false, description: 'Password must have 6-64 characters' })
bcrypt.hash(password, saltRounds, function(err, hash) {
if(err) return res.json({ success: false, description: 'Error generating password hash (╯°□°)╯︵ ┻━┻' })
if (err) return res.json({ success: false, description: 'Error generating password hash (╯°□°)╯︵ ┻━┻' })
db.table('users').where('id', user[0].id).update({password: hash}).then(() => {
return res.json({ success: true})
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
db.table('users').where('id', user[0].id).update({ password: hash }).then(() => {
return res.json({ success: true })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
})
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}
module.exports = authController

View File

@ -4,34 +4,34 @@ const randomstring = require('randomstring')
let tokenController = {}
tokenController.verify = function(req, res, next){
tokenController.verify = function(req, res, next) {
if(req.body.token === undefined) return res.json({ success: false, description: 'No token provided' })
if (req.body.token === undefined) return res.json({ success: false, description: 'No token provided' })
let token = req.body.token
db.table('users').where('token', token).then((user) => {
if(user.length === 0) return res.json({ success: false, description: 'Token mismatch' })
return res.json({ success: true, username: user[0].username})
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
if (user.length === 0) return res.json({ success: false, description: 'Token mismatch' })
return res.json({ success: true, username: user[0].username })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}
tokenController.list = function(req, res, next){
tokenController.list = function(req, res, next) {
let token = req.headers.token
if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
db.table('users').where('token', token).then((user) => {
if(user.length === 0) return res.json({ success: false, description: 'Token mismatch' })
if (user.length === 0) return res.json({ success: false, description: 'Token mismatch' })
return res.json({ success: true, token: token })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}
tokenController.change = function(req, res, next){
tokenController.change = function(req, res, next) {
let token = req.headers.token
if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
let newtoken = randomstring.generate(64)
@ -40,8 +40,7 @@ tokenController.change = function(req, res, next){
timestamp: Math.floor(Date.now() / 1000)
}).then(() => {
res.json({ success: true, token: newtoken })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}
module.exports = tokenController

View File

@ -1,20 +1,19 @@
const path = require('path')
const config = require('../config.js')
const multer = require('multer')
const multer = require('multer')
const randomstring = require('randomstring')
const db = require('knex')(config.database)
const crypto = require('crypto')
const fs = require('fs')
const gm = require('gm')
const ffmpeg = require('fluent-ffmpeg')
const utils = require('utilsController.js')
let uploadsController = {}
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './' + config.uploads.folder + '/')
destination: function(req, file, cb) {
cb(null, path.join(__dirname, '..', config.uploads.folder))
},
filename: function (req, file, cb) {
filename: function(req, file, cb) {
cb(null, randomstring.generate(config.uploads.fileLength) + path.extname(file.originalname))
}
})
@ -24,28 +23,27 @@ const upload = multer({
limits: { fileSize: config.uploads.maxSize }
}).array('files[]')
uploadsController.upload = function(req, res, next){
uploadsController.upload = function(req, res, next) {
// Get the token
let token = req.headers.token
// If we're running in private and there's no token, error
if(config.private === true)
if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
if (config.private === true)
if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
// If there is no token then just leave it blank so the query fails
if(token === undefined) token = ''
if (token === undefined) token = ''
db.table('users').where('token', token).then((user) => {
let userid
if(user.length > 0)
userid = user[0].id
if (user.length > 0) userid = user[0].id
// Check if user is trying to upload to an album
let album = undefined
if(userid !== undefined){
let album
if (userid !== undefined) {
album = req.headers.albumid
if(album === undefined)
if (album === undefined)
album = req.params.albumid
}
@ -58,7 +56,7 @@ uploadsController.upload = function(req, res, next){
})
}
if(req.files.length === 0) return res.json({ success: false, description: 'no-files' })
if (req.files.length === 0) return res.json({ success: false, description: 'no-files' })
let files = []
let existingFiles = []
@ -68,18 +66,18 @@ uploadsController.upload = function(req, res, next){
// Check if the file exists by checking hash and size
let hash = crypto.createHash('md5')
let stream = fs.createReadStream('./' + config.uploads.folder + '/' + file.filename)
let stream = fs.createReadStream(path.join(__dirname, '..', config.uploads.folder, file.filename))
stream.on('data', function (data) {
hash.update(data, 'utf8')
})
stream.on('end', function () {
let fileHash = hash.digest('hex') // 34f7a3113803f8ed3b8fd7ce5656ebec
let fileHash = hash.digest('hex')
db.table('files')
.where(function(){
if(userid === undefined)
.where(function() {
if (userid === undefined)
this.whereNull('userid')
else
this.where('userid', userid)
@ -89,10 +87,10 @@ uploadsController.upload = function(req, res, next){
size: file.size
}).then((dbfile) => {
if(dbfile.length !== 0){
if (dbfile.length !== 0) {
uploadsController.deleteFile(file.filename).then(() => {}).catch((e) => console.error(e))
existingFiles.push(dbfile[0])
}else{
} else {
files.push({
name: file.filename,
original: file.originalname,
@ -106,26 +104,25 @@ uploadsController.upload = function(req, res, next){
})
}
if(iteration === req.files.length)
if (iteration === req.files.length)
return uploadsController.processFilesForDisplay(req, res, files, existingFiles)
iteration++
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
})
})
})
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}
uploadsController.processFilesForDisplay = function(req, res, files, existingFiles){
uploadsController.processFilesForDisplay = function(req, res, files, existingFiles) {
let basedomain = req.get('host')
for(let domain of config.domains)
if(domain.host === req.get('host'))
if(domain.hasOwnProperty('resolve'))
for (let domain of config.domains)
if (domain.host === req.get('host'))
if (domain.hasOwnProperty('resolve'))
basedomain = domain.resolve
if(files.length === 0){
if (files.length === 0) {
return res.json({
success: true,
files: existingFiles.map(file => {
@ -140,7 +137,7 @@ uploadsController.processFilesForDisplay = function(req, res, files, existingFil
db.table('files').insert(files).then(() => {
for(let efile of existingFiles) files.push(efile)
for (let efile of existingFiles) files.push(efile)
res.json({
success: true,
@ -153,55 +150,54 @@ uploadsController.processFilesForDisplay = function(req, res, files, existingFil
})
})
for (let file of files){
uploadsController.generateThumbs(file, basedomain)
for (let file of files) {
utils.generateThumbs(file)
}
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}
uploadsController.delete = function(req, res){
uploadsController.delete = function(req, res) {
let token = req.headers.token
if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
let id = req.body.id
if(id === undefined || id === '')
if (id === undefined || id === '')
return res.json({ success: false, description: 'No file specified' })
db.table('users').where('token', token).then((user) => {
if(user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
if (user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token' })
db.table('files')
.where('id', id)
.where(function(){
if(user[0].username !== 'root')
.where(function() {
if (user[0].username !== 'root')
this.where('userid', user[0].id)
})
.then((file) => {
uploadsController.deleteFile(file[0].name).then(() => {
db.table('files').where('id', id).del().then(() =>{
db.table('files').where('id', id).del().then(() => {
return res.json({ success: true })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}).catch((e) => {
console.log(e.toString())
db.table('files').where('id', id).del().then(() =>{
db.table('files').where('id', id).del().then(() => {
return res.json({ success: true })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
})
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}
uploadsController.deleteFile = function(file){
uploadsController.deleteFile = function(file) {
return new Promise(function(resolve, reject){
fs.stat('./' + config.uploads.folder + '/' + file, function (err, stats) {
return new Promise(function(resolve, reject) {
fs.stat(path.join(__dirname, '..', config.uploads.folder, file), function(err, stats) {
if (err) { return reject(err) }
fs.unlink('./' + config.uploads.folder + '/' + file, function(err){
fs.unlink(path.join(__dirname, '..', config.uploads.folder, file), function(err) {
if (err) { return reject(err) }
return resolve()
})
@ -210,26 +206,26 @@ uploadsController.deleteFile = function(file){
}
uploadsController.list = function(req, res){
uploadsController.list = function(req, res) {
let token = req.headers.token
if(token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
if (token === undefined) return res.status(401).json({ success: false, description: 'No token provided' })
db.table('users').where('token', token).then((user) => {
if(user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
if (user.length === 0) return res.status(401).json({ success: false, description: 'Invalid token'})
let offset = req.params.page
if(offset === undefined) offset = 0
if (offset === undefined) offset = 0
db.table('files')
.where(function(){
if(req.params.id === undefined)
.where(function() {
if (req.params.id === undefined)
this.where('id', '<>', '')
else
this.where('albumid', req.params.id)
})
.where(function(){
if(user[0].username !== 'root')
.where(function() {
if (user[0].username !== 'root')
this.where('userid', user[0].id)
})
.orderBy('id', 'DESC')
@ -240,96 +236,50 @@ uploadsController.list = function(req, res){
db.table('albums').then((albums) => {
let basedomain = req.get('host')
for(let domain of config.domains)
if(domain.host === req.get('host'))
if(domain.hasOwnProperty('resolve'))
for (let domain of config.domains)
if (domain.host === req.get('host'))
if (domain.hasOwnProperty('resolve'))
basedomain = domain.resolve
let userids = []
for(let file of files){
for (let file of files) {
file.file = basedomain + '/' + file.name
file.date = new Date(file.timestamp * 1000)
file.date = file.date.getFullYear() + '-' + (file.date.getMonth() + 1) + '-' + file.date.getDate() + ' ' + (file.date.getHours() < 10 ? '0' : '') + file.date.getHours() + ':' + (file.date.getMinutes() < 10 ? '0' : '') + file.date.getMinutes() + ':' + (file.date.getSeconds() < 10 ? '0' : '') + file.date.getSeconds()
file.date = utils.getPrettyDate(file.date) // file.date.getFullYear() + '-' + (file.date.getMonth() + 1) + '-' + file.date.getDate() + ' ' + (file.date.getHours() < 10 ? '0' : '') + file.date.getHours() + ':' + (file.date.getMinutes() < 10 ? '0' : '') + file.date.getMinutes() + ':' + (file.date.getSeconds() < 10 ? '0' : '') + file.date.getSeconds()
file.album = ''
if(file.albumid !== undefined)
for(let album of albums)
if(file.albumid === album.id)
if (file.albumid !== undefined)
for (let album of albums)
if (file.albumid === album.id)
file.album = album.name
// Only push usernames if we are root
if(user[0].username === 'root')
if(file.userid !== undefined && file.userid !== null && file.userid !== '')
if (user[0].username === 'root')
if (file.userid !== undefined && file.userid !== null && file.userid !== '')
userids.push(file.userid)
uploadsController.generateThumbs(file, basedomain)
utils.generateThumbs(file)
}
// If we are a normal user, send response
if(user[0].username !== 'root') return res.json({ success: true, files })
if (user[0].username !== 'root') return res.json({ success: true, files })
// If we are root but there are no uploads attached to a user, send response
if(userids.length === 0) return res.json({ success: true, files })
if (userids.length === 0) return res.json({ success: true, files })
db.table('users').whereIn('id', userids).then((users) => {
for(let user of users)
for(let file of files)
if(file.userid === user.id)
for (let user of users)
for (let file of files)
if (file.userid === user.id)
file.username = user.username
return res.json({ success: true, files })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
}).catch(function(error) { console.log(error); res.json({ success: false, description: 'error' }) })
})
}
uploadsController.generateThumbs = function(file, basedomain){
if(config.uploads.generateThumbnails !== true) return
let extensions = ['.jpg', '.jpeg', '.bmp', '.gif', '.png', '.webm', '.mp4']
for(let ext of extensions){
if(path.extname(file.name).toLowerCase() === ext){
let thumbname = path.join(__dirname, '..', config.uploads.folder, 'thumbs', file.name.slice(0, -ext.length) + '.png')
fs.access(thumbname, function(err) {
if (err && err.code === 'ENOENT') {
// File doesnt exist
if (ext === '.webm' || ext === '.mp4') {
ffmpeg(path.join(__dirname, '..', config.uploads.folder, file.name))
.thumbnail({
timestamps: [0],
filename: '%b.png',
folder: path.join(__dirname, '..', config.uploads.folder, 'thumbs'),
size: '200x?'
})
.on('error', function(error) {
console.log('Error - ', error.message)
})
}
else {
let size = {
width: 200,
height: 200
}
gm(path.join(__dirname, '..', config.uploads.folder, file.name))
.resize(size.width, size.height + '>')
.gravity('Center')
.extent(size.width, size.height)
.background('transparent')
.write(thumbname, function (error) {
if (error) console.log('Error - ', error)
})
}
}
})
}
}
}
module.exports = uploadsController

View File

@ -2,7 +2,7 @@ const config = require('./config.js')
const api = require('./routes/api.js')
const express = require('express')
const bodyParser = require('body-parser')
const rateLimit = require('express-rate-limit')
const RateLimit = require('express-rate-limit')
const db = require('knex')(config.database)
const fs = require('fs')
const safe = express()
@ -16,7 +16,7 @@ fs.existsSync('./' + config.uploads.folder + '/thumbs') || fs.mkdirSync('./' + c
safe.set('trust proxy', 1)
let limiter = new rateLimit({ windowMs: 5000, max: 2 })
let limiter = new RateLimit({ windowMs: 5000, max: 2 })
safe.use('/api/login/', limiter)
safe.use('/api/register/', limiter)
@ -26,24 +26,21 @@ safe.use(bodyParser.json())
safe.use('/', express.static('./uploads'))
safe.use('/', express.static('./public'))
safe.use('/api', api)
safe.get('/a/:identifier', (req, res, next) => res.sendFile('album.html', {root: './pages/'}))
safe.get('/a/:identifier', (req, res, next) => res.sendFile('album.html', { root: './pages/' }))
for(let page of config.pages){
for (let page of config.pages) {
let root = './pages/'
if(fs.existsSync(`./pages/custom/${page}.html`))
if (fs.existsSync(`./pages/custom/${page}.html`)) {
root = './pages/custom/'
if(page === 'home') safe.get('/', (req, res, next) => res.sendFile(`${page}.html`, { root: root }))
else safe.get(`/${page}`, (req, res, next) => res.sendFile(`${page}.html`, { root: root }))
}
if (page === 'home') {
safe.get('/', (req, res, next) => res.sendFile(`${page}.html`, { root: root }))
} else {
safe.get(`/${page}`, (req, res, next) => res.sendFile(`${page}.html`, { root: root }))
}
}
safe.use((req, res, next) => res.status(404).sendFile('404.html', { root: './pages/error/' }))
safe.use((req, res, next) => res.status(500).sendFile('500.html', { root: './pages/error/' }))
safe.listen(config.port, () => console.log(`loli-safe started on port ${config.port}`))
safe.prepareFrontendRoutes = function(){
}