OutputFileOptimiser.coffee 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. fs = require "fs"
  2. Path = require "path"
  3. spawn = require("child_process").spawn
  4. logger = require "logger-sharelatex"
  5. Metrics = require "./Metrics"
  6. _ = require "underscore"
  7. module.exports = OutputFileOptimiser =
  8. optimiseFile: (src, dst, callback = (error) ->) ->
  9. # check output file (src) and see if we can optimise it, storing
  10. # the result in the build directory (dst)
  11. if src.match(/\/output\.pdf$/)
  12. OutputFileOptimiser.checkIfPDFIsOptimised src, (err, isOptimised) ->
  13. return callback(null) if err? or isOptimised
  14. OutputFileOptimiser.optimisePDF src, dst, callback
  15. else
  16. callback (null)
  17. checkIfPDFIsOptimised: (file, callback) ->
  18. SIZE = 16*1024 # check the header of the pdf
  19. result = new Buffer(SIZE)
  20. result.fill(0) # prevent leakage of uninitialised buffer
  21. fs.open file, "r", (err, fd) ->
  22. return callback(err) if err?
  23. fs.read fd, result, 0, SIZE, 0, (errRead, bytesRead, buffer) ->
  24. fs.close fd, (errClose) ->
  25. return callback(errRead) if errRead?
  26. return callback(errClose) if errReadClose?
  27. isOptimised = buffer.toString('ascii').indexOf("/Linearized 1") >= 0
  28. callback(null, isOptimised)
  29. optimisePDF: (src, dst, callback = (error) ->) ->
  30. tmpOutput = dst + '.opt'
  31. args = ["--linearize", src, tmpOutput]
  32. logger.log args: args, "running qpdf command"
  33. timer = new Metrics.Timer("qpdf")
  34. proc = spawn("qpdf", args)
  35. stdout = ""
  36. proc.stdout.on "data", (chunk) ->
  37. stdout += chunk.toString()
  38. callback = _.once(callback) # avoid double call back for error and close event
  39. proc.on "error", (err) ->
  40. logger.warn {err, args}, "qpdf failed"
  41. callback(null) # ignore the error
  42. proc.on "close", (code) ->
  43. timer.done()
  44. if code != 0
  45. logger.warn {code, args}, "qpdf returned error"
  46. return callback(null) # ignore the error
  47. fs.rename tmpOutput, dst, (err) ->
  48. if err?
  49. logger.warn {tmpOutput, dst}, "failed to rename output of qpdf command"
  50. callback(null) # ignore the error