ProjectUploadManager.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. const Path = require('path')
  2. const fs = require('fs-extra')
  3. const { callbackify } = require('util')
  4. const ArchiveManager = require('./ArchiveManager')
  5. const { Doc } = require('../../models/Doc')
  6. const DocstoreManager = require('../Docstore/DocstoreManager')
  7. const DocumentHelper = require('../Documents/DocumentHelper')
  8. const DocumentUpdaterHandler = require('../DocumentUpdater/DocumentUpdaterHandler')
  9. const FileStoreHandler = require('../FileStore/FileStoreHandler')
  10. const FileSystemImportManager = require('./FileSystemImportManager')
  11. const ProjectCreationHandler = require('../Project/ProjectCreationHandler')
  12. const ProjectEntityMongoUpdateHandler = require('../Project/ProjectEntityMongoUpdateHandler')
  13. const ProjectRootDocManager = require('../Project/ProjectRootDocManager')
  14. const ProjectDetailsHandler = require('../Project/ProjectDetailsHandler')
  15. const ProjectDeleter = require('../Project/ProjectDeleter')
  16. const TpdsProjectFlusher = require('../ThirdPartyDataStore/TpdsProjectFlusher')
  17. const logger = require('@overleaf/logger')
  18. module.exports = {
  19. createProjectFromZipArchive: callbackify(createProjectFromZipArchive),
  20. createProjectFromZipArchiveWithName: callbackify(
  21. createProjectFromZipArchiveWithName
  22. ),
  23. promises: {
  24. createProjectFromZipArchive,
  25. createProjectFromZipArchiveWithName,
  26. },
  27. }
  28. async function createProjectFromZipArchive(ownerId, defaultName, zipPath) {
  29. const contentsPath = await _extractZip(zipPath)
  30. const { path, content } =
  31. await ProjectRootDocManager.promises.findRootDocFileFromDirectory(
  32. contentsPath
  33. )
  34. const projectName =
  35. DocumentHelper.getTitleFromTexContent(content || '') || defaultName
  36. const uniqueName = await _generateUniqueName(ownerId, projectName)
  37. const project = await ProjectCreationHandler.promises.createBlankProject(
  38. ownerId,
  39. uniqueName
  40. )
  41. try {
  42. await _initializeProjectWithZipContents(ownerId, project, contentsPath)
  43. if (path) {
  44. await ProjectRootDocManager.promises.setRootDocFromName(project._id, path)
  45. }
  46. } catch (err) {
  47. // no need to wait for the cleanup here
  48. ProjectDeleter.promises
  49. .deleteProject(project._id)
  50. .catch(err =>
  51. logger.error(
  52. { err, projectId: project._id },
  53. 'there was an error cleaning up project after importing a zip failed'
  54. )
  55. )
  56. throw err
  57. }
  58. await fs.remove(contentsPath)
  59. return project
  60. }
  61. async function createProjectFromZipArchiveWithName(
  62. ownerId,
  63. proposedName,
  64. zipPath,
  65. attributes = {}
  66. ) {
  67. const contentsPath = await _extractZip(zipPath)
  68. const uniqueName = await _generateUniqueName(ownerId, proposedName)
  69. const project = await ProjectCreationHandler.promises.createBlankProject(
  70. ownerId,
  71. uniqueName,
  72. attributes
  73. )
  74. try {
  75. await _initializeProjectWithZipContents(ownerId, project, contentsPath)
  76. await ProjectRootDocManager.promises.setRootDocAutomatically(project._id)
  77. } catch (err) {
  78. // no need to wait for the cleanup here
  79. ProjectDeleter.promises
  80. .deleteProject(project._id)
  81. .catch(err =>
  82. logger.error(
  83. { err, projectId: project._id },
  84. 'there was an error cleaning up project after importing a zip failed'
  85. )
  86. )
  87. throw err
  88. }
  89. await fs.remove(contentsPath)
  90. return project
  91. }
  92. async function _extractZip(zipPath) {
  93. const destination = Path.join(
  94. Path.dirname(zipPath),
  95. `${Path.basename(zipPath, '.zip')}-${Date.now()}`
  96. )
  97. await ArchiveManager.promises.extractZipArchive(zipPath, destination)
  98. return destination
  99. }
  100. async function _generateUniqueName(ownerId, originalName) {
  101. const fixedName = ProjectDetailsHandler.fixProjectName(originalName)
  102. const uniqueName = await ProjectDetailsHandler.promises.generateUniqueName(
  103. ownerId,
  104. fixedName
  105. )
  106. return uniqueName
  107. }
  108. async function _initializeProjectWithZipContents(
  109. ownerId,
  110. project,
  111. contentsPath
  112. ) {
  113. const topLevelDir = await ArchiveManager.promises.findTopLevelDirectory(
  114. contentsPath
  115. )
  116. const importEntries = await FileSystemImportManager.promises.importDir(
  117. topLevelDir
  118. )
  119. const { fileEntries, docEntries } = await _createEntriesFromImports(
  120. project._id,
  121. importEntries
  122. )
  123. const projectVersion =
  124. await ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure(
  125. project._id,
  126. docEntries,
  127. fileEntries
  128. )
  129. await _notifyDocumentUpdater(project, ownerId, {
  130. newFiles: fileEntries,
  131. newDocs: docEntries,
  132. newProject: { version: projectVersion },
  133. })
  134. await TpdsProjectFlusher.promises.flushProjectToTpds(project._id)
  135. }
  136. async function _createEntriesFromImports(projectId, importEntries) {
  137. const fileEntries = []
  138. const docEntries = []
  139. for (const importEntry of importEntries) {
  140. switch (importEntry.type) {
  141. case 'doc': {
  142. const docEntry = await _createDoc(
  143. projectId,
  144. importEntry.projectPath,
  145. importEntry.lines
  146. )
  147. docEntries.push(docEntry)
  148. break
  149. }
  150. case 'file': {
  151. const fileEntry = await _createFile(
  152. projectId,
  153. importEntry.projectPath,
  154. importEntry.fsPath
  155. )
  156. fileEntries.push(fileEntry)
  157. break
  158. }
  159. default: {
  160. throw new Error(`Invalid import type: ${importEntry.type}`)
  161. }
  162. }
  163. }
  164. return { fileEntries, docEntries }
  165. }
  166. async function _createDoc(projectId, projectPath, docLines) {
  167. const docName = Path.basename(projectPath)
  168. const doc = new Doc({ name: docName })
  169. await DocstoreManager.promises.updateDoc(
  170. projectId.toString(),
  171. doc._id.toString(),
  172. docLines,
  173. 0,
  174. {}
  175. )
  176. return { doc, path: projectPath, docLines: docLines.join('\n') }
  177. }
  178. async function _createFile(projectId, projectPath, fsPath) {
  179. const fileName = Path.basename(projectPath)
  180. const { fileRef, url } = await FileStoreHandler.promises.uploadFileFromDisk(
  181. projectId,
  182. { name: fileName },
  183. fsPath
  184. )
  185. return { file: fileRef, path: projectPath, url }
  186. }
  187. async function _notifyDocumentUpdater(project, userId, changes) {
  188. const projectHistoryId =
  189. project.overleaf && project.overleaf.history && project.overleaf.history.id
  190. await DocumentUpdaterHandler.promises.updateProjectStructure(
  191. project._id,
  192. projectHistoryId,
  193. userId,
  194. changes,
  195. null
  196. )
  197. }