Skip to content

Commit

Permalink
Only update DNS entry on start and when IP changed
Browse files Browse the repository at this point in the history
  • Loading branch information
aequabit committed Dec 8, 2020
1 parent 6449d77 commit bab5492
Show file tree
Hide file tree
Showing 3 changed files with 733 additions and 586 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"typescript": "^2.7.2"
},
"dependencies": {
"cloudflare": "^2.4.1",
"cloudflare": "^2.7.0",
"moment": "^2.22.2",
"npmlog": "^4.1.2",
"request": "^2.87.0",
Expand All @@ -23,7 +23,7 @@
"scripts": {
"start": "nodemon --watch src --exec ts-node src/index.ts",
"test": "nodemon --watch src --exec ts-node src/test.ts",
"build": "npm run lint && tsc",
"build": "tsc",
"lint": "tslint -c tslint.json -p tsconfig.json",
"serve": "node dist/index.js"
},
Expand Down
49 changes: 31 additions & 18 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,35 +8,48 @@ import Logger from './lib/Logger';
// CloudFlare has a limit of 1200 calls every five minutes
const UPDATE_INTERVAL = 10 * 1000;

const cf = new CloudFlare(config);
let lastIp = null;

const getIp = async (): Promise<string> => {
const response = await request({ uri: 'https://wtfismyip.com/json' });
const response = await request({ uri: 'https://api.myip.com' });

try {
return JSON.parse(response).YourFuckingIPAddress;
return JSON.parse(response).ip;
} catch (err) {
return null;
}
}

(async (): Promise<void> => {
Logger.info('cloudflare', 'Started DNS updater');
const updateDnsEntry = async () => {
let ip = await getIp();

// Failed to get IP
if (ip === null) {
Logger.error('app', 'Failed to get IP address');
return;
}

// IP didn't change (will run once because lastIp isn't set initially)
if (ip === lastIp)
return;

const cf = new CloudFlare(config);
if (lastIp !== null)
Logger.info('app', 'IP change from %s to %s', lastIp, ip);

setInterval(async () => {
const ip = await getIp();
lastIp = ip;

if (ip === null) {
Logger.error('ip', 'Failed to get IP address');
return;
}
try {
await cf.updateRecord(ip);

try {
await cf.updateRecord(ip);
Logger.info('cloudflare', 'Updated IP for %s to %s', cf.getConfig().domain, ip);
} catch (err) {
Logger.error('cloudflare', 'Error while getting external IP: %s', err.message);
}
Logger.info('cloudflare', 'Updated IP for %s to %s', cf.getConfig().domain, ip);
} catch (err) {
Logger.error('cloudflare', 'Error while updating DNS record IP: %s', err.message);
}
};

(async (): Promise<void> => {
Logger.info('app', 'Started');

}, UPDATE_INTERVAL);
setInterval(async () => await updateDnsEntry(), UPDATE_INTERVAL);
})();
Loading

0 comments on commit bab5492

Please sign in to comment.