CompileController.coffee 9.0 KB

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