FileWriter.coffee 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. fs = require 'fs'
  2. logger = require 'logger-sharelatex'
  3. uuid = require 'uuid'
  4. _ = require 'underscore'
  5. Settings = require 'settings-sharelatex'
  6. request = require 'request'
  7. module.exports = FileWriter =
  8. _ensureDumpFolderExists: (callback=(error)->) ->
  9. fs.mkdir Settings.path.dumpFolder, (error) ->
  10. if error? and error.code != 'EEXIST'
  11. # Ignore error about already existing
  12. return callback(error)
  13. callback(null)
  14. writeLinesToDisk: (identifier, lines, callback = (error, fsPath)->) ->
  15. FileWriter.writeContentToDisk(identifier, lines.join('\n'), callback)
  16. writeContentToDisk: (identifier, content, callback = (error, fsPath)->) ->
  17. callback = _.once(callback)
  18. fsPath = "#{Settings.path.dumpFolder}/#{identifier}_#{uuid.v4()}"
  19. FileWriter._ensureDumpFolderExists (error) ->
  20. return callback(error) if error?
  21. fs.writeFile fsPath, content, (error) ->
  22. return callback(error) if error?
  23. callback(null, fsPath)
  24. writeStreamToDisk: (identifier, stream, callback = (error, fsPath) ->) ->
  25. callback = _.once(callback)
  26. fsPath = "#{Settings.path.dumpFolder}/#{identifier}_#{uuid.v4()}"
  27. stream.pause()
  28. FileWriter._ensureDumpFolderExists (error) ->
  29. return callback(error) if error?
  30. stream.resume()
  31. writeStream = fs.createWriteStream(fsPath)
  32. stream.pipe(writeStream)
  33. stream.on 'error', (err)->
  34. logger.err {err, identifier, fsPath}, "[writeStreamToDisk] something went wrong with incoming stream"
  35. callback(err)
  36. writeStream.on 'error', (err)->
  37. logger.err {err, identifier, fsPath}, "[writeStreamToDisk] something went wrong with writing to disk"
  38. callback(err)
  39. writeStream.on "finish", ->
  40. logger.log {identifier, fsPath}, "[writeStreamToDisk] write stream finished"
  41. callback null, fsPath
  42. writeUrlToDisk: (identifier, url, callback = (error, fsPath) ->) ->
  43. callback = _.once(callback)
  44. stream = request.get(url)
  45. stream.on 'response', (response) ->
  46. if 200 <= response.statusCode < 300
  47. FileWriter.writeStreamToDisk identifier, stream, callback
  48. else
  49. err = new Error("bad response from url: #{response.statusCode}")
  50. logger.err {err, identifier, url}, err.message
  51. callback(err)