2019-05-29 05:21:06 -04:00
|
|
|
const request = require('request')
|
|
|
|
const _ = require('underscore')
|
|
|
|
const urlValidator = require('valid-url')
|
|
|
|
const { InvalidUrlError, UrlFetchFailedError } = require('./LinkedFilesErrors')
|
|
|
|
const LinkedFilesHandler = require('./LinkedFilesHandler')
|
|
|
|
const UrlHelper = require('../Helpers/UrlHelper')
|
|
|
|
|
2021-09-22 08:32:16 -04:00
|
|
|
function createLinkedFile(
|
|
|
|
projectId,
|
|
|
|
linkedFileData,
|
|
|
|
name,
|
|
|
|
parentFolderId,
|
|
|
|
userId,
|
|
|
|
callback
|
|
|
|
) {
|
|
|
|
linkedFileData = _sanitizeData(linkedFileData)
|
|
|
|
_getUrlStream(projectId, linkedFileData, userId, (err, readStream) => {
|
|
|
|
if (err) {
|
|
|
|
return callback(err)
|
|
|
|
}
|
|
|
|
readStream.on('error', callback)
|
|
|
|
readStream.on('response', response => {
|
|
|
|
if (response.statusCode >= 200 && response.statusCode < 300) {
|
|
|
|
LinkedFilesHandler.importFromStream(
|
|
|
|
projectId,
|
|
|
|
readStream,
|
|
|
|
linkedFileData,
|
|
|
|
name,
|
|
|
|
parentFolderId,
|
|
|
|
userId,
|
|
|
|
(err, file) => {
|
|
|
|
if (err) {
|
|
|
|
return callback(err)
|
|
|
|
}
|
|
|
|
callback(null, file._id)
|
2021-04-14 09:17:21 -04:00
|
|
|
}
|
2021-09-22 08:32:16 -04:00
|
|
|
) // Created
|
|
|
|
} else {
|
|
|
|
const error = new UrlFetchFailedError(
|
|
|
|
`url fetch failed: ${linkedFileData.url}`
|
|
|
|
)
|
|
|
|
error.statusCode = response.statusCode
|
|
|
|
callback(error)
|
2021-04-14 09:17:21 -04:00
|
|
|
}
|
2021-09-22 08:32:16 -04:00
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
2019-05-29 05:21:06 -04:00
|
|
|
|
2021-09-22 08:32:16 -04:00
|
|
|
function refreshLinkedFile(
|
|
|
|
projectId,
|
|
|
|
linkedFileData,
|
|
|
|
name,
|
|
|
|
parentFolderId,
|
|
|
|
userId,
|
|
|
|
callback
|
|
|
|
) {
|
|
|
|
createLinkedFile(
|
|
|
|
projectId,
|
2019-05-29 05:21:06 -04:00
|
|
|
linkedFileData,
|
|
|
|
name,
|
2021-09-22 08:32:16 -04:00
|
|
|
parentFolderId,
|
|
|
|
userId,
|
2019-05-29 05:21:06 -04:00
|
|
|
callback
|
2021-09-22 08:32:16 -04:00
|
|
|
)
|
|
|
|
}
|
2019-05-29 05:21:06 -04:00
|
|
|
|
2021-09-22 08:32:16 -04:00
|
|
|
function _sanitizeData(data) {
|
|
|
|
return {
|
|
|
|
provider: data.provider,
|
|
|
|
url: UrlHelper.prependHttpIfNeeded(data.url),
|
|
|
|
}
|
|
|
|
}
|
2019-05-29 05:21:06 -04:00
|
|
|
|
2021-09-22 08:32:16 -04:00
|
|
|
function _getUrlStream(projectId, data, currentUserId, callback) {
|
|
|
|
callback = _.once(callback)
|
|
|
|
let { url } = data
|
|
|
|
if (!urlValidator.isWebUri(url)) {
|
|
|
|
return callback(new InvalidUrlError(`invalid url: ${url}`))
|
|
|
|
}
|
|
|
|
url = UrlHelper.wrapUrlWithProxy(url)
|
|
|
|
const readStream = request.get(url)
|
|
|
|
readStream.pause()
|
|
|
|
callback(null, readStream)
|
2019-05-29 05:21:06 -04:00
|
|
|
}
|
2021-09-22 08:32:16 -04:00
|
|
|
|
|
|
|
module.exports = { createLinkedFile, refreshLinkedFile }
|