UrlAgent.coffee 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. request = require 'request'
  2. FileWriter = require('../../infrastructure/FileWriter')
  3. _ = require "underscore"
  4. urlValidator = require 'valid-url'
  5. UrlFetchFailedError = (message) ->
  6. error = new Error(message)
  7. error.name = 'UrlFetchFailedError'
  8. error.__proto__ = UrlFetchFailedError.prototype
  9. return error
  10. UrlFetchFailedError.prototype.__proto__ = Error.prototype
  11. InvalidUrlError = (message) ->
  12. error = new Error(message)
  13. error.name = 'InvalidUrlError'
  14. error.__proto__ = InvalidUrlError.prototype
  15. return error
  16. InvalidUrlError.prototype.__proto__ = Error.prototype
  17. module.exports = UrlAgent = {
  18. UrlFetchFailedError: UrlFetchFailedError
  19. InvalidUrlError: InvalidUrlError
  20. sanitizeData: (data) ->
  21. return {
  22. url: data.url
  23. }
  24. _prependHttpIfNeeded: (url) ->
  25. if !url.match('://')
  26. url = 'http://' + url
  27. return url
  28. writeIncomingFileToDisk: (project_id, data, current_user_id, callback = (error, fsPath) ->) ->
  29. # TODO: Proxy through external API
  30. callback = _.once(callback)
  31. url = @._prependHttpIfNeeded(data.url)
  32. if !urlValidator.isWebUri(url)
  33. return callback(new InvalidUrlError())
  34. readStream = request.get(url)
  35. readStream.on "error", callback
  36. readStream.on "response", (response) ->
  37. if 200 <= response.statusCode < 300
  38. FileWriter.writeStreamToDisk project_id, readStream, callback
  39. else
  40. error = new UrlFetchFailedError()
  41. error.statusCode = response.statusCode
  42. callback(error)
  43. handleError: (error, req, res, next) ->
  44. if error instanceof UrlFetchFailedError
  45. res.status(422).send(
  46. "Your URL could not be reached (#{error.statusCode} status code). Please check it and try again."
  47. )
  48. else if error instanceof InvalidUrlError
  49. res.status(422).send(
  50. "Your URL is not valid. Please check it and try again."
  51. )
  52. else
  53. next(error)
  54. }