(
server: FastifyInstance,
dbManager: DatabaseManager,
options: ImportRouteOptions = {}
)
| 45 | } |
| 46 | |
| 47 | export function registerImportRoutes( |
| 48 | server: FastifyInstance, |
| 49 | dbManager: DatabaseManager, |
| 50 | options: ImportRouteOptions = {} |
| 51 | ): void { |
| 52 | const sourceManager = |
| 53 | options.sourceManager ?? |
| 54 | new ArchiveImportSourceManager({ |
| 55 | tempRoot: fs.mkdtempSync(path.join(os.tmpdir(), 'chatlab-import-sources-')), |
| 56 | }) |
| 57 | const runPreparedImport = |
| 58 | options.runPreparedImport ?? |
| 59 | (async (manifestPath: string, onProgress: (progress: unknown) => void) => { |
| 60 | const result = await streamImport(dbManager, manifestPath, { |
| 61 | formatId: 'google-chat-takeout', |
| 62 | nativeBinding: resolveNativeBinding(), |
| 63 | onProgress: onProgress as any, |
| 64 | }) |
| 65 | return { |
| 66 | success: result.success, |
| 67 | sessionId: result.sessionId, |
| 68 | error: result.error, |
| 69 | messageCount: result.diagnostics?.messagesWritten ?? 0, |
| 70 | memberCount: 0, |
| 71 | } |
| 72 | }) |
| 73 | |
| 74 | server.addHook('onClose', async () => { |
| 75 | await sourceManager.close() |
| 76 | }) |
| 77 | |
| 78 | server.post('/_web/import-sources', async (request, reply) => { |
| 79 | const data = await (request as any).file({ |
| 80 | limits: { fileSize: ARCHIVE_UPLOAD_LIMIT }, |
| 81 | }) |
| 82 | if (!data) return reply.code(400).send({ success: false, error: 'error.no_file_selected' }) |
| 83 | |
| 84 | const uploadPath = path.join(os.tmpdir(), `chatlab-archive-${randomUUID()}.zip`) |
| 85 | try { |
| 86 | await pipeline(data.file, fs.createWriteStream(uploadPath, { flags: 'wx' })) |
| 87 | if (data.file.truncated) { |
| 88 | cleanupTemp(uploadPath) |
| 89 | return reply.code(413).send({ success: false, error: 'error.archive_limit_exceeded' }) |
| 90 | } |
| 91 | |
| 92 | const source = await sourceManager.prepareOwnedArchive(uploadPath) |
| 93 | return { success: true, source } |
| 94 | } catch (error) { |
| 95 | cleanupTemp(uploadPath) |
| 96 | if (error instanceof ArchiveImportError) { |
| 97 | return reply.code(400).send({ success: false, error: error.code }) |
| 98 | } |
| 99 | return reply.code(400).send({ |
| 100 | success: false, |
| 101 | error: error instanceof Error ? error.message : String(error), |
| 102 | }) |
| 103 | } |
| 104 | }) |
no test coverage detected