Skip to content

Commit

Permalink
feat(alert): the ability to send to discord webhook url
Browse files Browse the repository at this point in the history
  • Loading branch information
wajeht committed Nov 11, 2023
1 parent d826146 commit 94668d9
Show file tree
Hide file tree
Showing 13 changed files with 154 additions and 53 deletions.
12 changes: 6 additions & 6 deletions dist/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@wajeht/cdns",
"version": "1.1.7",
"description": "a cli tool to automatically update cloudflare dns records",
"description": "a cli tool to schedule automatic updates for cloudflare dns records",
"main": "./dist/src/index.js",
"bin": {
"cdns": "./dist/src/index.js"
Expand Down Expand Up @@ -46,12 +46,12 @@
"author": "@wajeht",
"license": "MIT",
"devDependencies": {
"@commitlint/cli": "^18.2.0",
"@commitlint/config-conventional": "^18.1.0",
"@commitlint/cli": "^18.4.0",
"@commitlint/config-conventional": "^18.4.0",
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/commit-analyzer": "^11.1.0",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.2.2",
"@semantic-release/github": "^9.2.3",
"@semantic-release/npm": "^11.0.1",
"@semantic-release/release-notes-generator": "^12.1.0",
"@types/node": "^20.9.0",
Expand All @@ -68,9 +68,9 @@
"vitest": "^0.34.6"
},
"dependencies": {
"@inquirer/prompts": "^3.2.0",
"@inquirer/prompts": "^3.3.0",
"@prisma/client": "^5.5.2",
"axios": "^1.6.0",
"axios": "^1.6.1",
"commander": "^11.1.0",
"node-cron": "^3.0.3",
"prisma": "^5.5.2"
Expand Down
32 changes: 28 additions & 4 deletions dist/src/commands/add.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const db_1 = require("../database/db");
const utils_1 = require("../utils");
const prompts_1 = require("@inquirer/prompts");
async function add(params) {
let { cloudflare_email, cloudflare_api_token, zone_name, ip_address, frequency } = params;
let { cloudflare_email, cloudflare_api_token, zone_name, ip_address, frequency, discord_webhook_url, } = params;
let sure = false;
while (!sure) {
if (params.interactive) {
Expand Down Expand Up @@ -38,10 +38,22 @@ async function add(params) {
if (!frequency) {
frequency = await (0, prompts_1.input)({
message: 'Enter frequency',
validate: (value) => value.length !== 0,
validate: function (value) {
if (value.length === 0)
return true;
const parsedValue = parseInt(value);
const isNumber = !isNaN(parsedValue) && parsedValue > 0;
// prettier-ignore
return value.length !== 0 && isNumber ? true : 'The frequency must be in minutes. For example, 60 for every hour.';
},
default: '60',
});
}
if (!discord_webhook_url) {
discord_webhook_url = await (0, prompts_1.input)({
message: 'Enter discord webhook url (optional)',
});
}
}
if (!cloudflare_email || !cloudflare_api_token || !zone_name || !ip_address || !frequency) {
const requiredParams = {
Expand All @@ -56,22 +68,32 @@ async function add(params) {
console.error('Missing required parameters:', missingParams.join(', '));
return process.exit(1);
}
console.table([{ cloudflare_email, cloudflare_api_token, zone_name, ip_address, frequency }]);
console.table([
{
cloudflare_email,
cloudflare_api_token,
zone_name,
ip_address,
frequency,
discord_webhook_url,
},
]);
sure =
(await (0, prompts_1.input)({
message: 'Are you sure these are the correct information? (y/n)',
validate: (value) => value === 'y' || value === 'n',
})) === 'y';
if (!sure) {
const modify = await (0, prompts_1.input)({
message: 'What do you want to change? \nemail (e), cloudflare_api_token (a), zone_name (z), ip_address (p), frequency (f)?',
message: 'What do you want to change? \nemail (e), cloudflare_api_token (a), zone_name (z), ip_address (p), frequency (f), discord_webhook_url (d)?',
validate: (value) => ['e', 'a', 'z', 'r', 'f'].includes(value) === true,
});
cloudflare_email = modify === 'e' ? '' : cloudflare_email;
cloudflare_api_token = modify === 'a' ? '' : cloudflare_api_token;
zone_name = modify === 'z' ? '' : zone_name;
ip_address = modify === 'p' ? '' : ip_address;
frequency = modify === 'f' ? '' : frequency;
discord_webhook_url = modify === 'd' ? '' : discord_webhook_url;
}
}
await db_1.db.configuration
Expand All @@ -83,13 +105,15 @@ async function add(params) {
cloudflare_email,
cloudflare_api_token,
ip_address,
discord_webhook_url,
frequency: parseInt(frequency) || 60,
},
create: {
cloudflare_email,
cloudflare_api_token,
zone_name,
ip_address,
discord_webhook_url,
frequency: parseInt(frequency) || 60,
},
})
Expand Down
1 change: 1 addition & 0 deletions dist/src/commands/schedule.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ async function schedule() {
console.log(`updating dns records for id: ${r.id}!`);
await cloudflareApi.updateContent(zoneInfo.result[0].id, r.id, currentIpAddress);
console.log(`done updating dns records for id: ${r.id}!`);
await (0, utils_1.alertToDiscord)(r.content, currentIpAddress);
}
catch (error) {
console.error(`something went wrong while updating record for id: ${r.id}!`);
Expand Down
1 change: 1 addition & 0 deletions dist/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ program
.option('-z, --zone_name <string>', 'the zone which holds the record')
.option('-p, --ip_address <string>', 'the ip address of current server')
.option('-f, --frequency <number>', 'the frequency of the update')
.option('-d, --discord_webhook_url <string>', 'the discord webhook url')
.action(async (option) => await (0, add_1.add)(option));
program
.command('status')
Expand Down
47 changes: 47 additions & 0 deletions dist/src/utils/alert-to-discord.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.alertToDiscord = void 0;
const format_custom_date_1 = require("./format-custom-date");
const axios_1 = __importDefault(require("axios"));
const db_1 = require("../database/db");
async function alertToDiscord(fromIpAddress, toIpAddress) {
const configuration = await db_1.db.configuration.findFirst();
if (!configuration) {
console.error('no configuration found');
return false;
}
if (!configuration.discord_webhook_url) {
console.error('no discord webhook url found');
return false;
}
const embeds = [
{
title: '',
color: 5174599,
footer: {
text: `📅 ${(0, format_custom_date_1.formatCustomDate)(new Date())}`,
},
fields: [
{
name: 'CDNS Update!',
value: `You're ip address has been updated from ${fromIpAddress} to ${toIpAddress}!`,
},
],
},
];
const data = JSON.stringify({ embeds });
const headers = { 'Content-Type': 'application/json' };
try {
await axios_1.default.post(configuration.discord_webhook_url, data, { headers });
}
catch (error) {
// @ts-ignore
console.error(error?.response?.data?.message);
return false;
}
return true;
}
exports.alertToDiscord = alertToDiscord;
2 changes: 0 additions & 2 deletions dist/src/utils/env.js

This file was deleted.

18 changes: 18 additions & 0 deletions dist/src/utils/format-custom-date.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatCustomDate = void 0;
function formatCustomDate(date) {
const options = {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: true,
timeZoneName: 'short',
};
const formattedDate = date.toLocaleString('en-US', options);
return formattedDate;
}
exports.formatCustomDate = formatCustomDate;
6 changes: 5 additions & 1 deletion dist/src/utils/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.timeToCron = exports.getIPAddress = exports.CloudflareApiClient = void 0;
exports.alertToDiscord = exports.formatCustomDate = exports.timeToCron = exports.getIPAddress = exports.CloudflareApiClient = void 0;
var cloudflare_api_client_1 = require("./cloudflare-api-client");
Object.defineProperty(exports, "CloudflareApiClient", { enumerable: true, get: function () { return cloudflare_api_client_1.CloudflareApiClient; } });
var get_ip_address_1 = require("./get-ip-address");
Object.defineProperty(exports, "getIPAddress", { enumerable: true, get: function () { return get_ip_address_1.getIPAddress; } });
var time_to_cron_1 = require("./time-to-cron");
Object.defineProperty(exports, "timeToCron", { enumerable: true, get: function () { return time_to_cron_1.timeToCron; } });
var format_custom_date_1 = require("./format-custom-date");
Object.defineProperty(exports, "formatCustomDate", { enumerable: true, get: function () { return format_custom_date_1.formatCustomDate; } });
var alert_to_discord_1 = require("./alert-to-discord");
Object.defineProperty(exports, "alertToDiscord", { enumerable: true, get: function () { return alert_to_discord_1.alertToDiscord; } });
35 changes: 0 additions & 35 deletions dist/src/utils/utils.js

This file was deleted.

40 changes: 36 additions & 4 deletions src/commands/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,18 @@ type Params = {
zone_name: string;
ip_address: string;
frequency: string;
discord_webhook_url?: string;
};

export async function add(params: Params) {
let { cloudflare_email, cloudflare_api_token, zone_name, ip_address, frequency } = params;
let {
cloudflare_email,
cloudflare_api_token,
zone_name,
ip_address,
frequency,
discord_webhook_url,
} = params;

let sure = false;

Expand Down Expand Up @@ -51,10 +59,22 @@ export async function add(params: Params) {
if (!frequency) {
frequency = await input({
message: 'Enter frequency',
validate: (value) => value.length !== 0,
validate: function (value) {
if (value.length === 0) return true;
const parsedValue = parseInt(value);
const isNumber = !isNaN(parsedValue) && parsedValue > 0;
// prettier-ignore
return value.length !== 0 && isNumber ? true : 'The frequency must be in minutes. For example, 60 for every hour.';
},
default: '60',
});
}

if (!discord_webhook_url) {
discord_webhook_url = await input({
message: 'Enter discord webhook url (optional)',
});
}
}

if (!cloudflare_email || !cloudflare_api_token || !zone_name || !ip_address || !frequency) {
Expand All @@ -74,7 +94,16 @@ export async function add(params: Params) {
return process.exit(1);
}

console.table([{ cloudflare_email, cloudflare_api_token, zone_name, ip_address, frequency }]);
console.table([
{
cloudflare_email,
cloudflare_api_token,
zone_name,
ip_address,
frequency,
discord_webhook_url,
},
]);

sure =
(await input({
Expand All @@ -85,7 +114,7 @@ export async function add(params: Params) {
if (!sure) {
const modify = await input({
message:
'What do you want to change? \nemail (e), cloudflare_api_token (a), zone_name (z), ip_address (p), frequency (f)?',
'What do you want to change? \nemail (e), cloudflare_api_token (a), zone_name (z), ip_address (p), frequency (f), discord_webhook_url (d)?',
validate: (value) => ['e', 'a', 'z', 'r', 'f'].includes(value) === true,
});

Expand All @@ -94,6 +123,7 @@ export async function add(params: Params) {
zone_name = modify === 'z' ? '' : zone_name;
ip_address = modify === 'p' ? '' : ip_address;
frequency = modify === 'f' ? '' : frequency;
discord_webhook_url = modify === 'd' ? '' : discord_webhook_url;
}
}

Expand All @@ -106,13 +136,15 @@ export async function add(params: Params) {
cloudflare_email,
cloudflare_api_token,
ip_address,
discord_webhook_url,
frequency: parseInt(frequency) || 60,
},
create: {
cloudflare_email,
cloudflare_api_token,
zone_name,
ip_address,
discord_webhook_url,
frequency: parseInt(frequency) || 60,
},
})
Expand Down
10 changes: 9 additions & 1 deletion src/commands/schedule.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import cron from 'node-cron';
import { db } from '../database/db';
import axios, { AxiosError } from 'axios';
import { getIPAddress, ZoneInfo, CloudflareApi, CloudflareApiClient, timeToCron } from '../utils';
import {
getIPAddress,
ZoneInfo,
CloudflareApi,
CloudflareApiClient,
timeToCron,
alertToDiscord,
} from '../utils';

async function schedule() {
const configuration = await db.configuration.findFirst();
Expand Down Expand Up @@ -85,6 +92,7 @@ async function schedule() {
console.log(`updating dns records for id: ${r.id}!`);
await cloudflareApi.updateContent(zoneInfo.result[0].id, r.id, currentIpAddress);
console.log(`done updating dns records for id: ${r.id}!`);
await alertToDiscord(r.content, currentIpAddress);
} catch (error) {
console.error(`something went wrong while updating record for id: ${r.id}!`);
// @ts-ignore
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ program
.option('-z, --zone_name <string>', 'the zone which holds the record')
.option('-p, --ip_address <string>', 'the ip address of current server')
.option('-f, --frequency <number>', 'the frequency of the update')
.option('-d, --discord_webhook_url <string>', 'the discord webhook url')
.action(async (option) => await add(option));

program
Expand Down
2 changes: 2 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export { CloudflareApi, ZoneInfo, CloudflareApiClient } from './cloudflare-api-client';
export { getIPAddress } from './get-ip-address';
export { timeToCron } from './time-to-cron';
export { formatCustomDate } from './format-custom-date';
export { alertToDiscord } from './alert-to-discord';

0 comments on commit 94668d9

Please sign in to comment.