CompileController.coffee 8.8 KB

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