2015-02-24 10:48:34 -05:00
|
|
|
fs = require "fs"
|
|
|
|
Path = require "path"
|
|
|
|
spawn = require("child_process").spawn
|
|
|
|
logger = require "logger-sharelatex"
|
2015-02-27 11:07:02 -05:00
|
|
|
_ = require "underscore"
|
2015-02-24 10:48:34 -05:00
|
|
|
|
|
|
|
module.exports = OutputFileOptimiser =
|
|
|
|
|
|
|
|
optimiseFile: (src, dst, callback = (error) ->) ->
|
2015-02-27 08:15:28 -05:00
|
|
|
# check output file (src) and see if we can optimise it, storing
|
|
|
|
# the result in the build directory (dst)
|
2015-02-24 10:48:34 -05:00
|
|
|
if src.match(/\.pdf$/)
|
|
|
|
OutputFileOptimiser.optimisePDF src, dst, callback
|
|
|
|
else
|
|
|
|
callback (null)
|
|
|
|
|
|
|
|
optimisePDF: (src, dst, callback = (error) ->) ->
|
|
|
|
tmpOutput = dst + '.opt'
|
|
|
|
args = ["--linearize", src, tmpOutput]
|
|
|
|
logger.log args: args, "running qpdf command"
|
|
|
|
|
|
|
|
proc = spawn("qpdf", args)
|
|
|
|
stdout = ""
|
|
|
|
proc.stdout.on "data", (chunk) ->
|
2015-02-27 08:15:28 -05:00
|
|
|
stdout += chunk.toString()
|
2015-02-27 11:07:02 -05:00
|
|
|
callback = _.once(callback) # avoid double call back for error and close event
|
|
|
|
proc.on "error", (err) ->
|
|
|
|
logger.warn {err, args}, "qpdf failed"
|
|
|
|
callback(null) # ignore the error
|
2015-02-24 10:48:34 -05:00
|
|
|
proc.on "close", (code) ->
|
|
|
|
if code != 0
|
2015-02-27 11:07:02 -05:00
|
|
|
logger.warn {code, args}, "qpdf returned error"
|
|
|
|
return callback(null) # ignore the error
|
2015-02-24 10:48:34 -05:00
|
|
|
fs.rename tmpOutput, dst, (err) ->
|
2015-02-27 08:15:28 -05:00
|
|
|
if err?
|
|
|
|
logger.warn {tmpOutput, dst}, "failed to rename output of qpdf command"
|
2015-02-27 11:07:02 -05:00
|
|
|
callback(null) # ignore the error
|