LinkedFilesController.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /* eslint-disable
  2. max-len,
  3. */
  4. // TODO: This file was created by bulk-decaffeinate.
  5. // Fix any style issues and re-enable lint.
  6. /*
  7. * decaffeinate suggestions:
  8. * DS101: Remove unnecessary use of Array.from
  9. * DS102: Remove unnecessary code created because of implicit returns
  10. * DS207: Consider shorter variations of null checks
  11. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  12. */
  13. let LinkedFilesController
  14. const SessionManager = require('../Authentication/SessionManager')
  15. const Settings = require('@overleaf/settings')
  16. const _ = require('lodash')
  17. const AnalyticsManager = require('../../../../app/src/Features/Analytics/AnalyticsManager')
  18. const LinkedFilesHandler = require('./LinkedFilesHandler')
  19. const {
  20. CompileFailedError,
  21. UrlFetchFailedError,
  22. InvalidUrlError,
  23. AccessDeniedError,
  24. BadEntityTypeError,
  25. BadDataError,
  26. ProjectNotFoundError,
  27. V1ProjectNotFoundError,
  28. SourceFileNotFoundError,
  29. NotOriginalImporterError,
  30. FeatureNotAvailableError,
  31. RemoteServiceError,
  32. FileCannotRefreshError,
  33. } = require('./LinkedFilesErrors')
  34. const {
  35. OutputFileFetchFailedError,
  36. FileTooLargeError,
  37. OError,
  38. } = require('../Errors/Errors')
  39. const Modules = require('../../infrastructure/Modules')
  40. const { plainTextResponse } = require('../../infrastructure/Response')
  41. const ReferencesHandler = require('../References/ReferencesHandler')
  42. const EditorRealTimeController = require('../Editor/EditorRealTimeController')
  43. const { expressify } = require('@overleaf/promise-utils')
  44. async function createLinkedFile(req, res, next) {
  45. const { project_id: projectId } = req.params
  46. const { name, provider, data, parent_folder_id: parentFolderId } = req.body
  47. const userId = SessionManager.getLoggedInUserId(req.session)
  48. const Agent = LinkedFilesController._getAgent(provider)
  49. if (Agent == null) {
  50. return res.sendStatus(400)
  51. }
  52. data.provider = provider
  53. data.importedAt = new Date().toISOString()
  54. try {
  55. const newFileId = await Agent.promises.createLinkedFile(
  56. projectId,
  57. data,
  58. name,
  59. parentFolderId,
  60. userId
  61. )
  62. if (name.endsWith('.bib')) {
  63. AnalyticsManager.recordEventForUserInBackground(
  64. userId,
  65. 'linked-bib-file',
  66. {
  67. integration: provider,
  68. }
  69. )
  70. }
  71. return res.json({ new_file_id: newFileId })
  72. } catch (err) {
  73. return LinkedFilesController.handleError(err, req, res, next)
  74. }
  75. }
  76. async function refreshLinkedFile(req, res, next) {
  77. const { project_id: projectId, file_id: fileId } = req.params
  78. const userId = SessionManager.getLoggedInUserId(req.session)
  79. const { file, parentFolder } = await LinkedFilesHandler.promises.getFileById(
  80. projectId,
  81. fileId
  82. )
  83. if (file == null) {
  84. return res.sendStatus(404)
  85. }
  86. const { name } = file
  87. const { linkedFileData } = file
  88. if (
  89. linkedFileData == null ||
  90. (linkedFileData != null ? linkedFileData.provider : undefined) == null
  91. ) {
  92. return res.sendStatus(409)
  93. }
  94. const { provider } = linkedFileData
  95. const parentFolderId = parentFolder._id
  96. const Agent = LinkedFilesController._getAgent(provider)
  97. if (Agent == null) {
  98. return res.sendStatus(400)
  99. }
  100. linkedFileData.importedAt = new Date().toISOString()
  101. let newFileId
  102. try {
  103. newFileId = await Agent.promises.refreshLinkedFile(
  104. projectId,
  105. linkedFileData,
  106. name,
  107. parentFolderId,
  108. userId
  109. )
  110. } catch (err) {
  111. return LinkedFilesController.handleError(err, req, res, next)
  112. }
  113. if (req.body.shouldReindexReferences) {
  114. let data
  115. try {
  116. data = await ReferencesHandler.promises.indexAll(projectId)
  117. } catch (error) {
  118. OError.tag(error, 'failed to index references', {
  119. projectId,
  120. })
  121. return next(error)
  122. }
  123. EditorRealTimeController.emitToRoom(
  124. projectId,
  125. 'references:keys:updated',
  126. data.keys,
  127. true
  128. )
  129. res.json({ new_file_id: newFileId })
  130. } else {
  131. res.json({ new_file_id: newFileId })
  132. }
  133. }
  134. module.exports = LinkedFilesController = {
  135. Agents: _.extend(
  136. {
  137. url: require('./UrlAgent'),
  138. project_file: require('./ProjectFileAgent'),
  139. project_output_file: require('./ProjectOutputFileAgent'),
  140. },
  141. Modules.linkedFileAgentsIncludes()
  142. ),
  143. _getAgent(provider) {
  144. if (
  145. !Object.prototype.hasOwnProperty.call(
  146. LinkedFilesController.Agents,
  147. provider
  148. )
  149. ) {
  150. return null
  151. }
  152. if (!Array.from(Settings.enabledLinkedFileTypes).includes(provider)) {
  153. return null
  154. }
  155. return LinkedFilesController.Agents[provider]
  156. },
  157. createLinkedFile: expressify(createLinkedFile),
  158. refreshLinkedFile: expressify(refreshLinkedFile),
  159. handleError(error, req, res, next) {
  160. if (error instanceof AccessDeniedError) {
  161. res.status(403)
  162. plainTextResponse(
  163. res,
  164. res.locals.translate(
  165. 'the_project_that_contains_this_file_is_not_shared_with_you'
  166. )
  167. )
  168. } else if (error instanceof BadDataError) {
  169. res.status(400)
  170. plainTextResponse(res, 'The submitted data is not valid')
  171. } else if (error instanceof BadEntityTypeError) {
  172. res.status(400)
  173. plainTextResponse(res, 'The file is the wrong type')
  174. } else if (error instanceof SourceFileNotFoundError) {
  175. res.status(404)
  176. plainTextResponse(res, 'Source file not found')
  177. } else if (error instanceof ProjectNotFoundError) {
  178. res.status(404)
  179. plainTextResponse(res, 'Project not found')
  180. } else if (error instanceof V1ProjectNotFoundError) {
  181. res.status(409)
  182. plainTextResponse(
  183. res,
  184. 'Sorry, the source project is not yet imported to Overleaf v2. Please import it to Overleaf v2 to refresh this file'
  185. )
  186. } else if (error instanceof CompileFailedError) {
  187. res.status(422)
  188. plainTextResponse(
  189. res,
  190. res.locals.translate('generic_linked_file_compile_error')
  191. )
  192. } else if (error instanceof OutputFileFetchFailedError) {
  193. res.status(404)
  194. plainTextResponse(res, 'Could not get output file')
  195. } else if (error instanceof UrlFetchFailedError) {
  196. res.status(422)
  197. if (error.cause instanceof FileTooLargeError) {
  198. plainTextResponse(res, 'File too large')
  199. } else {
  200. plainTextResponse(
  201. res,
  202. `Your URL could not be reached (${
  203. error.info?.status || error.cause?.info?.status
  204. } status code). Please check it and try again.`
  205. )
  206. }
  207. } else if (error instanceof InvalidUrlError) {
  208. res.status(422)
  209. plainTextResponse(
  210. res,
  211. 'Your URL is not valid. Please check it and try again.'
  212. )
  213. } else if (error instanceof NotOriginalImporterError) {
  214. res.status(400)
  215. plainTextResponse(
  216. res,
  217. 'You are not the user who originally imported this file'
  218. )
  219. } else if (error instanceof FeatureNotAvailableError) {
  220. res.status(400)
  221. plainTextResponse(res, 'This feature is not enabled on your account')
  222. } else if (error instanceof RemoteServiceError) {
  223. if (error.info?.statusCode === 403) {
  224. res.status(400).json({ relink: true })
  225. } else {
  226. res.status(502)
  227. plainTextResponse(res, 'The remote service produced an error')
  228. }
  229. } else if (error instanceof FileCannotRefreshError) {
  230. res.status(400)
  231. plainTextResponse(res, 'This file cannot be refreshed')
  232. } else if (error.message === 'project_has_too_many_files') {
  233. res.status(400)
  234. plainTextResponse(res, 'too many files')
  235. } else if (/\bECONNREFUSED\b/.test(error.message)) {
  236. res.status(500)
  237. plainTextResponse(res, 'Importing references is not currently available')
  238. } else if (error instanceof FileTooLargeError) {
  239. res.status(422)
  240. plainTextResponse(res, 'File too large')
  241. } else {
  242. next(error)
  243. }
  244. },
  245. }