ZipManager.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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. continue
  78. }
  79. const updatePath = `${id}/updates/${update.v}`
  80. zipfile.addBuffer(Buffer.from(JSON.stringify(update)), updatePath, {
  81. mtime: new Date(update.meta.start_ts),
  82. })
  83. try {
  84. content = DiffGenerator.rewindUpdate(content, update)
  85. v = update.v
  86. } catch (e) {
  87. e.attempted_update = update // keep a record of the attempted update
  88. logger.warn({ projectId, docId, err: e }, 'rewind error')
  89. break // stop attempting to rewind on error
  90. }
  91. metadata.updates.push({
  92. path: updatePath,
  93. version: update.v,
  94. ts: update.meta.start_ts,
  95. doc_length: content.length,
  96. })
  97. previousUpdate = update
  98. update = await getUpdate()
  99. }
  100. const contentStartPath = `${id}/content/start/${v}`
  101. zipfile.addBuffer(Buffer.from(content), contentStartPath)
  102. metadata.content.start = {
  103. path: contentStartPath,
  104. version: v,
  105. }
  106. return metadata
  107. }
  108. async function generateZip(projectId, zipfile) {
  109. await UpdatesManager.promises.processUncompressedUpdatesForProject(projectId)
  110. const docIds = await PackManager.promises.findAllDocsInProject(projectId)
  111. const manifest = { projectId, docs: [] }
  112. for (const docId of docIds) {
  113. const doc = await rewindDoc(projectId, docId, zipfile)
  114. if (doc) {
  115. manifest.docs.push(doc)
  116. }
  117. }
  118. zipfile.addBuffer(
  119. Buffer.from(JSON.stringify(manifest, null, 2)),
  120. 'manifest.json'
  121. )
  122. zipfile.end()
  123. }
  124. async function exportProject(projectId, zipPath) {
  125. const zipfile = new yazl.ZipFile()
  126. const pipeline = streamPipeline(
  127. zipfile.outputStream,
  128. fs.createWriteStream(zipPath)
  129. )
  130. await generateZip(projectId, zipfile)
  131. await pipeline
  132. }
  133. /**
  134. * Create a temporary directory for use with exportProject()
  135. */
  136. async function makeTempDirectory() {
  137. const tmpdir = await fs.promises.mkdtemp(
  138. (await fs.promises.realpath(os.tmpdir())) + Path.sep
  139. )
  140. return tmpdir
  141. }
  142. /**
  143. * Clean up a temporary directory made with makeTempDirectory()
  144. */
  145. function cleanupTempDirectory(tmpdir) {
  146. fs.promises.rm(tmpdir, { recursive: true, force: true }).catch(err => {
  147. if (err) {
  148. logger.warn({ err, tmpdir }, 'Failed to clean up temp directory')
  149. }
  150. })
  151. }
  152. module.exports = {
  153. exportProject: util.callbackify(exportProject),
  154. makeTempDirectory: util.callbackify(makeTempDirectory),
  155. cleanupTempDirectory,
  156. }