-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
64 lines (57 loc) · 1.92 KB
/
app.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
const express = require("express");
const request = require("request");
const app = express();
app.listen(8888, function() {
console.log("Example app listening on port 8888!");
});
const getUri = (start, number, mkt) =>
"https://www.bing.com/HPImageArchive.aspx?format=js&idx=" +
start +
"&n=" +
number +
"&mkt=" +
mkt;
const getWallpaper = (res, days_ago, mkt, type) => {
let uri;
if (days_ago <= 7) {
uri = getUri(days_ago, 1, mkt);
} else {
uri = getUri(7, days_ago - 6, mkt);
}
request(uri, (error, response, body) => {
if (!error && response.statusCode === 200) {
let images = JSON.parse(body).images;
if(type==='url'){
return res.send({url:"https://www.bing.com" + images[images.length - 1].url});
}
res.redirect("https://www.bing.com" + images[images.length - 1].url);
} else {
res.send("request error!");
}
});
};
const getRandomInteger = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
const getWallpaperByCondition = (req, res) => {
let days_ago = req.query.days_ago || 0;
let mkt = req.query.mkt || "zh-CN";
getWallpaper(res, days_ago, mkt);
};
const getWallpaperByRandom = (req, res) => {
const {type} = req.params||'';
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild"
);
res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
let days_ago = getRandomInteger(0, 15);
var mkt = getRandomInteger(0, 1) ? "zh-CN" : "en-US";
getWallpaper(res, days_ago, mkt, type);
};
app.get("/", function(req, res) {
res.sendfile("index.html");
});
app.get("/wallpaper/random/:type", getWallpaperByRandom);
app.get("/wallpaper/random", getWallpaperByRandom);
app.get("/wallpaper", getWallpaperByCondition);