|
| 1 | +import path from 'path' |
| 2 | +import fs from 'fs/promises' |
| 3 | +import { executePandoc, canPandocConvert } from './utils/pandoc-wrapper' |
| 4 | + |
| 5 | +export interface DocumentConvertOptions { |
| 6 | + sourcePath: string |
| 7 | + outputDir: string |
| 8 | + targetFormat: string |
| 9 | + quality: number // 1-100 (not used for documents, but kept for interface consistency) |
| 10 | + overwriteBehavior: 'skip' | 'rename' | 'overwrite' |
| 11 | +} |
| 12 | + |
| 13 | +export interface ConvertResult { |
| 14 | + success: boolean |
| 15 | + outputPath: string |
| 16 | + error?: string |
| 17 | + durationMs: number |
| 18 | +} |
| 19 | + |
| 20 | +// Supported document formats (note: PDF as input is NOT supported by Pandoc) |
| 21 | +const DOCUMENT_FORMATS = ['pdf', 'epub', 'docx', 'txt', 'rtf', 'odt', 'md', 'html'] as const |
| 22 | + |
| 23 | +/** |
| 24 | + * Check if a format is a supported document format |
| 25 | + */ |
| 26 | +export function isDocumentFormat(ext: string): boolean { |
| 27 | + const lower = ext.toLowerCase() |
| 28 | + return DOCUMENT_FORMATS.includes(lower as typeof DOCUMENT_FORMATS[number]) |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Generate a unique output file path, handling conflicts based on overwrite behavior. |
| 33 | + */ |
| 34 | +async function resolveOutputPath( |
| 35 | + outputDir: string, |
| 36 | + baseName: string, |
| 37 | + targetFormat: string, |
| 38 | + overwriteBehavior: 'skip' | 'rename' | 'overwrite' |
| 39 | +): Promise<{ path: string; skip: boolean }> { |
| 40 | + const outputPath = path.join(outputDir, `${baseName}.${targetFormat}`) |
| 41 | + |
| 42 | + try { |
| 43 | + await fs.access(outputPath) |
| 44 | + // File exists |
| 45 | + if (overwriteBehavior === 'overwrite') { |
| 46 | + return { path: outputPath, skip: false } |
| 47 | + } |
| 48 | + if (overwriteBehavior === 'skip') { |
| 49 | + return { path: outputPath, skip: true } |
| 50 | + } |
| 51 | + // rename: find next available name |
| 52 | + let counter = 1 |
| 53 | + let newPath: string |
| 54 | + do { |
| 55 | + newPath = path.join(outputDir, `${baseName} (${counter}).${targetFormat}`) |
| 56 | + counter++ |
| 57 | + try { |
| 58 | + await fs.access(newPath) |
| 59 | + } catch { |
| 60 | + // File doesn't exist, use this path |
| 61 | + return { path: newPath, skip: false } |
| 62 | + } |
| 63 | + } while (counter < 10000) |
| 64 | + |
| 65 | + return { path: newPath, skip: false } |
| 66 | + } catch { |
| 67 | + // File doesn't exist, use original path |
| 68 | + return { path: outputPath, skip: false } |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +/** |
| 73 | + * Get the base name of a file without its extension |
| 74 | + */ |
| 75 | +function getBaseName(filePath: string): string { |
| 76 | + const name = path.basename(filePath) |
| 77 | + const lastDot = name.lastIndexOf('.') |
| 78 | + if (lastDot === -1) return name |
| 79 | + return name.substring(0, lastDot) |
| 80 | +} |
| 81 | + |
| 82 | +/** |
| 83 | + * Get file extension without the dot |
| 84 | + */ |
| 85 | +function getExtension(filePath: string): string { |
| 86 | + const ext = path.extname(filePath) |
| 87 | + return ext ? ext.substring(1).toLowerCase() : '' |
| 88 | +} |
| 89 | + |
| 90 | +/** |
| 91 | + * Convert a document file to the target format using Pandoc. |
| 92 | + */ |
| 93 | +export async function convertDocument(options: DocumentConvertOptions): Promise<ConvertResult> { |
| 94 | + const startTime = Date.now() |
| 95 | + const { sourcePath, outputDir, targetFormat, overwriteBehavior } = options |
| 96 | + |
| 97 | + try { |
| 98 | + // Validate source file exists |
| 99 | + await fs.access(sourcePath) |
| 100 | + |
| 101 | + // Get source format |
| 102 | + const sourceExt = getExtension(sourcePath) |
| 103 | + if (!sourceExt) { |
| 104 | + return { |
| 105 | + success: false, |
| 106 | + outputPath: '', |
| 107 | + error: 'Could not determine source file format.', |
| 108 | + durationMs: Date.now() - startTime, |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + // Check if Pandoc can handle this conversion |
| 113 | + if (!canPandocConvert(sourceExt, targetFormat)) { |
| 114 | + // Special error message for PDF input |
| 115 | + if (sourceExt === 'pdf') { |
| 116 | + return { |
| 117 | + success: false, |
| 118 | + outputPath: '', |
| 119 | + error: 'PDF as input is not supported by Pandoc. To convert from PDF, you would need additional tools like pdftotext.', |
| 120 | + durationMs: Date.now() - startTime, |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + return { |
| 125 | + success: false, |
| 126 | + outputPath: '', |
| 127 | + error: `Pandoc does not support conversion from ${sourceExt} to ${targetFormat}.`, |
| 128 | + durationMs: Date.now() - startTime, |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + // Ensure output directory exists |
| 133 | + await fs.mkdir(outputDir, { recursive: true }) |
| 134 | + |
| 135 | + // Resolve output path |
| 136 | + const baseName = getBaseName(sourcePath) |
| 137 | + const { path: outputPath, skip } = await resolveOutputPath( |
| 138 | + outputDir, |
| 139 | + baseName, |
| 140 | + targetFormat, |
| 141 | + overwriteBehavior |
| 142 | + ) |
| 143 | + |
| 144 | + if (skip) { |
| 145 | + return { |
| 146 | + success: true, |
| 147 | + outputPath, |
| 148 | + durationMs: Date.now() - startTime, |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + // Execute Pandoc conversion |
| 153 | + const result = await executePandoc({ |
| 154 | + inputPath: sourcePath, |
| 155 | + outputPath, |
| 156 | + targetFormat, |
| 157 | + }) |
| 158 | + |
| 159 | + if (!result.success) { |
| 160 | + return { |
| 161 | + success: false, |
| 162 | + outputPath: '', |
| 163 | + error: result.error || 'Pandoc conversion failed', |
| 164 | + durationMs: Date.now() - startTime, |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + return { |
| 169 | + success: true, |
| 170 | + outputPath, |
| 171 | + durationMs: Date.now() - startTime, |
| 172 | + } |
| 173 | + } catch (err) { |
| 174 | + const errorMessage = err instanceof Error ? err.message : String(err) |
| 175 | + console.error(`[document-converter] Failed to convert ${sourcePath}:`, errorMessage) |
| 176 | + |
| 177 | + return { |
| 178 | + success: false, |
| 179 | + outputPath: '', |
| 180 | + error: errorMessage, |
| 181 | + durationMs: Date.now() - startTime, |
| 182 | + } |
| 183 | + } |
| 184 | +} |
0 commit comments