ZipManager.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. const logger = require('@overleaf/logger')
  2. const UpdatesManager = require('./UpdatesManager')
  3. const DiffGenerator = require('./DiffGenerator')
  4. const DocumentUpdaterManager = require('./DocumentUpdaterManager')
  5. const DocstoreManager = require('./DocstoreManager')
  6. const Errors = require('./Errors')
  7. const PackManager = require('./PackManager')
  8. const yazl = require('yazl')
  9. const util = require('util')
  10. const stream = require('stream')
  11. const fs = require('fs')
  12. const os = require('os')
  13. const Path = require('path')
  14. const { packsAreDuplicated } = require('./util/PackUtils')
  15. const streamPipeline = util.promisify(stream.pipeline)
  16. // look in docstore or docupdater for the latest version of the document
  17. async function getLatestContent(projectId, docId, lastUpdateVersion) {
  18. const [docstoreContent, docstoreVersion] =
  19. await DocstoreManager.promises.peekDocument(projectId, docId)
  20. // if docstore is out of date, check for a newer version in docupdater
  21. // and return that instead
  22. if (docstoreVersion <= lastUpdateVersion) {
  23. const [docupdaterContent, docupdaterVersion] =
  24. await DocumentUpdaterManager.promises.peekDocument(projectId, docId)
  25. if (docupdaterVersion > docstoreVersion) {
  26. return [docupdaterContent, docupdaterVersion]
  27. }
  28. }
  29. return [docstoreContent, docstoreVersion]
  30. }
  31. async function rewindDoc(projectId, docId, zipfile) {
  32. logger.debug({ projectId, docId }, 'rewinding document')
  33. // Prepare to rewind content
  34. const docIterator = await PackManager.promises.makeDocIterator(docId)
  35. const getUpdate = util.promisify(docIterator.next).bind(docIterator)
  36. const lastUpdate = await getUpdate()
  37. if (!lastUpdate) {
  38. return null
  39. }
  40. const lastUpdateVersion = lastUpdate.v
  41. let latestContent
  42. let version
  43. try {
  44. ;[latestContent, version] = await getLatestContent(
  45. projectId,
  46. docId,
  47. lastUpdateVersion
  48. )
  49. } catch (err) {
  50. if (err instanceof Errors.NotFoundError) {
  51. // Doc not found in docstore. We can't build its history
  52. return null
  53. } else {
  54. throw err
  55. }
  56. }
  57. const id = docId.toString()
  58. const contentEndPath = `${id}/content/end/${version}`
  59. zipfile.addBuffer(Buffer.from(latestContent), contentEndPath)
  60. const metadata = {
  61. id,
  62. version,
  63. content: {
  64. end: {
  65. path: contentEndPath,
  66. version,
  67. },
  68. },
  69. updates: [],
  70. }
  71. let content = latestContent
  72. let v = version
  73. let update = lastUpdate
  74. let previousUpdate = null
  75. while (update) {
  76. if (packsAreDuplicated(update, previousUpdate)) {
  77. previousUpdate = update
  78. update = await getUpdate()
  79. continue
  80. }
  81. const updatePath = `${id}/updates/${update.v}`
  82. zipfile.addBuffer(Buffer.from(JSON.stringify(update)), updatePath, {
  83. mtime: new Date(update.meta.start_ts),
  84. })
  85. try {
  86. content = DiffGenerator.rewindUpdate(content, update)
  87. v = update.v
  88. } catch (e) {
  89. e.attempted_update = update // keep a record of the attempted update
  90. logger.warn({ projectId, docId, err: e }, 'rewind error')
  91. break // stop attempting to rewind on error
  92. }
  93. metadata.updates.push({
  94. path: updatePath,
  95. version: update.v,
  96. ts: update.meta.start_ts,
  97. doc_length: content.length,
  98. })
  99. previousUpdate = update
  100. update = await getUpdate()
  101. }
  102. const contentStartPath = `${id}/content/start/${v}`
  103. zipfile.addBuffer(Buffer.from(content), contentStartPath)
  104. metadata.content.start = {
  105. path: contentStartPath,
  106. version: v,
  107. }
  108. return metadata
  109. }
  110. async function generateZip(projectId, zipfile) {
  111. await UpdatesManager.promises.processUncompressedUpdatesForProject(projectId)
  112. const docIds = await PackManager.promises.findAllDocsInProject(projectId)
  113. const manifest = { projectId, docs: [] }
  114. for (const docId of docIds) {
  115. const doc = await rewindDoc(projectId, docId, zipfile)
  116. if (doc) {
  117. manifest.docs.push(doc)
  118. }
  119. }
  120. zipfile.addBuffer(
  121. Buffer.from(JSON.stringify(manifest, null, 2)),
  122. 'manifest.json'
  123. )
  124. zipfile.end()
  125. }
  126. async function exportProject(projectId, zipPath) {
  127. const zipfile = new yazl.ZipFile()
  128. const pipeline = streamPipeline(
  129. zipfile.outputStream,
  130. fs.createWriteStream(zipPath)
  131. )
  132. await generateZip(projectId, zipfile)
  133. await pipeline
  134. }
  135. /**
  136. * Create a temporary directory for use with exportProject()
  137. */
  138. async function makeTempDirectory() {
  139. const tmpdir = await fs.promises.mkdtemp(
  140. (await fs.promises.realpath(os.tmpdir())) + Path.sep
  141. )
  142. return tmpdir
  143. }
  144. /**
  145. * Clean up a temporary directory made with makeTempDirectory()
  146. */
  147. function cleanupTempDirectory(tmpdir) {
  148. fs.promises.rm(tmpdir, { recursive: true, force: true }).catch(err => {
  149. if (err) {
  150. logger.warn({ err, tmpdir }, 'Failed to clean up temp directory')
  151. }
  152. })
  153. }
  154. module.exports = {
  155. exportProject: util.callbackify(exportProject),
  156. makeTempDirectory: util.callbackify(makeTempDirectory),
  157. cleanupTempDirectory,
  158. }