OutputFileArchiveManager.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. const archiver = require('archiver')
  2. const OutputCacheManager = require('./OutputCacheManager')
  3. const OutputFileFinder = require('./OutputFileFinder')
  4. const Settings = require('@overleaf/settings')
  5. const { open } = require('node:fs/promises')
  6. const path = require('path')
  7. const { NotFoundError } = require('./Errors')
  8. const logger = require('@overleaf/logger')
  9. // NOTE: Updating this list requires a corresponding change in
  10. // * services/web/frontend/js/features/pdf-preview/util/file-list.js
  11. const ignoreFiles = ['output.fls', 'output.fdb_latexmk']
  12. function getContentDir(projectId, userId) {
  13. let subDir
  14. if (userId != null) {
  15. subDir = `${projectId}-${userId}`
  16. } else {
  17. subDir = projectId
  18. }
  19. return `${Settings.path.outputDir}/${subDir}/`
  20. }
  21. module.exports = {
  22. async archiveFilesForBuild(projectId, userId, build) {
  23. logger.debug({ projectId, userId, build }, 'Will create zip file')
  24. const outputFiles = await this._getAllOutputFiles(projectId, userId, build)
  25. const archive = archiver('zip')
  26. archive.on('error', err => {
  27. logger.warn({ err }, 'error emitted when creating output files archive')
  28. })
  29. const missingFiles = []
  30. for (const file of outputFiles) {
  31. let fileHandle
  32. try {
  33. fileHandle = await open(file, 'r')
  34. } catch (error) {
  35. logger.warn(
  36. { file, error },
  37. 'error opening file to add to output files archive'
  38. )
  39. missingFiles.push(file)
  40. continue
  41. }
  42. const fileStream = fileHandle.createReadStream()
  43. archive.append(fileStream, {
  44. name: path.basename(file),
  45. })
  46. }
  47. if (missingFiles.length > 0) {
  48. archive.append(missingFiles.join('\n'), {
  49. name: 'missing_files.txt',
  50. })
  51. }
  52. await archive.finalize()
  53. return archive
  54. },
  55. async _getAllOutputFiles(projectId, userId, build) {
  56. const contentDir = getContentDir(projectId, userId)
  57. try {
  58. const { outputFiles } = await OutputFileFinder.promises.findOutputFiles(
  59. [],
  60. `${contentDir}${OutputCacheManager.path(build, '.')}`
  61. )
  62. return outputFiles
  63. .filter(
  64. // Ignore the pdf and also ignore the files ignored by the frontend.
  65. ({ path }) => path !== 'output.pdf' && !ignoreFiles.includes(path)
  66. )
  67. .map(
  68. ({ path }) => `${contentDir}${OutputCacheManager.path(build, path)}`
  69. )
  70. } catch (error) {
  71. if (
  72. error.code === 'ENOENT' ||
  73. error.code === 'ENOTDIR' ||
  74. error.code === 'EACCES'
  75. ) {
  76. throw new NotFoundError('Output files not found')
  77. }
  78. throw error
  79. }
  80. },
  81. }