CompileController.coffee 9.2 KB

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