Skip to content

Commit

Permalink
fix: partial downloads in cache (#11)
Browse files Browse the repository at this point in the history
Bug in #5 occurred when the header check download (which only requests
the first 6 bytes) would get cached and the final download would receive
that partial body instead of the full. Fix is to bust cache by appending
query param.
  • Loading branch information
0ui committed Jul 27, 2023
1 parent 6a31cab commit ac93c56
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions js/scrubber.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,15 @@ window.addEventListener('load', () => {
return url;
});

function bustCache(url) {
if (url === 'undefined') {
return url;
}
const urlObject = new URL(url);
urlObject.searchParams.set('gscb', Date.now());
return urlObject.toString();
}

function confirmGIF(url) {
return new Promise(function(ignore, use) {
if (url === 'undefined') return ignore('undefined');
Expand All @@ -106,7 +115,7 @@ window.addEventListener('load', () => {
h.setRequestHeader('Range', 'bytes=0-5');
h.onload = () => {
const validHeaders = ['GIF87a', 'GIF89a'];
if (validHeaders.includes(h.responseText.substr(0, 6))) use(url);
if (validHeaders.includes(h.responseText.slice(0, 6))) use(url);
else ignore('bad header');
};
h.onerror = () => ignore('error loading');
Expand All @@ -117,20 +126,20 @@ window.addEventListener('load', () => {
// Download GIF
// ============

Promise.all(urlList.map(confirmGIF)).then(reason => {
Promise.all(urlList.map(bustCache).map(confirmGIF)).then(reason => {
showError('Not a valid GIF file.');
console.log('Could not load GIF from URL because: ',reason);
}, validURL => {
console.log('downloading...',validURL);
}, validUrl => {
const downloadUrl = bustCache(validUrl);
console.time('download');
const h = new XMLHttpRequest();
h.responseType = 'arraybuffer';
h.onload = request => downloadReady = handleGIF(request.target.response);
h.onprogress = e => e.lengthComputable && downloadBar.set(e.loaded / e.total);
h.onerror = showError.bind(null, validURL);
h.open('GET', validURL, true);
h.onerror = showError.bind(null, downloadUrl);
h.open('GET', downloadUrl, true);
h.send();
url = validURL;
url = downloadUrl;
});

// Initialize player
Expand Down

0 comments on commit ac93c56

Please sign in to comment.