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