2018-03-18 02:14:50 +01:00
|
|
|
'use strict'
|
2020-05-31 00:41:01 +08:00
|
|
|
|
2021-06-12 05:23:22 +08:00
|
|
|
import * as fs from "fs";
|
|
|
|
import * as path from "path";
|
|
|
|
import * as crypto from "crypto";
|
|
|
|
import {URL} from "url";
|
2018-03-18 02:14:50 +01:00
|
|
|
|
2021-06-12 05:23:22 +08:00
|
|
|
import * as config from "../config";
|
|
|
|
import * as logger from "../logger";
|
2018-03-18 02:14:50 +01:00
|
|
|
|
2020-05-31 00:41:01 +08:00
|
|
|
/**
|
|
|
|
* generate a random filename for uploaded image
|
|
|
|
*/
|
2021-06-12 05:23:22 +08:00
|
|
|
function randomFilename() {
|
2020-05-31 00:41:01 +08:00
|
|
|
const buf = crypto.randomBytes(16)
|
|
|
|
return `upload_${buf.toString('hex')}`
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* pick a filename not exist in filesystem
|
|
|
|
* maximum attempt 5 times
|
|
|
|
*/
|
2021-06-12 05:23:22 +08:00
|
|
|
function pickFilename(defaultFilename) {
|
2020-05-31 00:41:01 +08:00
|
|
|
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.')
|
|
|
|
}
|
|
|
|
|
2021-06-12 05:23:22 +08:00
|
|
|
export function uploadImage(imagePath, callback) {
|
2018-03-18 02:14:50 +01:00
|
|
|
if (!imagePath || typeof imagePath !== 'string') {
|
|
|
|
callback(new Error('Image path is missing or wrong'), null)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!callback || typeof callback !== 'function') {
|
2018-06-01 13:01:57 +02:00
|
|
|
logger.error('Callback has to be a function')
|
2018-03-18 02:14:50 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-05-31 00:41:01 +08: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 19:10:46 +09:00
|
|
|
let url
|
|
|
|
try {
|
2020-05-31 00:41:01 +08:00
|
|
|
url = (new URL(filename, config.serverURL + '/uploads/')).href
|
2019-04-18 19:10:46 +09:00
|
|
|
} catch (e) {
|
2020-05-31 00:41:01 +08:00
|
|
|
url = config.serverURL + '/uploads/' + filename
|
2019-04-18 19:10:46 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
callback(null, url)
|
2018-03-18 02:14:50 +01:00
|
|
|
}
|