2018-03-18 01:14:50 +00:00
|
|
|
'use strict'
|
2020-05-30 16:41:01 +00:00
|
|
|
|
|
|
|
const crypto = require('crypto')
|
|
|
|
const fs = require('fs')
|
2018-12-18 13:52:09 +00:00
|
|
|
const URL = require('url').URL
|
2018-09-26 18:40:28 +00:00
|
|
|
const path = require('path')
|
2018-03-18 01:14:50 +00:00
|
|
|
|
2020-01-04 22:30:23 +00:00
|
|
|
const config = require('../config')
|
|
|
|
const logger = require('../logger')
|
2018-03-18 01:14:50 +00:00
|
|
|
|
2020-05-30 16:41:01 +00:00
|
|
|
/**
|
|
|
|
* generate a random filename for uploaded image
|
|
|
|
*/
|
|
|
|
function randomFilename () {
|
|
|
|
const buf = crypto.randomBytes(16)
|
|
|
|
return `upload_${buf.toString('hex')}`
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* pick a filename not exist in filesystem
|
|
|
|
* maximum attempt 5 times
|
|
|
|
*/
|
|
|
|
function pickFilename (defaultFilename) {
|
|
|
|
let retryCounter = 5
|
|
|
|
let filename = defaultFilename
|
|
|
|
const extname = path.extname(defaultFilename)
|
|
|
|
while (retryCounter-- > 0) {
|
|
|
|
if (fs.existsSync(path.join(config.uploadsPath, filename))) {
|
|
|
|
filename = `${randomFilename()}${extname}`
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
return filename
|
|
|
|
}
|
|
|
|
throw new Error('file exists.')
|
|
|
|
}
|
|
|
|
|
2018-03-18 01:14:50 +00:00
|
|
|
exports.uploadImage = function (imagePath, callback) {
|
|
|
|
if (!imagePath || typeof imagePath !== 'string') {
|
|
|
|
callback(new Error('Image path is missing or wrong'), null)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!callback || typeof callback !== 'function') {
|
2018-06-01 11:01:57 +00:00
|
|
|
logger.error('Callback has to be a function')
|
2018-03-18 01:14:50 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-05-30 16:41:01 +00:00
|
|
|
let filename = path.basename(imagePath)
|
|
|
|
try {
|
|
|
|
filename = pickFilename(path.basename(imagePath))
|
|
|
|
} catch (e) {
|
|
|
|
return callback(e, null)
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
fs.copyFileSync(imagePath, path.join(config.uploadsPath, filename))
|
|
|
|
} catch (e) {
|
|
|
|
return callback(e, null)
|
|
|
|
}
|
|
|
|
|
2019-04-18 10:10:46 +00:00
|
|
|
let url
|
|
|
|
try {
|
2020-05-30 16:41:01 +00:00
|
|
|
url = (new URL(filename, config.serverURL + '/uploads/')).href
|
2019-04-18 10:10:46 +00:00
|
|
|
} catch (e) {
|
2020-05-30 16:41:01 +00:00
|
|
|
url = config.serverURL + '/uploads/' + filename
|
2019-04-18 10:10:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
callback(null, url)
|
2018-03-18 01:14:50 +00:00
|
|
|
}
|