-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpbDNSUpdater.js
88 lines (79 loc) · 3.24 KB
/
pbDNSUpdater.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
require('dotenv').config();
const ipUrl = 'https://api.ipify.org?format=json';
const secretApiKey = process.env.SECRETKEY;
const apiKey = process.env.APIKEY;
const domainsString = process.env.DOMAINS;
const domains = domainsString.split(',');
const domainBaseUrl = 'https://porkbun.com/api/json/v3/dns/retrieve/';
const apiBaseUrl = 'https://porkbun.com/api/json/v3/dns/edit/';
let externalIp = '';
function runFetch() {
fetch(ipUrl)
.then((response) => response.json())
.then((data) => {
let domainData = [];
if (data && externalIp !== data.ip) {
externalIp = data.ip;
console.log('New IP: ' + data.ip);
domains.forEach(function (domain) {
const options = {
method: 'POST',
headers: {
Accept: 'application/json',
"Content-Type": 'application/json;charset=UTF-8',
},
body: JSON.stringify({
secretapikey: secretApiKey,
apikey: apiKey,
}),
};
domainData.push(fetch(domainBaseUrl + domain, options));
})
} else {
throw new Error('Message: IP has not changed');
}
return Promise.all(domainData);
})
.then((responses) => Promise.all(responses.map((response) => response.json())))
.then((dataArray) => {
let fetchPromises = [];
dataArray.forEach(function (domainData, index) {
let records = domainData.records;
records.forEach(function (record) {
if (record.type === 'A') {
const options = {
method: 'POST',
headers: {
Accept: 'application/json',
"Content-Type": 'application/json;charset=UTF-8',
},
body: JSON.stringify({
secretapikey: secretApiKey,
apikey: apiKey,
name: record.name.substring(0, 3) === 'www' ? 'www' : '',
type: record.type,
content: externalIp
}),
};
fetchPromises.push(fetch(apiBaseUrl + domains[index] + '/' + record.id, options));
}
});
})
return Promise.all(fetchPromises);
})
.then((responses) => Promise.all(responses.map((response) => response.json())))
.then((dataArray) => {
dataArray.forEach((data) => {
if (data.status === 'ERROR') {
clearInterval(updateProcess);
runFetch();
} else {
console.log('Message: ' + data.status);
}
});
})
.catch((error) => {
console.log(error.message);
});
}
const updateProcess = setInterval(runFetch, 3600000);