FileConverter.coffee 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. _ = require("underscore")
  2. metrics = require("metrics-sharelatex")
  3. logger = require("logger-sharelatex")
  4. exec = require('child_process').exec
  5. approvedFormats = ["png"]
  6. fourtySeconds = 40 * 1000
  7. childProcessOpts =
  8. killSignal: "SIGKILL"
  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. console.log args
  22. exec args, childProcessOpts, (err, stdout, stderr)->
  23. timer.done()
  24. if err?
  25. logger.err err:err, stderr:stderr, sourcePath:sourcePath, requestedFormat:requestedFormat, destPath:destPath, "something went wrong converting file"
  26. else
  27. logger.log sourcePath:sourcePath, requestedFormat:requestedFormat, destPath:destPath, "finished converting file"
  28. callback(err, destPath)
  29. thumbnail: (sourcePath, callback)->
  30. logger.log sourcePath:sourcePath, "thumbnail convert file"
  31. destPath = "#{sourcePath}.png"
  32. sourcePath = "#{sourcePath}[0]"
  33. width = "260x"
  34. args = "nice convert -flatten -background white -density 300 -define pdf:fit-page=#{width} #{sourcePath} -resize #{width} #{destPath}"
  35. exec args, childProcessOpts, (err, stdout, stderr)->
  36. if err?
  37. logger.err err:err, stderr:stderr, sourcePath:sourcePath, "something went wrong converting file to preview"
  38. else
  39. logger.log sourcePath:sourcePath, destPath:destPath, "finished thumbnailing file"
  40. callback(err, destPath)
  41. preview: (sourcePath, callback)->
  42. logger.log sourcePath:sourcePath, "preview convert file"
  43. destPath = "#{sourcePath}.png"
  44. sourcePath = "#{sourcePath}[0]"
  45. width = "548x"
  46. args = "nice convert -flatten -background white -density 300 -define pdf:fit-page=#{width} #{sourcePath} -resize #{width} #{destPath}"
  47. exec args, childProcessOpts, (err, stdout, stderr)->
  48. if err?
  49. logger.err err:err, stderr:stderr, sourcePath:sourcePath, destPath:destPath, "something went wrong converting file to preview"
  50. else
  51. logger.log sourcePath:sourcePath, destPath:destPath, "finished converting file to preview"
  52. callback(err, destPath)