-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdate-wallpapers
More file actions
executable file
·60 lines (47 loc) · 1.65 KB
/
update-wallpapers
File metadata and controls
executable file
·60 lines (47 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env node
const https = require("https");
const fs = require("fs");
const streamTransform = require("stream").Transform;
const path = require("path");
const filenameUrlOffset = 1;
const wallpaperDirArgPosition = 2;
const config = {
wallpapersDir: ".config/wallpaper",
wallpaperAPI: "https://www.reddit.com/r/earthporn/top/.json?limit=10&t=month",
};
const wallpapersDir = process.argv[wallpaperDirArgPosition] ?
process.argv[wallpaperDirArgPosition] : path.join(process.env.HOME, config.wallpapersDir);
const getFilename = (url) => url.substring(url.lastIndexOf("/") + filenameUrlOffset );
const getImageUrls = (data) => JSON.parse(data).data.children.map(post => post.data.url);
function download(url) {
https.request(url, function(response) {
const data = new streamTransform();
let writeError = null;
response.on("data", function(chunk) {
data.push(chunk);
});
data.pipe(fs.createWriteStream(
path.join(wallpapersDir, getFilename(url))
).on("error", (err) => {
writeError = err;
}));
response.on("end", function(err) {
writeError ?
console.log("Error downloading", url, "to", path.join(wallpapersDir, getFilename(url)), ":", writeError.message) :
console.log("Downloaded", url, "to", path.join(wallpapersDir, getFilename(url)));
});
}).end().on("error", (err) => {
console.log("Error: " + err.message);
});
}
https.get(config.wallpaperAPI, (resp) => {
let data = "";
resp.on("data", (chunk) => {
data += chunk;
});
resp.on("end", () => {
getImageUrls(data).forEach(download);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});