2018-03-17 21:14:50 -04:00
|
|
|
'use strict'
|
|
|
|
const config = require('../../config')
|
|
|
|
const logger = require('../../logger')
|
2021-04-19 06:31:14 -04:00
|
|
|
const fs = require('fs')
|
|
|
|
const fetch = require('node-fetch')
|
2018-03-17 21:14:50 -04:00
|
|
|
|
|
|
|
exports.uploadImage = function (imagePath, callback) {
|
2019-06-08 14:51:24 -04:00
|
|
|
if (!callback || typeof callback !== 'function') {
|
|
|
|
logger.error('Callback has to be a function')
|
2018-03-17 21:14:50 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-06-08 14:51:24 -04:00
|
|
|
if (!imagePath || typeof imagePath !== 'string') {
|
|
|
|
callback(new Error('Image path is missing or wrong'), null)
|
2018-03-17 21:14:50 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-04-19 06:31:14 -04:00
|
|
|
// The following client ID is for use with HedgeDoc only
|
|
|
|
const clientId = config.imgur.clientID || '032aa2f687790cd'
|
|
|
|
|
|
|
|
const buffer = fs.readFileSync(imagePath)
|
|
|
|
|
|
|
|
const params = new URLSearchParams()
|
|
|
|
params.append('image', buffer.toString('base64'))
|
|
|
|
params.append('type', 'base64')
|
|
|
|
fetch('https://api.imgur.com/3/image', {
|
|
|
|
method: 'POST',
|
|
|
|
body: params,
|
|
|
|
headers: { Authorization: `Client-ID ${clientId}` }
|
|
|
|
})
|
|
|
|
.then((res) => {
|
|
|
|
if (!res.ok) {
|
|
|
|
callback(new Error(res.statusText), null)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
return res.json()
|
|
|
|
})
|
|
|
|
.then((json) => {
|
2019-06-08 14:51:24 -04:00
|
|
|
logger.debug(`SERVER uploadimage success: ${JSON.stringify(json)}`)
|
2019-05-30 18:27:56 -04:00
|
|
|
callback(null, json.data.link.replace(/^http:\/\//i, 'https://'))
|
2021-04-19 06:31:14 -04:00
|
|
|
}).catch((err) => {
|
2019-05-30 18:27:56 -04:00
|
|
|
callback(new Error(err), null)
|
|
|
|
})
|
2018-03-17 21:14:50 -04:00
|
|
|
}
|