added function to update latest images

This commit is contained in:
Quentin Roussel
2024-08-18 01:17:50 +08:00
parent ab1d1669a6
commit 16851517ef
5 changed files with 42 additions and 5 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
images/*.png

BIN
bg.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

View File

@@ -1,3 +1,4 @@
import { time } from 'console';
import fs from 'fs'; import fs from 'fs';
import client from 'https'; import client from 'https';
@@ -34,7 +35,7 @@ function downloadImage(time_string, filepath) {
} else { } else {
// Consume response data to free up memory // Consume response data to free up memory
res.resume(); res.resume();
reject(new Error(`Request Failed With a Status Code: ${res.statusCode}`)); reject(new Error(res.statusCode));
} }
}); });
@@ -49,7 +50,38 @@ export async function initImages(count) {
await downloadImage(time_string, filename) await downloadImage(time_string, filename)
} catch (error) { } catch (error) {
//Response 302, we've reached the latest available image //Response 302, we've reached the latest available image
if(error.message === '302') {
console.log('Could not download image after ' + time_string);
return; return;
} }
} }
}
}
export async function updateImages(count) {
let time_strings = [];
for(let i = count; i >= 0 ; i--) {
time_strings.push(getTimeString(i));
}
let files = fs.readdirSync('images/');
let image_count = files.length;
//Try to download new images
for(let time_string of time_strings) {
if (!files.includes(`${time_string}.png`)) {
try {
await downloadImage(time_string, `images/${time_string}.png`);
image_count++;
} catch (error) {
console.log("No more images available");
break;
}
}
}
//Remove old files
for(let file of files.sort().slice(0, image_count-count)) {
console.log(`Deleting ${file}`);
fs.unlinkSync(`images/${file}`);
}
} }

1
images/.gitignore vendored
View File

@@ -1 +0,0 @@
*.png

View File

@@ -1,6 +1,11 @@
import { initImages } from './generate.mjs'; import { initImages, updateImages } from './generate.mjs';
initImages(10).then(() => { initImages(10).then(() => {
console.log('Downloaded images successfully'); console.log('Downloaded initial images successfully');
}); });
setInterval(() => {
updateImages(10).then(() => {
console.log('Updated images successfully');
});
}, 5 * 60 * 1000);