-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathxkcd.js
46 lines (39 loc) · 985 Bytes
/
xkcd.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
async function getMaxNum() {
let result = await $http.get("https://xkcd.com/info.0.json");
return result.data.num;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function requestFailed(resp) {
return resp == null || resp.response == null || resp.response.statusCode != 200;
}
async function fetch() {
const cache = $cache.get("image");
const maxNum = await getMaxNum();
const num = getRandomInt(1, maxNum);
const json = await $http.get(`https://xkcd.com/${num}/info.0.json`);
if (requestFailed(json)) {
return cache;
}
const file = await $http.download(json.data.img);
if (requestFailed(file)) {
return cache;
}
const image = file.data.image;
if (image) {
$cache.set("image", image);
}
return image;
}
const image = await fetch();
$widget.setTimeline(ctx => {
return {
type: "image",
props: {
image: image,
resizable: true,
scaledToFit: true
}
}
});