feat: podpora notifikací z notify

This commit is contained in:
2023-10-12 19:09:32 +02:00
committed by Martin Berka
parent 3460d69899
commit 6d89858e3e
7 changed files with 116 additions and 17 deletions

View File

@@ -1,15 +1,18 @@
/** Notifikace pro gotify*/
import { GotifyServer, NotififaceInput, NotifikaceData } from '../../types';
import { ClientData, GotifyServer, NotififaceInput, NotifikaceData } from '../../types';
import axios, { AxiosError } from 'axios';
import dotenv from 'dotenv';
import path from 'path';
import { getToday } from "./service";
import { formatDate, getUsersByLocation } from "./utils";
import getStorage from "./storage";
const storage = getStorage();
const ENVIRONMENT = process.env.NODE_ENV || 'production'
dotenv.config({ path: path.resolve(__dirname, `../.env.${ENVIRONMENT}`) });
const gotifyDataRaw = process.env.GOTIFY_SERVERS_AND_KEYS || "{}";
const gotifyData: GotifyServer[] = JSON.parse(gotifyDataRaw);
export const gotifyCall = async (data: NotififaceInput, gotifyServers?: GotifyServer[]): Promise<any[]> => {
if (!Array.isArray(gotifyServers)) {
return []
@@ -51,15 +54,56 @@ export const gotifyCall = async (data: NotififaceInput, gotifyServers?: GotifySe
return promises;
};
/** Zavolá notifikace na všechny konfigurované způsoby notifikace, přetížení proměných na false pro jednotlivé způsoby je vypne*/
export const callNotifikace = async ({ input, teams = true, gotify = true }: NotifikaceData) => {
const notifications = [];
if (gotify) {
const gotifyPromises = await gotifyCall(input, gotifyData);
notifications.push(...gotifyPromises);
export const ntfyCall = async (data: NotififaceInput) => {
const url = process.env.NTFY_HOST
const username = process.env.NTFY_USERNAME;
const password = process.env.NTFY_PASSWD;
if (!url) {
console.log("NTFY_HOST není definován v env")
return
}
if (!username) {
console.log("NTFY_USERNAME není definován v env")
return
}
if (!password) {
console.log("NTFY_PASSWD není definován v env")
return
}
const today = formatDate(getToday());
let clientData: ClientData = await storage.getData(today);
const userByCLocation = getUsersByLocation(clientData.choices, data.user)
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64');
const promises = userByCLocation.map(async user => {
try {
const response = await axios({
url: `${url}/${user}`,
method: 'POST',
data: `${data.udalost} - spustil:${data.user}`,
headers: {
'Authorization': `Basic ${token}`,
'Tag': 'meat_on_bone'
}
});
console.log(response.data);
} catch (error) {
console.error(error);
}
})
return promises;
}
/** Zavolá notifikace na všechny konfigurované způsoby notifikace, přetížení proměných na false pro jednotlivé způsoby je vypne*/
export const callNotifikace = async ({ input, teams = true, gotify = false, ntfy = true }: NotifikaceData) => {
const notifications = [];
if (ntfy) {
const ntfyPromises = await ntfyCall(input);
if (ntfyPromises) {
notifications.push(...ntfyPromises);
}
}
/* Zatím není
if (teams) {
notifications.push(teamsCall(input));
@@ -67,6 +111,12 @@ export const callNotifikace = async ({ input, teams = true, gotify = true }: Not
// Add more notifications as necessary
//gotify bych řekl, že už je deprecated
if (gotify) {
const gotifyPromises = await gotifyCall(input, gotifyData);
notifications.push(...gotifyPromises);
}
try {
const results = await Promise.all(notifications);
return results;

View File

@@ -1,8 +1,10 @@
import express from "express";
import { getLogin, getTrusted } from "../auth";
import { getDateForWeekIndex, addChoice, removeChoices, removeChoice, updateDepartureTime, getToday, addVolatileData } from "../service";
import { addChoice, addVolatileData, getDateForWeekIndex, getToday, removeChoice, removeChoices, updateDepartureTime } from "../service";
import { getDayOfWeekIndex, parseToken } from "../utils";
import { getWebsocket } from "../websocket";
import { callNotifikace } from "../notifikace";
import { UdalostEnum } from "../../../types";
/**
* Ověří a vrátí index dne v týdnu z požadavku, za předpokladu, že byl předán, a je zároveň
@@ -110,4 +112,11 @@ router.post("/changeDepartureTime", async (req, res, next) => {
} catch (e: any) { next(e) }
});
router.post("/jdemeObed", async (req, res, next) => {
const login = getLogin(parseToken(req));
try {
await callNotifikace({ input: { user: login, udalost: UdalostEnum.JDEME_OBED }, gotify: false })
} catch (e: any) { next(e) }
});
export default router;

View File

@@ -1,3 +1,5 @@
import { Choices } from "../../types";
/** Vrátí datum v ISO formátu. */
export function formatDate(date: Date) {
let currentDay = String(date.getDate()).padStart(2, '0');
@@ -106,4 +108,23 @@ export const checkBodyParams = (req: any, paramNames: string[]) => {
// TODO umístit do samostatného souboru
export class InsufficientPermissions extends Error { }
export class InsufficientPermissions extends Error { }
export const getUsersByLocation = (data: Choices, login: string): string[] => {
const result: string[] = [];
for (const location in data) {
if (data.hasOwnProperty(location)) {
if (data[location][login]) {
for (const username in data[location]) {
if (data[location].hasOwnProperty(username)) {
result.push(username);
}
}
break;
}
}
}
return result;
}