CompileController.coffee 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. Metrics = require "metrics-sharelatex"
  2. Project = require("../../models/Project").Project
  3. CompileManager = require("./CompileManager")
  4. ClsiManager = require("./ClsiManager")
  5. logger = require "logger-sharelatex"
  6. request = require "request"
  7. Settings = require "settings-sharelatex"
  8. AuthenticationController = require "../Authentication/AuthenticationController"
  9. UserGetter = require "../User/UserGetter"
  10. RateLimiter = require("../../infrastructure/RateLimiter")
  11. ClsiCookieManager = require("./ClsiCookieManager")
  12. Path = require("path")
  13. module.exports = CompileController =
  14. compile: (req, res, next = (error) ->) ->
  15. res.setTimeout(5 * 60 * 1000)
  16. project_id = req.params.Project_id
  17. isAutoCompile = !!req.query?.auto_compile
  18. user_id = AuthenticationController.getLoggedInUserId req
  19. options = {
  20. isAutoCompile: isAutoCompile
  21. }
  22. if req.body?.rootDoc_id?
  23. options.rootDoc_id = req.body.rootDoc_id
  24. else if req.body?.settingsOverride?.rootDoc_id? # Can be removed after deploy
  25. options.rootDoc_id = req.body.settingsOverride.rootDoc_id
  26. if req.body?.compiler
  27. options.compiler = req.body.compiler
  28. if req.body?.draft
  29. options.draft = req.body.draft
  30. if req.body?.check in ['validate', 'error', 'silent']
  31. options.check = req.body.check
  32. logger.log {options:options, project_id:project_id, user_id:user_id}, "got compile request"
  33. CompileManager.compile project_id, user_id, options, (error, status, outputFiles, clsiServerId, limits, validationProblems) ->
  34. return next(error) if error?
  35. res.contentType("application/json")
  36. res.status(200).send JSON.stringify {
  37. status: status
  38. outputFiles: outputFiles
  39. compileGroup: limits?.compileGroup
  40. clsiServerId:clsiServerId
  41. validationProblems:validationProblems
  42. }
  43. stopCompile: (req, res, next = (error) ->) ->
  44. project_id = req.params.Project_id
  45. user_id = AuthenticationController.getLoggedInUserId req
  46. logger.log {project_id:project_id, user_id:user_id}, "stop compile request"
  47. CompileManager.stopCompile project_id, user_id, (error) ->
  48. return next(error) if error?
  49. res.status(200).send()
  50. _compileAsUser: (req, callback) ->
  51. # callback with user_id if per-user, undefined otherwise
  52. if not Settings.disablePerUserCompiles
  53. user_id = AuthenticationController.getLoggedInUserId req
  54. return callback(null, user_id)
  55. else
  56. callback() # do a per-project compile, not per-user
  57. _downloadAsUser: (req, callback) ->
  58. # callback with user_id if per-user, undefined otherwise
  59. if not Settings.disablePerUserCompiles
  60. user_id = AuthenticationController.getLoggedInUserId req
  61. return callback(null, user_id)
  62. else
  63. callback() # do a per-project compile, not per-user
  64. downloadPdf: (req, res, next = (error) ->)->
  65. Metrics.inc "pdf-downloads"
  66. project_id = req.params.Project_id
  67. isPdfjsPartialDownload = req.query?.pdfng
  68. rateLimit = (callback)->
  69. if isPdfjsPartialDownload
  70. callback null, true
  71. else
  72. rateLimitOpts =
  73. endpointName: "full-pdf-download"
  74. throttle: 1000
  75. subjectName : req.ip
  76. timeInterval : 60 * 60
  77. RateLimiter.addCount rateLimitOpts, callback
  78. Project.findById project_id, {name: 1}, (err, project)->
  79. res.contentType("application/pdf")
  80. if !!req.query.popupDownload
  81. logger.log project_id: project_id, "download pdf as popup download"
  82. res.header('Content-Disposition', "attachment; filename=#{project.getSafeProjectName()}.pdf")
  83. else
  84. logger.log project_id: project_id, "download pdf to embed in browser"
  85. res.header('Content-Disposition', "filename=#{project.getSafeProjectName()}.pdf")
  86. rateLimit (err, canContinue)->
  87. if err?
  88. logger.err err:err, "error checking rate limit for pdf download"
  89. return res.send 500
  90. else if !canContinue
  91. logger.log project_id:project_id, ip:req.ip, "rate limit hit downloading pdf"
  92. res.send 500
  93. else
  94. CompileController._downloadAsUser req, (error, user_id) ->
  95. url = CompileController._getFileUrl project_id, user_id, req.params.build_id, "output.pdf"
  96. CompileController.proxyToClsi(project_id, url, req, res, next)
  97. deleteAuxFiles: (req, res, next) ->
  98. project_id = req.params.Project_id
  99. CompileController._compileAsUser req, (error, user_id) ->
  100. return next(error) if error?
  101. CompileManager.deleteAuxFiles project_id, user_id, (error) ->
  102. return next(error) if error?
  103. res.sendStatus(200)
  104. # this is only used by templates, so is not called with a user_id
  105. compileAndDownloadPdf: (req, res, next)->
  106. project_id = req.params.project_id
  107. # pass user_id as null, since templates are an "anonymous" compile
  108. CompileManager.compile project_id, null, {}, (err)->
  109. if err?
  110. logger.err err:err, project_id:project_id, "something went wrong compile and downloading pdf"
  111. res.sendStatus 500
  112. url = "/project/#{project_id}/output/output.pdf"
  113. CompileController.proxyToClsi project_id, url, req, res, next
  114. getFileFromClsi: (req, res, next = (error) ->) ->
  115. project_id = req.params.Project_id
  116. CompileController._downloadAsUser req, (error, user_id) ->
  117. return next(error) if error?
  118. url = CompileController._getFileUrl project_id, user_id, req.params.build_id, req.params.file
  119. CompileController.proxyToClsi(project_id, url, req, res, next)
  120. # compute a GET file url for a given project, user (optional), build (optional) and file
  121. _getFileUrl: (project_id, user_id, build_id, file) ->
  122. if user_id? and build_id?
  123. url = "/project/#{project_id}/user/#{user_id}/build/#{build_id}/output/#{file}"
  124. else if user_id?
  125. url = "/project/#{project_id}/user/#{user_id}/output/#{file}"
  126. else if build_id?
  127. url = "/project/#{project_id}/build/#{build_id}/output/#{file}"
  128. else
  129. url = "/project/#{project_id}/output/#{file}"
  130. return url
  131. # compute a POST url for a project, user (optional) and action
  132. _getUrl: (project_id, user_id, action) ->
  133. path = "/project/#{project_id}"
  134. path += "/user/#{user_id}" if user_id?
  135. return "#{path}/#{action}"
  136. proxySyncPdf: (req, res, next = (error) ->) ->
  137. project_id = req.params.Project_id
  138. {page, h, v} = req.query
  139. if not page?.match(/^\d+$/)
  140. return next(new Error("invalid page parameter"))
  141. if not h?.match(/^-?\d+\.\d+$/)
  142. return next(new Error("invalid h parameter"))
  143. if not v?.match(/^-?\d+\.\d+$/)
  144. return next(new Error("invalid v parameter"))
  145. # whether this request is going to a per-user container
  146. CompileController._compileAsUser req, (error, user_id) ->
  147. return next(error) if error?
  148. url = CompileController._getUrl(project_id, user_id, "sync/pdf")
  149. destination = {url: url, qs: {page, h, v}}
  150. CompileController.proxyToClsi(project_id, destination, req, res, next)
  151. proxySyncCode: (req, res, next = (error) ->) ->
  152. project_id = req.params.Project_id
  153. {file, line, column} = req.query
  154. if not file?
  155. return next(new Error("missing file parameter"))
  156. # Check that we are dealing with a simple file path (this is not
  157. # strictly needed because synctex uses this parameter as a label
  158. # to look up in the synctex output, and does not open the file
  159. # itself). Since we have valid synctex paths like foo/./bar we
  160. # allow those by replacing /./ with /
  161. testPath = file.replace '/./', '/'
  162. if Path.resolve("/", testPath) isnt "/#{testPath}"
  163. return next(new Error("invalid file parameter"))
  164. if not line?.match(/^\d+$/)
  165. return next(new Error("invalid line parameter"))
  166. if not column?.match(/^\d+$/)
  167. return next(new Error("invalid column parameter"))
  168. CompileController._compileAsUser req, (error, user_id) ->
  169. return next(error) if error?
  170. url = CompileController._getUrl(project_id, user_id, "sync/code")
  171. destination = {url:url, qs: {file, line, column}}
  172. CompileController.proxyToClsi(project_id, destination, req, res, next)
  173. proxyToClsi: (project_id, url, req, res, next = (error) ->) ->
  174. if req.query?.compileGroup
  175. CompileController.proxyToClsiWithLimits(project_id, url, {compileGroup: req.query.compileGroup}, req, res, next)
  176. else
  177. CompileManager.getProjectCompileLimits project_id, (error, limits) ->
  178. return next(error) if error?
  179. CompileController.proxyToClsiWithLimits(project_id, url, limits, req, res, next)
  180. proxyToClsiWithLimits: (project_id, url, limits, req, res, next = (error) ->) ->
  181. ClsiCookieManager.getCookieJar project_id, (err, jar)->
  182. if err?
  183. logger.err err:err, "error getting cookie jar for clsi request"
  184. return callback(err)
  185. # expand any url parameter passed in as {url:..., qs:...}
  186. if typeof url is "object"
  187. {url, qs} = url
  188. compilerUrl = Settings.apis.clsi.url
  189. url = "#{compilerUrl}#{url}"
  190. logger.log url: url, "proxying to CLSI"
  191. oneMinute = 60 * 1000
  192. # the base request
  193. options = { url: url, method: req.method, timeout: oneMinute, jar : jar }
  194. # add any provided query string
  195. options.qs = qs if qs?
  196. # if we have a build parameter, pass it through to the clsi
  197. if req.query?.pdfng && req.query?.build? # only for new pdf viewer
  198. options.qs ?= {}
  199. options.qs.build = req.query.build
  200. # if we are byte serving pdfs, pass through If-* and Range headers
  201. # do not send any others, there's a proxying loop if Host: is passed!
  202. if req.query?.pdfng
  203. newHeaders = {}
  204. for h, v of req.headers
  205. newHeaders[h] = req.headers[h] if h.match /^(If-|Range)/i
  206. options.headers = newHeaders
  207. proxy = request(options)
  208. proxy.pipe(res)
  209. proxy.on "error", (error) ->
  210. logger.warn err: error, url: url, "CLSI proxy error"
  211. wordCount: (req, res, next) ->
  212. project_id = req.params.Project_id
  213. file = req.query.file || false
  214. CompileController._compileAsUser req, (error, user_id) ->
  215. return next(error) if error?
  216. CompileManager.wordCount project_id, user_id, file, (error, body) ->
  217. return next(error) if error?
  218. res.contentType("application/json")
  219. res.send body