FileConverter.coffee 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. _ = require("underscore")
  2. metrics = require("metrics-sharelatex")
  3. logger = require("logger-sharelatex")
  4. safe_exec = require("./SafeExec")
  5. approvedFormats = ["png"]
  6. fourtySeconds = 40 * 1000
  7. childProcessOpts =
  8. killSignal: "SIGTERM"
  9. timeout: fourtySeconds
  10. module.exports =
  11. convert: (sourcePath, requestedFormat, callback)->
  12. logger.log sourcePath:sourcePath, requestedFormat:requestedFormat, "converting file format"
  13. timer = new metrics.Timer("imageConvert")
  14. destPath = "#{sourcePath}.#{requestedFormat}"
  15. sourcePath = "#{sourcePath}[0]"
  16. if !_.include approvedFormats, requestedFormat
  17. err = new Error("invalid format requested")
  18. return callback err
  19. width = "600x"
  20. args = "nice convert -define pdf:fit-page=#{width} -flatten -density 300 #{sourcePath} #{destPath}"
  21. safe_exec args, childProcessOpts, (err, stdout, stderr)->
  22. timer.done()
  23. if err?
  24. logger.err err:err, stderr:stderr, sourcePath:sourcePath, requestedFormat:requestedFormat, destPath:destPath, "something went wrong converting file"
  25. else
  26. logger.log sourcePath:sourcePath, requestedFormat:requestedFormat, destPath:destPath, "finished converting file"
  27. callback(err, destPath)
  28. thumbnail: (sourcePath, callback)->
  29. logger.log sourcePath:sourcePath, "thumbnail convert file"
  30. destPath = "#{sourcePath}.png"
  31. sourcePath = "#{sourcePath}[0]"
  32. width = "260x"
  33. args = "nice convert -flatten -background white -density 300 -define pdf:fit-page=#{width} #{sourcePath} -resize #{width} #{destPath}"
  34. safe_exec args, childProcessOpts, (err, stdout, stderr)->
  35. if err?
  36. logger.err err:err, stderr:stderr, sourcePath:sourcePath, "something went wrong converting file to thumbnail"
  37. else
  38. logger.log sourcePath:sourcePath, destPath:destPath, "finished thumbnailing file"
  39. callback(err, destPath)
  40. preview: (sourcePath, callback)->
  41. logger.log sourcePath:sourcePath, "preview convert file"
  42. destPath = "#{sourcePath}.png"
  43. sourcePath = "#{sourcePath}[0]"
  44. width = "548x"
  45. args = "nice convert -flatten -background white -density 300 -define pdf:fit-page=#{width} #{sourcePath} -resize #{width} #{destPath}"
  46. safe_exec args, childProcessOpts, (err, stdout, stderr)->
  47. if err?
  48. logger.err err:err, stderr:stderr, sourcePath:sourcePath, destPath:destPath, "something went wrong converting file to preview"
  49. else
  50. logger.log sourcePath:sourcePath, destPath:destPath, "finished converting file to preview"
  51. callback(err, destPath)