diff --git a/src/lucida.ts b/src/lucida.ts index 118714b..97ae8fe 100644 --- a/src/lucida.ts +++ b/src/lucida.ts @@ -25,27 +25,46 @@ export async function lucida(album: URL, baseTimeout: number, context: BrowserCo console.log(`Downloading ${albumName} (${trackCount} tracks) from ${album.href}...`); console.log(`Setting timeout to ${baseTimeout * trackCount} ms...`); - try { - const download: Download = await page.waitForEvent('download', { timeout: baseTimeout * trackCount }); - // Start download - await page.getByText('download full album').click(); - // Save the download to the Downloads folder - // TODO Set path (configurable) - await download.saveAs('/home/tdpeuter/Downloads/lucida/' + download.suggestedFilename()); + // Start download + await page.getByText('download full album').click(); - // Check if the album has a booklet - const bookPath: File | null = await booklet(album, context); - if (bookPath !== null) { - console.log(`Downloaded booklet ${bookPath.name}`); - // TODO Add booklet to ZIP + let download: Download | null = null; + const timeout: number = baseTimeout * trackCount; + const start: number = Date.now(); + let retryCount: number = 0; + + // Retry file download if it fails + while (!download && (Date.now() - start) < timeout && retryCount < trackCount) { + try { + download = await page.waitForEvent('download'); + } catch { + const retry: Locator = page.getByText('Retry'); + if (await retry.count() !== 0 && await retry.isVisible() && await retry.isEnabled()) { + await page.getByText('Retry').click(); + console.log('Retrying download...'); + retryCount++; + } } + } - await page.close(); - return true; - } catch { + if (download === null) { await page.close(); return 'Download timed out'; } + + // Save the download to the Downloads folder + // TODO Set path (configurable) + await download.saveAs('/home/tdpeuter/Downloads/lucida/' + download.suggestedFilename()); + + // Check if the album has a booklet + const bookPath: File | null = await booklet(album, context); + if (bookPath !== null) { + console.log(`Downloaded booklet ${bookPath.name}`); + // TODO Add booklet to ZIP + } + + await page.close(); + return true; } async function booklet(album: URL, context: BrowserContext): Promise {