mirror of https://github.com/requarks/wiki
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
282 lines
8.1 KiB
282 lines
8.1 KiB
8 years ago
|
'use strict'
|
||
8 years ago
|
|
||
7 years ago
|
/* global wiki */
|
||
8 years ago
|
|
||
8 years ago
|
const path = require('path')
|
||
|
const Promise = require('bluebird')
|
||
|
const fs = Promise.promisifyAll(require('fs-extra'))
|
||
|
const request = require('request')
|
||
|
const url = require('url')
|
||
8 years ago
|
const crypto = require('crypto')
|
||
8 years ago
|
const _ = require('lodash')
|
||
8 years ago
|
|
||
8 years ago
|
var regFolderName = new RegExp('^[a-z0-9][a-z0-9-]*[a-z0-9]$')
|
||
|
const maxDownloadFileSize = 3145728 // 3 MB
|
||
8 years ago
|
|
||
|
/**
|
||
|
* Uploads
|
||
|
*/
|
||
|
module.exports = {
|
||
|
|
||
8 years ago
|
_uploadsPath: './repo/uploads',
|
||
|
_uploadsThumbsPath: './data/thumbs',
|
||
|
|
||
|
/**
|
||
|
* Initialize Local Data Storage model
|
||
|
*
|
||
|
* @return {Object} Uploads model instance
|
||
|
*/
|
||
|
init () {
|
||
7 years ago
|
this._uploadsPath = path.resolve(wiki.ROOTPATH, wiki.config.paths.repo, 'uploads')
|
||
|
this._uploadsThumbsPath = path.resolve(wiki.ROOTPATH, wiki.config.paths.data, 'thumbs')
|
||
8 years ago
|
|
||
|
return this
|
||
|
},
|
||
|
|
||
|
/**
|
||
|
* Gets the thumbnails folder path.
|
||
|
*
|
||
|
* @return {String} The thumbs path.
|
||
|
*/
|
||
|
getThumbsPath () {
|
||
|
return this._uploadsThumbsPath
|
||
|
},
|
||
|
|
||
|
/**
|
||
|
* Gets the uploads folders.
|
||
|
*
|
||
|
* @return {Array<String>} The uploads folders.
|
||
|
*/
|
||
|
getUploadsFolders () {
|
||
7 years ago
|
return wiki.db.Folder.find({}, 'name').sort('name').exec().then((results) => {
|
||
8 years ago
|
return (results) ? _.map(results, 'name') : [{ name: '' }]
|
||
|
})
|
||
|
},
|
||
|
|
||
|
/**
|
||
|
* Creates an uploads folder.
|
||
|
*
|
||
|
* @param {String} folderName The folder name
|
||
|
* @return {Promise} Promise of the operation
|
||
|
*/
|
||
|
createUploadsFolder (folderName) {
|
||
|
let self = this
|
||
|
|
||
|
folderName = _.kebabCase(_.trim(folderName))
|
||
|
|
||
|
if (_.isEmpty(folderName) || !regFolderName.test(folderName)) {
|
||
|
return Promise.resolve(self.getUploadsFolders())
|
||
|
}
|
||
|
|
||
|
return fs.ensureDirAsync(path.join(self._uploadsPath, folderName)).then(() => {
|
||
7 years ago
|
return wiki.db.UplFolder.findOneAndUpdate({
|
||
8 years ago
|
_id: 'f:' + folderName
|
||
|
}, {
|
||
|
name: folderName
|
||
|
}, {
|
||
|
upsert: true
|
||
|
})
|
||
|
}).then(() => {
|
||
|
return self.getUploadsFolders()
|
||
|
})
|
||
|
},
|
||
|
|
||
|
/**
|
||
|
* Check if folder is valid and exists
|
||
|
*
|
||
|
* @param {String} folderName The folder name
|
||
|
* @return {Boolean} True if valid
|
||
|
*/
|
||
|
validateUploadsFolder (folderName) {
|
||
7 years ago
|
return wiki.db.UplFolder.findOne({ name: folderName }).then((f) => {
|
||
8 years ago
|
return (f) ? path.resolve(this._uploadsPath, folderName) : false
|
||
|
})
|
||
|
},
|
||
|
|
||
|
/**
|
||
|
* Adds one or more uploads files.
|
||
|
*
|
||
|
* @param {Array<Object>} arrFiles The uploads files
|
||
|
* @return {Void} Void
|
||
|
*/
|
||
|
addUploadsFiles (arrFiles) {
|
||
|
if (_.isArray(arrFiles) || _.isPlainObject(arrFiles)) {
|
||
7 years ago
|
// this._uploadswiki.Db.Files.insert(arrFiles);
|
||
8 years ago
|
}
|
||
|
},
|
||
|
|
||
|
/**
|
||
|
* Gets the uploads files.
|
||
|
*
|
||
|
* @param {String} cat Category type
|
||
|
* @param {String} fld Folder
|
||
|
* @return {Array<Object>} The files matching the query
|
||
|
*/
|
||
|
getUploadsFiles (cat, fld) {
|
||
7 years ago
|
return wiki.db.UplFile.find({
|
||
8 years ago
|
category: cat,
|
||
|
folder: 'f:' + fld
|
||
|
}).sort('filename').exec()
|
||
|
},
|
||
|
|
||
|
/**
|
||
|
* Deletes an uploads file.
|
||
|
*
|
||
|
* @param {string} uid The file unique ID
|
||
|
* @return {Promise} Promise of the operation
|
||
|
*/
|
||
|
deleteUploadsFile (uid) {
|
||
|
let self = this
|
||
|
|
||
7 years ago
|
return wiki.db.UplFile.findOneAndRemove({ _id: uid }).then((f) => {
|
||
8 years ago
|
if (f) {
|
||
|
return self.deleteUploadsFileTry(f, 0)
|
||
|
}
|
||
|
return true
|
||
|
})
|
||
|
},
|
||
|
|
||
|
deleteUploadsFileTry (f, attempt) {
|
||
|
let self = this
|
||
|
|
||
|
let fFolder = (f.folder && f.folder !== 'f:') ? f.folder.slice(2) : './'
|
||
|
|
||
|
return Promise.join(
|
||
|
fs.removeAsync(path.join(self._uploadsThumbsPath, f._id + '.png')),
|
||
|
fs.removeAsync(path.resolve(self._uploadsPath, fFolder, f.filename))
|
||
|
).catch((err) => {
|
||
|
if (err.code === 'EBUSY' && attempt < 5) {
|
||
|
return Promise.delay(100).then(() => {
|
||
|
return self.deleteUploadsFileTry(f, attempt + 1)
|
||
|
})
|
||
|
} else {
|
||
7 years ago
|
wiki.logger.warn('Unable to delete uploads file ' + f.filename + '. File is locked by another process and multiple attempts failed.')
|
||
8 years ago
|
return true
|
||
|
}
|
||
|
})
|
||
|
},
|
||
|
|
||
|
/**
|
||
|
* Downloads a file from url.
|
||
|
*
|
||
|
* @param {String} fFolder The folder
|
||
|
* @param {String} fUrl The full URL
|
||
|
* @return {Promise} Promise of the operation
|
||
|
*/
|
||
|
downloadFromUrl (fFolder, fUrl) {
|
||
|
let fUrlObj = url.parse(fUrl)
|
||
|
let fUrlFilename = _.last(_.split(fUrlObj.pathname, '/'))
|
||
|
let destFolder = _.chain(fFolder).trim().toLower().value()
|
||
|
|
||
7 years ago
|
return wiki.upl.validateUploadsFolder(destFolder).then((destFolderPath) => {
|
||
8 years ago
|
if (!destFolderPath) {
|
||
7 years ago
|
return Promise.reject(new Error(wiki.lang.t('errors:invalidfolder')))
|
||
8 years ago
|
}
|
||
|
|
||
7 years ago
|
return wiki.disk.validateUploadsFilename(fUrlFilename, destFolder).then((destFilename) => {
|
||
8 years ago
|
let destFilePath = path.resolve(destFolderPath, destFilename)
|
||
|
|
||
|
return new Promise((resolve, reject) => {
|
||
|
let rq = request({
|
||
|
url: fUrl,
|
||
|
method: 'GET',
|
||
|
followRedirect: true,
|
||
|
maxRedirects: 5,
|
||
|
timeout: 10000
|
||
|
})
|
||
|
|
||
|
let destFileStream = fs.createWriteStream(destFilePath)
|
||
|
let curFileSize = 0
|
||
|
|
||
|
rq.on('data', (data) => {
|
||
|
curFileSize += data.length
|
||
|
if (curFileSize > maxDownloadFileSize) {
|
||
|
rq.abort()
|
||
|
destFileStream.destroy()
|
||
|
fs.remove(destFilePath)
|
||
7 years ago
|
reject(new Error(wiki.lang.t('errors:remotetoolarge')))
|
||
8 years ago
|
}
|
||
|
}).on('error', (err) => {
|
||
|
destFileStream.destroy()
|
||
|
fs.remove(destFilePath)
|
||
|
reject(err)
|
||
|
})
|
||
|
|
||
|
destFileStream.on('finish', () => {
|
||
|
resolve(true)
|
||
|
})
|
||
|
|
||
|
rq.pipe(destFileStream)
|
||
|
})
|
||
|
})
|
||
|
})
|
||
|
},
|
||
|
|
||
|
/**
|
||
|
* Move/Rename a file
|
||
|
*
|
||
|
* @param {String} uid The file ID
|
||
|
* @param {String} fld The destination folder
|
||
|
* @param {String} nFilename The new filename (optional)
|
||
|
* @return {Promise} Promise of the operation
|
||
|
*/
|
||
|
moveUploadsFile (uid, fld, nFilename) {
|
||
|
let self = this
|
||
|
|
||
7 years ago
|
return wiki.db.UplFolder.finwiki.dById('f:' + fld).then((folder) => {
|
||
8 years ago
|
if (folder) {
|
||
7 years ago
|
return wiki.db.UplFile.finwiki.dById(uid).then((originFile) => {
|
||
8 years ago
|
// -> Check if rename is valid
|
||
|
|
||
|
let nameCheck = null
|
||
|
if (nFilename) {
|
||
|
let originFileObj = path.parse(originFile.filename)
|
||
7 years ago
|
nameCheck = wiki.disk.validateUploadsFilename(nFilename + originFileObj.ext, folder.name)
|
||
8 years ago
|
} else {
|
||
|
nameCheck = Promise.resolve(originFile.filename)
|
||
|
}
|
||
|
|
||
|
return nameCheck.then((destFilename) => {
|
||
|
let originFolder = (originFile.folder && originFile.folder !== 'f:') ? originFile.folder.slice(2) : './'
|
||
|
let sourceFilePath = path.resolve(self._uploadsPath, originFolder, originFile.filename)
|
||
|
let destFilePath = path.resolve(self._uploadsPath, folder.name, destFilename)
|
||
|
let preMoveOps = []
|
||
|
|
||
|
// -> Check for invalid operations
|
||
|
|
||
|
if (sourceFilePath === destFilePath) {
|
||
7 years ago
|
return Promise.reject(new Error(wiki.lang.t('errors:invalidoperation')))
|
||
8 years ago
|
}
|
||
|
|
||
7 years ago
|
// -> Delete wiki.DB entry
|
||
8 years ago
|
|
||
7 years ago
|
preMoveOps.push(wiki.db.UplFile.finwiki.dByIdAndRemove(uid))
|
||
8 years ago
|
|
||
|
// -> Move thumbnail ahead to avoid re-generation
|
||
|
|
||
|
if (originFile.category === 'image') {
|
||
8 years ago
|
let fUid = crypto.createHash('md5').update(folder.name + '/' + destFilename).digest('hex')
|
||
8 years ago
|
let sourceThumbPath = path.resolve(self._uploadsThumbsPath, originFile._id + '.png')
|
||
|
let destThumbPath = path.resolve(self._uploadsThumbsPath, fUid + '.png')
|
||
|
preMoveOps.push(fs.moveAsync(sourceThumbPath, destThumbPath))
|
||
|
} else {
|
||
|
preMoveOps.push(Promise.resolve(true))
|
||
|
}
|
||
|
|
||
|
// -> Proceed to move actual file
|
||
|
|
||
|
return Promise.all(preMoveOps).then(() => {
|
||
|
return fs.moveAsync(sourceFilePath, destFilePath, {
|
||
|
clobber: false
|
||
|
})
|
||
|
})
|
||
|
})
|
||
|
})
|
||
|
} else {
|
||
7 years ago
|
return Promise.reject(new Error(wiki.lang.t('errors:invaliddestfolder')))
|
||
8 years ago
|
}
|
||
|
})
|
||
|
}
|
||
|
|
||
|
}
|