ProjectDuplicator.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. const { callbackify } = require('util')
  2. const Path = require('path')
  3. const OError = require('@overleaf/o-error')
  4. const { promiseMapWithLimit } = require('../../util/promises')
  5. const { Doc } = require('../../models/Doc')
  6. const { File } = require('../../models/File')
  7. const DocstoreManager = require('../Docstore/DocstoreManager')
  8. const DocumentUpdaterHandler = require('../DocumentUpdater/DocumentUpdaterHandler')
  9. const FileStoreHandler = require('../FileStore/FileStoreHandler')
  10. const ProjectCreationHandler = require('./ProjectCreationHandler')
  11. const ProjectDeleter = require('./ProjectDeleter')
  12. const ProjectEntityMongoUpdateHandler = require('./ProjectEntityMongoUpdateHandler')
  13. const ProjectEntityUpdateHandler = require('./ProjectEntityUpdateHandler')
  14. const ProjectGetter = require('./ProjectGetter')
  15. const ProjectLocator = require('./ProjectLocator')
  16. const ProjectOptionsHandler = require('./ProjectOptionsHandler')
  17. const SafePath = require('./SafePath')
  18. const TpdsProjectFlusher = require('../ThirdPartyDataStore/TpdsProjectFlusher')
  19. module.exports = {
  20. duplicate: callbackify(duplicate),
  21. promises: {
  22. duplicate,
  23. },
  24. }
  25. async function duplicate(owner, originalProjectId, newProjectName) {
  26. await DocumentUpdaterHandler.promises.flushProjectToMongo(originalProjectId)
  27. const originalProject = await ProjectGetter.promises.getProject(
  28. originalProjectId,
  29. {
  30. compiler: true,
  31. rootFolder: true,
  32. rootDoc_id: true,
  33. }
  34. )
  35. const { path: rootDocPath } = await ProjectLocator.promises.findRootDoc({
  36. project_id: originalProjectId,
  37. })
  38. const originalEntries = _getFolderEntries(originalProject.rootFolder[0])
  39. // Now create the new project, cleaning it up on failure if necessary
  40. const newProject = await ProjectCreationHandler.promises.createBlankProject(
  41. owner._id,
  42. newProjectName
  43. )
  44. try {
  45. await ProjectOptionsHandler.promises.setCompiler(
  46. newProject._id,
  47. originalProject.compiler
  48. )
  49. const [docEntries, fileEntries] = await Promise.all([
  50. _copyDocs(originalEntries.docEntries, originalProject, newProject),
  51. _copyFiles(originalEntries.fileEntries, originalProject, newProject),
  52. ])
  53. const projectVersion = await ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure(
  54. newProject._id,
  55. docEntries,
  56. fileEntries
  57. )
  58. // Silently ignore the rootDoc in case it's not valid per the new limits.
  59. if (
  60. rootDocPath &&
  61. ProjectEntityUpdateHandler.isPathValidForRootDoc(rootDocPath.fileSystem)
  62. ) {
  63. await _setRootDoc(newProject._id, rootDocPath.fileSystem)
  64. }
  65. await _notifyDocumentUpdater(newProject, owner._id, {
  66. newFiles: fileEntries,
  67. newDocs: docEntries,
  68. newProject: { version: projectVersion },
  69. })
  70. await TpdsProjectFlusher.promises.flushProjectToTpds(newProject._id)
  71. } catch (err) {
  72. // Clean up broken clone on error.
  73. // Make sure we delete the new failed project, not the original one!
  74. await ProjectDeleter.promises.deleteProject(newProject._id)
  75. throw OError.tag(err, 'error cloning project, broken clone deleted', {
  76. originalProjectId,
  77. newProjectName,
  78. newProjectId: newProject._id,
  79. })
  80. }
  81. return newProject
  82. }
  83. function _getFolderEntries(folder, folderPath = '/') {
  84. const docEntries = []
  85. const fileEntries = []
  86. const docs = folder.docs || []
  87. const files = folder.fileRefs || []
  88. const subfolders = folder.folders || []
  89. for (const doc of docs) {
  90. if (doc == null || doc._id == null) {
  91. continue
  92. }
  93. const path = Path.join(folderPath, doc.name)
  94. docEntries.push({ doc, path })
  95. }
  96. for (const file of files) {
  97. if (file == null || file._id == null) {
  98. continue
  99. }
  100. const path = Path.join(folderPath, file.name)
  101. fileEntries.push({ file, path })
  102. }
  103. for (const subfolder of subfolders) {
  104. if (subfolder == null || subfolder._id == null) {
  105. continue
  106. }
  107. const subfolderPath = Path.join(folderPath, subfolder.name)
  108. const subfolderEntries = _getFolderEntries(subfolder, subfolderPath)
  109. for (const docEntry of subfolderEntries.docEntries) {
  110. docEntries.push(docEntry)
  111. }
  112. for (const fileEntry of subfolderEntries.fileEntries) {
  113. fileEntries.push(fileEntry)
  114. }
  115. }
  116. return { docEntries, fileEntries }
  117. }
  118. async function _copyDocs(sourceEntries, sourceProject, targetProject) {
  119. const docLinesById = await _getDocLinesForProject(sourceProject._id)
  120. const targetEntries = []
  121. for (const sourceEntry of sourceEntries) {
  122. const sourceDoc = sourceEntry.doc
  123. const path = sourceEntry.path
  124. const doc = new Doc({ name: sourceDoc.name })
  125. const docLines = docLinesById.get(sourceDoc._id.toString())
  126. await DocstoreManager.promises.updateDoc(
  127. targetProject._id.toString(),
  128. doc._id.toString(),
  129. docLines,
  130. 0,
  131. {}
  132. )
  133. targetEntries.push({ doc, path, docLines: docLines.join('\n') })
  134. }
  135. return targetEntries
  136. }
  137. async function _getDocLinesForProject(projectId) {
  138. const docs = await DocstoreManager.promises.getAllDocs(projectId)
  139. const docLinesById = new Map(docs.map(doc => [doc._id, doc.lines]))
  140. return docLinesById
  141. }
  142. async function _copyFiles(sourceEntries, sourceProject, targetProject) {
  143. const targetEntries = await promiseMapWithLimit(
  144. 5,
  145. sourceEntries,
  146. async sourceEntry => {
  147. const sourceFile = sourceEntry.file
  148. const path = sourceEntry.path
  149. const file = new File({ name: SafePath.clean(sourceFile.name) })
  150. if (sourceFile.linkedFileData != null) {
  151. file.linkedFileData = sourceFile.linkedFileData
  152. }
  153. if (sourceFile.hash != null) {
  154. file.hash = sourceFile.hash
  155. }
  156. const url = await FileStoreHandler.promises.copyFile(
  157. sourceProject._id,
  158. sourceFile._id,
  159. targetProject._id,
  160. file._id
  161. )
  162. return { file, path, url }
  163. }
  164. )
  165. return targetEntries
  166. }
  167. async function _setRootDoc(projectId, path) {
  168. const { element: rootDoc } = await ProjectLocator.promises.findElementByPath({
  169. project_id: projectId,
  170. path,
  171. exactCaseMatch: true,
  172. })
  173. await ProjectEntityUpdateHandler.promises.setRootDoc(projectId, rootDoc._id)
  174. }
  175. async function _notifyDocumentUpdater(project, userId, changes) {
  176. const projectHistoryId =
  177. project.overleaf && project.overleaf.history && project.overleaf.history.id
  178. await DocumentUpdaterHandler.promises.updateProjectStructure(
  179. project._id,
  180. projectHistoryId,
  181. userId,
  182. changes
  183. )
  184. }