forked from pferraris/docker-cloudns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
102 lines (92 loc) · 2.71 KB
/
index.js
File metadata and controls
102 lines (92 loc) · 2.71 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
102
const https = require('https');
const { Resolver } = require('dns');
const domain = process.env.CLOUDNS_DOMAIN;
const token = process.env.CLOUDNS_TOKEN;
const interval = process.env.CLOUDNS_INTERVAL || 30 * 60 * 1000;
const dnsServer = process.env.CLOUDNS_DNS_SERVER || '8.8.8.8';
const resolver = new Resolver();
resolver.setServers([dnsServer]);
function callClouDNSUpdate(token) {
return new Promise((resolve, reject) => {
https.get(`https://ipv4.cloudns.net/api/dynamicURL/?q=${token}`, res => {
if (res.statusCode === 200) {
try {
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => { resolve(rawData); });
} catch (err) {
reject(err);
}
} else {
reject(res.statusCode);
}
});
});
}
function getCurrentIP(domain) {
return new Promise((resolve, reject) => {
resolver.resolve4(domain, (err, currentIp) => {
if (err) {
reject(err);
} else {
resolve(currentIp);
}
});
});
}
function getRealIP() {
return new Promise((resolve, reject) => {
https.get('https://api.ipify.org/', res => {
if (res.statusCode === 200) {
try {
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => { resolve(rawData); });
} catch (err) {
reject(err);
}
} else {
reject(res.statusCode);
}
});
});
}
function updateIP() {
console.log('-'.repeat(50));
console.log('Starting UpdateIP process...');
getRealIP().then(realIP => {
console.log(`Real IP is ${realIP}`);
return getCurrentIP(domain).then(currentIP => {
console.log(`Current IP for ${domain} is ${currentIP}`);
if (currentIP != realIP) {
return callClouDNSUpdate(token).then(response => {
console.log(`IP ${realIP} updated successfully for ${domain}: ${response}`);
});
} else {
console.log(`Update no needed for ${domain}`);
}
});
}).catch(err=> {
console.error('Error: ', err);
}).finally(() => {
console.log('UpdateIP process finished');
});
}
console.log('Daemon started');
process.on('exit', code => { console.log('Daemon stopped. Exit status: ', code); });
if (!domain) {
console.error('Missing domain');
process.exit(1);
} else if (!token) {
console.error('Missing token');
process.exit(1);
} else {
console.log('Domain:', domain);
console.log('Token:', token);
console.log('Interval:', interval / 1000, 'seconds');
updateIP();
const task = setInterval(updateIP, interval);
process.on('exit', () => { clearInterval(task); });
}