OutputFileArchiveManager.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. const archiver = require('archiver')
  2. const OutputCacheManager = require('./OutputCacheManager')
  3. const OutputFileFinder = require('./OutputFileFinder')
  4. const Settings = require('@overleaf/settings')
  5. const { open, realpath } = require('node:fs/promises')
  6. const path = require('path')
  7. const { NotFoundError } = require('./Errors')
  8. function getContentDir(projectId, userId) {
  9. let subDir
  10. if (userId != null) {
  11. subDir = `${projectId}-${userId}`
  12. } else {
  13. subDir = projectId
  14. }
  15. return `${Settings.path.outputDir}/${subDir}/`
  16. }
  17. /**
  18. * Is the provided path a symlink?
  19. * @param {string} path
  20. * @return {Promise<boolean>}
  21. */
  22. async function isSymlink(path) {
  23. try {
  24. const realPath = await realpath(path)
  25. return realPath !== path
  26. } catch (error) {
  27. if (error.code === 'ELOOP') {
  28. return true
  29. }
  30. throw error
  31. }
  32. }
  33. module.exports = {
  34. async archiveFilesForBuild(projectId, userId, build) {
  35. const validFiles = await this._getAllOutputFiles(projectId, userId, build)
  36. const archive = archiver('zip')
  37. const missingFiles = []
  38. for (const file of validFiles) {
  39. try {
  40. if (!(await isSymlink(file))) {
  41. const fileHandle = await open(file, 'r')
  42. const fileStream = fileHandle.createReadStream()
  43. archive.append(fileStream, { name: path.basename(file) })
  44. }
  45. } catch (error) {
  46. missingFiles.push(file)
  47. }
  48. }
  49. if (missingFiles.length > 0) {
  50. archive.append(missingFiles.join('\n'), {
  51. name: 'missing_files.txt',
  52. })
  53. }
  54. await archive.finalize()
  55. return archive
  56. },
  57. async _getAllOutputFiles(projectId, userId, build) {
  58. const contentDir = getContentDir(projectId, userId)
  59. try {
  60. const { outputFiles } = await OutputFileFinder.promises.findOutputFiles(
  61. [],
  62. `${contentDir}${OutputCacheManager.path(build, '.')}`
  63. )
  64. return outputFiles
  65. .filter(({ path }) => path !== 'output.pdf')
  66. .map(
  67. ({ path }) => `${contentDir}${OutputCacheManager.path(build, path)}`
  68. )
  69. } catch (error) {
  70. if (
  71. error.code === 'ENOENT' ||
  72. error.code === 'ENOTDIR' ||
  73. error.code === 'EACCES'
  74. ) {
  75. throw new NotFoundError('Output files not found')
  76. }
  77. throw error
  78. }
  79. },
  80. }