LinkedFilesController.js 8.3 KB

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