LinkedFilesHandler.mjs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import FileWriter from '../../infrastructure/FileWriter.js'
  2. import EditorController from '../Editor/EditorController.mjs'
  3. import ProjectLocator from '../Project/ProjectLocator.mjs'
  4. import { Project } from '../../models/Project.mjs'
  5. import ProjectGetter from '../Project/ProjectGetter.mjs'
  6. import LinkedFilesErrors from './LinkedFilesErrors.mjs'
  7. import { callbackifyAll } from '@overleaf/promise-utils'
  8. const { ProjectNotFoundError, V1ProjectNotFoundError, BadDataError } =
  9. LinkedFilesErrors
  10. const LinkedFilesHandler = {
  11. async getFileById(projectId, fileId) {
  12. const { element, path, folder } = await ProjectLocator.promises.findElement(
  13. {
  14. project_id: projectId,
  15. element_id: fileId,
  16. type: 'file',
  17. }
  18. )
  19. return { file: element, path, parentFolder: folder }
  20. },
  21. async getSourceProject(data) {
  22. const projection = { _id: 1, name: 1, overleaf: 1 } // include the historyId for future use
  23. if (data.v1_source_doc_id != null) {
  24. const project = await Project.findOne(
  25. { 'overleaf.id': data.v1_source_doc_id },
  26. projection
  27. ).exec()
  28. if (project == null) {
  29. throw new V1ProjectNotFoundError()
  30. }
  31. return project
  32. } else if (data.source_project_id != null) {
  33. const project = await ProjectGetter.promises.getProject(
  34. data.source_project_id,
  35. projection
  36. )
  37. if (project == null) {
  38. throw new ProjectNotFoundError()
  39. }
  40. return project
  41. } else {
  42. throw new BadDataError('neither v1 nor v2 id present')
  43. }
  44. },
  45. async importFromStream(
  46. projectId,
  47. readStream,
  48. linkedFileData,
  49. name,
  50. parentFolderId,
  51. userId
  52. ) {
  53. const fsPath = await FileWriter.promises.writeStreamToDisk(
  54. projectId,
  55. readStream
  56. )
  57. return await EditorController.promises.upsertFile(
  58. projectId,
  59. parentFolderId,
  60. name,
  61. fsPath,
  62. linkedFileData,
  63. 'upload',
  64. userId
  65. )
  66. },
  67. async importContent(
  68. projectId,
  69. content,
  70. linkedFileData,
  71. name,
  72. parentFolderId,
  73. userId
  74. ) {
  75. const fsPath = await FileWriter.promises.writeContentToDisk(
  76. projectId,
  77. content
  78. )
  79. return await EditorController.promises.upsertFile(
  80. projectId,
  81. parentFolderId,
  82. name,
  83. fsPath,
  84. linkedFileData,
  85. 'upload',
  86. userId
  87. )
  88. },
  89. }
  90. export default {
  91. promises: LinkedFilesHandler,
  92. ...callbackifyAll(LinkedFilesHandler, {
  93. multiResult: { getFileById: ['file', 'path', 'parentFolder'] },
  94. }),
  95. }