ConversionManager.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. import logger from '@overleaf/logger'
  2. import Settings from '@overleaf/settings'
  3. import fs from 'node:fs/promises'
  4. import Path from 'node:path'
  5. import CommandRunner from './CommandRunner.js'
  6. import LockManager from './LockManager.js'
  7. import OError from '@overleaf/o-error'
  8. import { ConversionError } from './Errors.js'
  9. const CONVERSION_CONFIGS = {
  10. docx: {
  11. inputFilename: 'input.docx',
  12. pandocArgs: ['--extract-media=.', '--from', 'docx+citations', '--citeproc'],
  13. },
  14. markdown: {
  15. inputFilename: 'input.md',
  16. pandocArgs: ['--from', 'markdown'],
  17. },
  18. }
  19. const PDF_TO_JPEG_CONFIGS = {
  20. preview: { width: 794, quality: 90 },
  21. thumbnail: { width: 190, quality: 50 },
  22. }
  23. const PDF_TO_JPEG_INPUT_FILENAME = 'input.pdf'
  24. const PDF_TO_JPEG_OUTPUT_FILENAME = 'output.jpg'
  25. const PDF_TO_JPEG_OUTPUT_BASENAME = Path.basename(
  26. PDF_TO_JPEG_OUTPUT_FILENAME,
  27. '.jpg'
  28. )
  29. async function convertToLaTeXWithLock(conversionId, inputPath, conversionType) {
  30. const conversionDir = Path.join(Settings.path.compilesDir, conversionId)
  31. const lock = LockManager.acquire(conversionDir)
  32. try {
  33. return await convertToLaTeX(
  34. conversionId,
  35. conversionDir,
  36. inputPath,
  37. conversionType
  38. )
  39. } finally {
  40. lock.release()
  41. }
  42. }
  43. async function convertToLaTeX(
  44. conversionId,
  45. conversionDir,
  46. inputPath,
  47. conversionType
  48. ) {
  49. const config = CONVERSION_CONFIGS[conversionType]
  50. if (!config) {
  51. throw new OError('unsupported conversion type', { conversionType })
  52. }
  53. await fs.mkdir(conversionDir, { recursive: true })
  54. const newSourcePath = Path.join(conversionDir, config.inputFilename)
  55. await fs.copyFile(inputPath, newSourcePath)
  56. const outputName = crypto.randomUUID() + '.zip'
  57. try {
  58. const {
  59. stdout: stdoutPandoc,
  60. stderr: stderrPandoc,
  61. exitCode: exitCodePandoc,
  62. } = await CommandRunner.promises.run(
  63. conversionId,
  64. [
  65. 'pandoc',
  66. config.inputFilename,
  67. '--output',
  68. 'main.tex',
  69. '--to',
  70. 'latex',
  71. '--standalone',
  72. ...config.pandocArgs,
  73. ],
  74. conversionDir,
  75. Settings.pandocImage,
  76. Settings.conversionTimeoutSeconds * 1000,
  77. {},
  78. 'conversions',
  79. null
  80. )
  81. if (exitCodePandoc !== 0) {
  82. throw new ConversionError('Non-zero exit code from pandoc', {
  83. type: conversionType,
  84. exitCode: exitCodePandoc,
  85. stderr: stderrPandoc,
  86. })
  87. }
  88. logger.debug(
  89. { stdout: stdoutPandoc, stderr: stderrPandoc, exitCode: exitCodePandoc },
  90. 'conversion command completed'
  91. )
  92. // Clean up the source document to leave only the conversion result
  93. await fs.unlink(newSourcePath).catch(() => {})
  94. const {
  95. stdout: stdoutZip,
  96. stderr: stderrZip,
  97. exitCode: exitCodeZip,
  98. } = await CommandRunner.promises.run(
  99. conversionId,
  100. ['zip', '-r', outputName, '.'],
  101. conversionDir,
  102. Settings.pandocImage,
  103. Settings.conversionTimeoutSeconds * 1000,
  104. {},
  105. 'conversions',
  106. null
  107. )
  108. if (exitCodeZip !== 0) {
  109. throw new OError('Non-zero exit code from pandoc', {
  110. exitCode: exitCodeZip,
  111. stderr: stderrZip,
  112. })
  113. }
  114. logger.debug(
  115. { stdout: stdoutZip, stderr: stderrZip, exitCode: exitCodeZip },
  116. 'conversion output compressed'
  117. )
  118. } catch (error) {
  119. // Clean up the conversion directory on error to avoid leaving failed conversions around
  120. await fs.rm(conversionDir, { force: true, recursive: true }).catch(() => {})
  121. if (error instanceof ConversionError) {
  122. throw error
  123. }
  124. throw new OError('pandoc conversion failed').withCause(error)
  125. }
  126. return Path.join(conversionDir, outputName)
  127. }
  128. const LATEX_EXPORT_CONFIGS = {
  129. docx: {
  130. fileExtension: 'docx',
  131. compressOutput: false,
  132. getPandocArgs: ({ outputPath }) => [
  133. '--output',
  134. outputPath,
  135. '--from',
  136. 'latex',
  137. '--to',
  138. 'docx',
  139. '--citeproc',
  140. '--number-sections',
  141. ],
  142. },
  143. markdown: {
  144. fileExtension: 'md',
  145. compressOutput: true,
  146. getPandocArgs: ({ outputPath }) => [
  147. '--output',
  148. outputPath,
  149. '--from',
  150. 'latex',
  151. '--to',
  152. 'markdown',
  153. ],
  154. },
  155. }
  156. async function convertLaTeXToDocumentInDirWithLock(
  157. conversionId,
  158. compileDir,
  159. rootDocPath,
  160. type
  161. ) {
  162. const lock = LockManager.acquire(compileDir)
  163. try {
  164. return await convertLaTeXToDocumentInDir(
  165. conversionId,
  166. compileDir,
  167. rootDocPath,
  168. type
  169. )
  170. } finally {
  171. lock.release()
  172. }
  173. }
  174. async function convertLaTeXToDocumentInDir(
  175. conversionId,
  176. compileDir,
  177. rootDocPath = 'main.tex',
  178. type
  179. ) {
  180. if (!Object.hasOwn(LATEX_EXPORT_CONFIGS, type)) {
  181. throw new OError('unsupported conversion type', { type })
  182. }
  183. const config = LATEX_EXPORT_CONFIGS[type]
  184. const timeoutMs = Settings.conversionTimeoutSeconds * 1000
  185. const outputId = crypto.randomUUID()
  186. logger.debug(
  187. { compileDir, rootDocPath, type },
  188. 'running pandoc latex-to-document in compile dir'
  189. )
  190. if (!config.compressOutput) {
  191. const outputName = `${outputId}.${config.fileExtension}`
  192. const { exitCode, stdout, stderr } = await CommandRunner.promises.run(
  193. conversionId,
  194. [
  195. 'pandoc',
  196. rootDocPath,
  197. ...config.getPandocArgs({ outputPath: outputName }),
  198. '--resource-path=.',
  199. ],
  200. compileDir,
  201. Settings.pandocImage,
  202. timeoutMs,
  203. {},
  204. 'conversions',
  205. null
  206. )
  207. if (exitCode !== 0) {
  208. throw new ConversionError('pandoc latex-to-document conversion failed', {
  209. type,
  210. exitCode,
  211. stderr,
  212. })
  213. }
  214. logger.debug(
  215. { stdout, stderr, exitCode },
  216. 'pandoc latex-to-document conversion completed'
  217. )
  218. return Path.join(compileDir, outputName)
  219. }
  220. // For compressed outputs we stage everything inside a uuid subdir so
  221. // the archive root ends up flat:
  222. // - pandoc runs with cwd=<outputId>, --extract-media=. drops images flat
  223. // alongside main.<ext>, and --resource-path=.. lets it find originals
  224. // in the parent compile dir.
  225. // - zip runs with the same cwd, so `zip -r ../<id>.zip .` produces an
  226. // archive whose root is main.<ext> + the media files (no uuid leak,
  227. // no collision with anything already in compileDir).
  228. await fs.mkdir(Path.join(compileDir, outputId), { recursive: true })
  229. const outputName = `main.${config.fileExtension}`
  230. const finalOutputName = `${outputId}.zip`
  231. const { exitCode, stdout, stderr } = await CommandRunner.promises.run(
  232. conversionId,
  233. [
  234. 'pandoc',
  235. Path.join('..', rootDocPath),
  236. ...config.getPandocArgs({ outputPath: outputName }),
  237. '--resource-path=..',
  238. '--extract-media=.',
  239. ],
  240. compileDir,
  241. Settings.pandocImage,
  242. timeoutMs,
  243. {},
  244. 'conversions',
  245. outputId
  246. )
  247. if (exitCode !== 0) {
  248. throw new ConversionError('pandoc latex-to-document conversion failed', {
  249. type,
  250. exitCode,
  251. stderr,
  252. })
  253. }
  254. logger.debug(
  255. { stdout, stderr, exitCode },
  256. 'pandoc latex-to-document conversion completed'
  257. )
  258. const {
  259. exitCode: zipExitCode,
  260. stdout: zipStdout,
  261. stderr: zipStderr,
  262. } = await CommandRunner.promises.run(
  263. conversionId,
  264. ['zip', '-r', Path.join('..', finalOutputName), '.'],
  265. compileDir,
  266. Settings.pandocImage,
  267. timeoutMs,
  268. {},
  269. 'conversions',
  270. outputId
  271. )
  272. if (zipExitCode !== 0) {
  273. throw new OError('zip compression of export failed', {
  274. exitCode: zipExitCode,
  275. stdout: zipStdout,
  276. stderr: zipStderr,
  277. })
  278. }
  279. logger.debug(
  280. { stdout: zipStdout, stderr: zipStderr, exitCode: zipExitCode },
  281. 'export compressed'
  282. )
  283. return Path.join(compileDir, finalOutputName)
  284. }
  285. async function convertPDFToJPEGWithLock(conversionId, inputPath, mode) {
  286. const conversionDir = Path.join(Settings.path.compilesDir, conversionId)
  287. const lock = LockManager.acquire(conversionDir)
  288. try {
  289. return await convertPDFToJPEG(conversionId, conversionDir, inputPath, mode)
  290. } finally {
  291. lock.release()
  292. }
  293. }
  294. async function convertPDFToJPEG(conversionId, conversionDir, inputPath, mode) {
  295. const config = PDF_TO_JPEG_CONFIGS[mode]
  296. await fs.mkdir(conversionDir, { recursive: true })
  297. const newSourcePath = Path.join(conversionDir, PDF_TO_JPEG_INPUT_FILENAME)
  298. await fs.copyFile(inputPath, newSourcePath)
  299. const dstPath = Path.join(conversionDir, PDF_TO_JPEG_OUTPUT_FILENAME)
  300. try {
  301. const { stdout, stderr, exitCode } = await CommandRunner.promises.run(
  302. conversionId,
  303. [
  304. 'pdftocairo',
  305. '-jpeg',
  306. '-jpegopt',
  307. `quality=${config.quality}`,
  308. '-singlefile',
  309. '-scale-to-x',
  310. config.width.toString(),
  311. '-scale-to-y',
  312. '-1', // maintain aspect ratio
  313. PDF_TO_JPEG_INPUT_FILENAME,
  314. PDF_TO_JPEG_OUTPUT_BASENAME,
  315. ],
  316. conversionDir,
  317. Settings.pdftocairoImage,
  318. Settings.conversionTimeoutSeconds * 1000,
  319. {},
  320. 'conversions',
  321. null
  322. )
  323. if (exitCode !== 0) {
  324. throw new OError('Non-zero exit code from pdftocairo', {
  325. exitCode,
  326. stderr,
  327. })
  328. }
  329. logger.debug(
  330. { stdout, stderr, exitCode },
  331. 'pdf-to-jpeg conversion completed'
  332. )
  333. const stat = await fs.lstat(dstPath)
  334. if (!stat.isFile()) {
  335. throw new OError('output.jpg is not a regular file', { stat })
  336. }
  337. // Clean up the source PDF to leave only the conversion result
  338. await fs.unlink(newSourcePath).catch(() => {})
  339. } catch (error) {
  340. await fs.rm(conversionDir, { force: true, recursive: true }).catch(() => {})
  341. throw new OError('pdf-to-jpeg conversion failed').withCause(error)
  342. }
  343. return dstPath
  344. }
  345. export default {
  346. promises: {
  347. convertToLaTeXWithLock,
  348. convertLaTeXToDocumentInDirWithLock,
  349. convertPDFToJPEGWithLock,
  350. },
  351. }