-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
88 lines (69 loc) · 2.61 KB
/
index.js
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const config = require('./config.json');
const fileType = require('file-type');
const fs = require('fs');
const request = require('request');
const rp = require('request-promise-native');
const wallpaper = require('wallpaper');
const change = async (start = 0) => {
try {
if (!config) {
return console.log('Please configure the `config.json`.');
}
if (start === config.maxRetry) {
return console.log('We tried our best, but were unable to change the wallpaper. Sorry.');
}
const url = `https://www.reddit.com/r/${randomElement(config.subreddits)}/${config.sort}.json?t=${config.from}&limit=${config.limit}`;
const options = {
uri: url,
json: true,
simple: true,
};
const path = `${config.directory}/wallpaper`;
let name = '';
const directoryExists = await exists(config.directory);
if (!directoryExists) {
await makeDirectory(config.directory);
}
const obj = await rp(options);
const imgUrl = await getURL(obj);
await download(imgUrl, path);
const type = await getType(path);
if (!type || !config.types.includes(type.ext)) throw 'type is null';
name = `${path}.${type.ext}`;
await renameDirectory(path, name);
wallpaper.set(name);
console.log('Success!');
}
catch (e) {
console.error(e);
change(start + 1);
}
};
const getURL = async obj => {
const posts = obj.data.children
.filter(post =>
post.kind.toLowerCase() === 't3' &&
post.data &&
config.domains.includes(post.data.domain.toLowerCase()) &&
post.data.over_18 === (config.over_18 === 'true') &&
post.data.score >= config.score &&
post.data.preview.images[0].source.width >= config.minimum_image_size.width &&
post.data.preview.images[0].source.height >= config.minimum_image_size.height
)
.map(post => ({
url: post.data.preview.images[0].source.url,
domain: post.data.domain.toLowerCase(),
}));
if (!posts) {
throw 'No posts match the config criteria.';
}
return randomElement(posts).url;
};
const exists = path => new Promise(res => fs.stat(path, (err) => err ? res(true) : res(false)));
const makeDirectory = path => new Promise((res, rej) => fs.mkdir(path, (err) => err ? rej(err) : res()));
const renameDirectory = (oldPath, newPath) => new Promise((res, rej) =>
fs.rename(oldPath, newPath, (err) => err ? rej(err) : res()));
const randomElement = array => array[Math.floor(Math.random() * array.length)];
const download = (uri, path) => new Promise(resolve => request(uri).pipe(fs.createWriteStream(path)).on('close', resolve));
const getType = path => new Promise((resolve, reject) => fs.readFile(path, (err, data) => err ? reject(err) : resolve(fileType(data))));
change();