mirror of
https://github.com/markuryy/shark.git
synced 2025-12-12 19:51:01 +00:00
fix(dl): add retry logic for network errors and rate limits
This commit is contained in:
@@ -24,7 +24,8 @@ export async function downloadTrack(
|
||||
downloadURL: string,
|
||||
musicFolder: string,
|
||||
format: string,
|
||||
onProgress?: ProgressCallback
|
||||
onProgress?: ProgressCallback,
|
||||
retryCount: number = 0
|
||||
): Promise<string> {
|
||||
// Generate paths
|
||||
const paths = generateTrackPath(track, musicFolder, format, false);
|
||||
@@ -50,14 +51,20 @@ export async function downloadTrack(
|
||||
console.log('Temp path:', paths.tempPath);
|
||||
|
||||
try {
|
||||
// Fetch the track with streaming
|
||||
// Fetch the track with timeout
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 60000); // 60 second timeout
|
||||
|
||||
const response = await fetch(downloadURL, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
|
||||
}
|
||||
},
|
||||
signal: controller.signal
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
@@ -100,7 +107,7 @@ export async function downloadTrack(
|
||||
console.log('Download complete!');
|
||||
return finalPath;
|
||||
|
||||
} catch (error) {
|
||||
} catch (error: any) {
|
||||
// Clean up temp file on error
|
||||
try {
|
||||
if (await exists(paths.tempPath)) {
|
||||
@@ -110,6 +117,18 @@ export async function downloadTrack(
|
||||
console.error('Error cleaning up temp file:', cleanupError);
|
||||
}
|
||||
|
||||
// Retry on network errors or timeout (max 3 retries)
|
||||
const networkErrors = ['ECONNABORTED', 'ECONNREFUSED', 'ECONNRESET', 'ENETRESET', 'ETIMEDOUT'];
|
||||
const isNetworkError = error.code && networkErrors.includes(error.code);
|
||||
const isTimeout = error.name === 'AbortError';
|
||||
|
||||
if ((isNetworkError || isTimeout) && retryCount < 3) {
|
||||
const errorType = isTimeout ? 'timeout' : error.code;
|
||||
console.log(`[DEBUG] Download ${errorType}, waiting 2s before retry (${retryCount + 1}/3)...`);
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
return downloadTrack(track, downloadURL, musicFolder, format, onProgress, retryCount + 1);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user