wallpaper.js
2.53 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
61
62
63
64
65
66
67
import { System as SystemConfig } from '../config'
const path = require('path')
var http = require('https')
const util = require('util')
const koa2Req = require('koa2-request')
// const mimeType = require('mime-types')
// const chalk = require('chalk') // 带色彩的控制台输出
const fs = require('fs')
const config = {
format: 'js',
idx: 0,
n: 1,
baseUrl: 'https://cn.bing.com'
}
let getImg = async (url, photoPath, filename) => {
return new Promise(resolve => {
http.get(url, function (res) {
let imgData = ''
let contentLength = parseInt(res.headers['content-length'])
res.setEncoding('binary')
res.on('data', function (chunk) {
imgData += chunk
let process = ((imgData.length) / contentLength) * 100
let percent = parseInt(((process).toFixed(0)))
// 任务栏进度条
console.log(percent)
})
res.on('end', function () {
fs.writeFile(photoPath, imgData, 'binary', function (err) {
if (err) {
console.log(err)
// console.log(chalk.red(`Failed!`))
} else {
resolve(SystemConfig.API_server_type + SystemConfig.API_server_host + `/${filename}`)
}
})
})
})
})
}
export let get = async (ctx) => {
const date = new Date()
const toPad2 = num => num.padStart(2, '0')
const filename = `${date.getFullYear()}${toPad2(`${date.getMonth() + 1}`)}${toPad2(`${date.getDate()}`)}`
const filePath = `../../assets/wallpapers/${filename}`
const jsonPath = path.join(__dirname, `${filePath}.json`)
if (fs.existsSync(jsonPath)) {
const readFile = util.promisify(fs.readFile)
const data = await readFile(jsonPath)
ctx.body = JSON.parse(data.toString())
} else {
// request选项
const photoPath = path.join(__dirname, `${filePath}.jpg`)
const {format, idx, n} = config
var res = await koa2Req(`http://cn.bing.com/HPImageArchive.aspx?format=${format}&idx=${idx}&n=${n}`)
const __img = JSON.parse(res.body).images[0]
const __path = await getImg(`https://cn.bing.com${__img.urlbase}_1920x1080.jpg&rf=NorthMale_1920x1080.jpg`, photoPath, `assets/wallpapers/${filename}.jpg`)
__img.path = __path
// let __data = fs.readFileSync(photoPath)
// let fileMimeType = mimeType.lookup(photoPath) // 获取文件的 memeType
// // 转换为 data:image/jpeg;base64,***** 格式的字符串
// __img.base64 = `data:${fileMimeType};base64,${Buffer.from(__data).toString('base64')}`
fs.writeFileSync(jsonPath, JSON.stringify(__img))
ctx.body = __img
}
}