cdn_cache.js
3.1 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
*
* @author: chenfeng<feng.chen@yoho.cn>
* @date: 16/10/19
*/
'use strict';
import Model from './model';
import utils from 'utility';
import rp from 'request-promise';
import ws from '../../lib/ws';
class CdnCache extends Model {
constructor() {
super('cdn_page');
}
async removeCache(queryUris, objectType) {
let self = this;
self._requestApi({
Action: 'RefreshObjectCaches',
ObjectPath: queryUris,
ObjectType: objectType
})
}
async _requestApi(params) {
let self = this;
let cdns = await self.findAll();
if (!cdns.length) {
return;
}
params = Object.assign(params, {
Format: 'JSON',
Version: '2014-11-11',
AccessKeyId: cdns[0].keyId,
SignatureMethod: 'HMAC-SHA1',
TimeStamp: self._getUtcTime(new Date()),
SignatureVersion: '1.0',
SignatureNonce: parseInt(Math.random() * 100000, 10) + ''
});
let sign = self._sign(params, cdns[0].keySecret);
params.Signature = sign;
rp({
uri: `${cdns[0].scheme}://${cdns[0].cdnApi}`,
qs: params,
json: true
})
.then(function (res) {
self._broadcast(`清理提交成功,RefreshTaskId:${res.RefreshTaskId}`)
})
.catch(function (err) {
self._broadcast(`清理失败:${err.response.body}`)
});
}
_getUtcTime(date) {
let year = date.getUTCFullYear();
let month = date.getUTCMonth() + 1;
let day = date.getUTCDate() < 10 ? '0' + date.getUTCDate() : date.getUTCDate();
let hour = date.getUTCHours() < 10 ? '0' + date.getUTCHours() : date.getUTCHours();
let minute = date.getUTCMinutes() < 10 ? '0' + date.getUTCMinutes() : date.getUTCMinutes();
let second = date.getUTCSeconds() < 10 ? '0' + date.getUTCSeconds() : date.getUTCSeconds();
month = month < 10 ? '0' + month : month;
return `${year}-${month}-${day}T${hour}:${minute}:${second}Z`
}
_sign(params, keySecret) {
let data = {};
Object.keys(params).sort().forEach(k => data[k]=params[k]);
let signString = '';
Object.keys(data).forEach(k => {
data[k] = encodeURIComponent(data[k])
signString += `&${k}=${data[k]}`;
});
if (signString) {
signString = `GET&%2F&${encodeURIComponent(signString.substring(1, signString.length))}`;
let sign = utils.hmac('sha1', keySecret + '&', signString);
return sign;
}
return '';
}
_broadcast(message) {
console.log(message)
ws.broadcast(`/cdn_cache/log`, {
message: message
});
}
async init() {
let count = await this.count({});
if (count === 0) {
await this.insert({
scheme: 'https',
cdnApi: 'cdn.aliyuncs.com',
keyId: 'Mt6m3xVdWddj8bDe',
keySecret: 'ExHpmJJ7ayJEEMz2LUffKRe3ehMGDs'
})
}
}
}
export default CdnCache;