ConversionManager.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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. html: {
  156. fileExtension: 'html',
  157. compressOutput: true,
  158. getPandocArgs: ({ outputPath }) => [
  159. '--output',
  160. outputPath,
  161. '--from',
  162. 'latex',
  163. '--to',
  164. 'html',
  165. '--standalone',
  166. ],
  167. },
  168. }
  169. async function convertLaTeXToDocumentInDirWithLock(
  170. conversionId,
  171. compileDir,
  172. rootDocPath,
  173. type
  174. ) {
  175. const lock = LockManager.acquire(compileDir)
  176. try {
  177. return await convertLaTeXToDocumentInDir(
  178. conversionId,
  179. compileDir,
  180. rootDocPath,
  181. type
  182. )
  183. } finally {
  184. lock.release()
  185. }
  186. }
  187. async function convertLaTeXToDocumentInDir(
  188. conversionId,
  189. compileDir,
  190. rootDocPath = 'main.tex',
  191. type
  192. ) {
  193. if (!Object.hasOwn(LATEX_EXPORT_CONFIGS, type)) {
  194. throw new OError('unsupported conversion type', { type })
  195. }
  196. const config = LATEX_EXPORT_CONFIGS[type]
  197. const timeoutMs = Settings.conversionTimeoutSeconds * 1000
  198. const outputId = crypto.randomUUID()
  199. logger.debug(
  200. { compileDir, rootDocPath, type },
  201. 'running pandoc latex-to-document in compile dir'
  202. )
  203. if (!config.compressOutput) {
  204. const outputName = `${outputId}.${config.fileExtension}`
  205. const { exitCode, stdout, stderr } = await CommandRunner.promises.run(
  206. conversionId,
  207. [
  208. 'pandoc',
  209. rootDocPath,
  210. ...config.getPandocArgs({ outputPath: outputName }),
  211. '--resource-path=.',
  212. ],
  213. compileDir,
  214. Settings.pandocImage,
  215. timeoutMs,
  216. {},
  217. 'conversions',
  218. null
  219. )
  220. if (exitCode !== 0) {
  221. throw new ConversionError('pandoc latex-to-document conversion failed', {
  222. type,
  223. exitCode,
  224. stderr,
  225. })
  226. }
  227. logger.debug(
  228. { stdout, stderr, exitCode },
  229. 'pandoc latex-to-document conversion completed'
  230. )
  231. return Path.join(compileDir, outputName)
  232. }
  233. // For compressed outputs we stage everything inside a uuid subdir so
  234. // the archive root ends up flat:
  235. // - pandoc runs with cwd=<outputId>, --extract-media=. drops images flat
  236. // alongside main.<ext>, and --resource-path=.. lets it find originals
  237. // in the parent compile dir.
  238. // - zip runs with the same cwd, so `zip -r ../<id>.zip .` produces an
  239. // archive whose root is main.<ext> + the media files (no uuid leak,
  240. // no collision with anything already in compileDir).
  241. await fs.mkdir(Path.join(compileDir, outputId), { recursive: true })
  242. const outputName = `main.${config.fileExtension}`
  243. const finalOutputName = `${outputId}.zip`
  244. const { exitCode, stdout, stderr } = await CommandRunner.promises.run(
  245. conversionId,
  246. [
  247. 'pandoc',
  248. Path.join('..', rootDocPath),
  249. ...config.getPandocArgs({ outputPath: outputName }),
  250. '--resource-path=..',
  251. '--extract-media=.',
  252. ],
  253. compileDir,
  254. Settings.pandocImage,
  255. timeoutMs,
  256. {
  257. // By default pandoc uses cwd for resolving \input, \include, etc.
  258. // Setting TEXINPUTS allows us to override that to look in the actual
  259. // compileDir rather than the output directory.
  260. TEXINPUTS: '..:',
  261. },
  262. 'conversions',
  263. outputId
  264. )
  265. if (exitCode !== 0) {
  266. throw new ConversionError('pandoc latex-to-document conversion failed', {
  267. type,
  268. exitCode,
  269. stderr,
  270. })
  271. }
  272. logger.debug(
  273. { stdout, stderr, exitCode },
  274. 'pandoc latex-to-document conversion completed'
  275. )
  276. const {
  277. exitCode: zipExitCode,
  278. stdout: zipStdout,
  279. stderr: zipStderr,
  280. } = await CommandRunner.promises.run(
  281. conversionId,
  282. ['zip', '-r', Path.join('..', finalOutputName), '.'],
  283. compileDir,
  284. Settings.pandocImage,
  285. timeoutMs,
  286. {},
  287. 'conversions',
  288. outputId
  289. )
  290. if (zipExitCode !== 0) {
  291. throw new OError('zip compression of export failed', {
  292. exitCode: zipExitCode,
  293. stdout: zipStdout,
  294. stderr: zipStderr,
  295. })
  296. }
  297. logger.debug(
  298. { stdout: zipStdout, stderr: zipStderr, exitCode: zipExitCode },
  299. 'export compressed'
  300. )
  301. return Path.join(compileDir, finalOutputName)
  302. }
  303. async function convertPDFToJPEGWithLock(conversionId, inputPath, mode) {
  304. const conversionDir = Path.join(Settings.path.compilesDir, conversionId)
  305. const lock = LockManager.acquire(conversionDir)
  306. try {
  307. return await convertPDFToJPEG(conversionId, conversionDir, inputPath, mode)
  308. } finally {
  309. lock.release()
  310. }
  311. }
  312. async function convertPDFToJPEG(conversionId, conversionDir, inputPath, mode) {
  313. const config = PDF_TO_JPEG_CONFIGS[mode]
  314. await fs.mkdir(conversionDir, { recursive: true })
  315. const newSourcePath = Path.join(conversionDir, PDF_TO_JPEG_INPUT_FILENAME)
  316. await fs.copyFile(inputPath, newSourcePath)
  317. const dstPath = Path.join(conversionDir, PDF_TO_JPEG_OUTPUT_FILENAME)
  318. try {
  319. const { stdout, stderr, exitCode } = await CommandRunner.promises.run(
  320. conversionId,
  321. [
  322. 'pdftocairo',
  323. '-jpeg',
  324. '-jpegopt',
  325. `quality=${config.quality}`,
  326. '-singlefile',
  327. '-scale-to-x',
  328. config.width.toString(),
  329. '-scale-to-y',
  330. '-1', // maintain aspect ratio
  331. PDF_TO_JPEG_INPUT_FILENAME,
  332. PDF_TO_JPEG_OUTPUT_BASENAME,
  333. ],
  334. conversionDir,
  335. Settings.pdftocairoImage,
  336. Settings.conversionTimeoutSeconds * 1000,
  337. {},
  338. 'conversions',
  339. null
  340. )
  341. if (exitCode !== 0) {
  342. throw new OError('Non-zero exit code from pdftocairo', {
  343. exitCode,
  344. stderr,
  345. })
  346. }
  347. logger.debug(
  348. { stdout, stderr, exitCode },
  349. 'pdf-to-jpeg conversion completed'
  350. )
  351. const stat = await fs.lstat(dstPath)
  352. if (!stat.isFile()) {
  353. throw new OError('output.jpg is not a regular file', { stat })
  354. }
  355. // Clean up the source PDF to leave only the conversion result
  356. await fs.unlink(newSourcePath).catch(() => {})
  357. } catch (error) {
  358. await fs.rm(conversionDir, { force: true, recursive: true }).catch(() => {})
  359. throw new OError('pdf-to-jpeg conversion failed').withCause(error)
  360. }
  361. return dstPath
  362. }
  363. export default {
  364. promises: {
  365. convertToLaTeXWithLock,
  366. convertLaTeXToDocumentInDirWithLock,
  367. convertPDFToJPEGWithLock,
  368. },
  369. }