feat: podpora notifikací z notify
This commit is contained in:
parent
3460d69899
commit
6d89858e3e
@ -19,7 +19,7 @@ import Footer from './components/Footer';
|
|||||||
import { faChainBroken, faChevronLeft, faChevronRight, faGear, faSatelliteDish, faSearch } from '@fortawesome/free-solid-svg-icons';
|
import { faChainBroken, faChevronLeft, faChevronRight, faGear, faSatelliteDish, faSearch } from '@fortawesome/free-solid-svg-icons';
|
||||||
import Loader from './components/Loader';
|
import Loader from './components/Loader';
|
||||||
import { getData, errorHandler, getQrUrl } from './api/Api';
|
import { getData, errorHandler, getQrUrl } from './api/Api';
|
||||||
import { addChoice, removeChoices, removeChoice, changeDepartureTime } from './api/FoodApi';
|
import { addChoice, removeChoices, removeChoice, changeDepartureTime, jdemeObed } from './api/FoodApi';
|
||||||
|
|
||||||
const EVENT_CONNECT = "connect"
|
const EVENT_CONNECT = "connect"
|
||||||
|
|
||||||
@ -168,6 +168,12 @@ function App() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const doJdemeObed = async () => {
|
||||||
|
if (auth?.login) {
|
||||||
|
await jdemeObed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const doAddFoodChoice = async (event: React.ChangeEvent<HTMLSelectElement>) => {
|
const doAddFoodChoice = async (event: React.ChangeEvent<HTMLSelectElement>) => {
|
||||||
if (event.target.value && foodChoiceList?.length && choiceRef.current?.value) {
|
if (event.target.value && foodChoiceList?.length && choiceRef.current?.value) {
|
||||||
const restaurantKey = choiceRef.current.value;
|
const restaurantKey = choiceRef.current.value;
|
||||||
@ -470,10 +476,13 @@ function App() {
|
|||||||
<FontAwesomeIcon icon={faGear} className='fa-spin' /> Zjišťujeme dostupné pizzy
|
<FontAwesomeIcon icon={faGear} className='fa-spin' /> Zjišťujeme dostupné pizzy
|
||||||
</span>
|
</span>
|
||||||
:
|
:
|
||||||
<Button onClick={async () => {
|
<>
|
||||||
setLoadingPizzaDay(true);
|
<Button onClick={async () => {
|
||||||
await createPizzaDay().then(() => setLoadingPizzaDay(false));
|
setLoadingPizzaDay(true);
|
||||||
}}>Založit Pizza day</Button>
|
await createPizzaDay().then(() => setLoadingPizzaDay(false));
|
||||||
|
}}>Založit Pizza day</Button>
|
||||||
|
<Button onClick={doJdemeObed} style={{ marginLeft: "14px" }}>Jdeme na oběd !</Button>
|
||||||
|
</>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
@ -17,3 +17,7 @@ export const removeChoice = async (locationIndex: number, foodIndex: number, day
|
|||||||
export const changeDepartureTime = async (time: string, dayIndex?: number) => {
|
export const changeDepartureTime = async (time: string, dayIndex?: number) => {
|
||||||
return await api.post<any, any>(`${FOOD_API_PREFIX}/changeDepartureTime`, JSON.stringify({ time, dayIndex }));
|
return await api.post<any, any>(`${FOOD_API_PREFIX}/changeDepartureTime`, JSON.stringify({ time, dayIndex }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const jdemeObed = async () => {
|
||||||
|
return await api.post<any, any>(`${FOOD_API_PREFIX}/jdemeObed`, JSON.stringify({}));
|
||||||
|
}
|
||||||
|
@ -24,3 +24,7 @@
|
|||||||
# To je užitečné pro odesílání upozornění na různé servery Gotify s různými klíči API.
|
# To je užitečné pro odesílání upozornění na různé servery Gotify s různými klíči API.
|
||||||
# Struktura dat je ve formátu JSON a je uložena jako řetězec.
|
# Struktura dat je ve formátu JSON a je uložena jako řetězec.
|
||||||
# GOTIFY_SERVERS_AND_KEYS='[{"server":"https://notification.server.eu", "api_keys":["key1", "key2"]},{"server":"https://notification.server2.eu", "api_keys":["key3", "key4"]}]'
|
# GOTIFY_SERVERS_AND_KEYS='[{"server":"https://notification.server.eu", "api_keys":["key1", "key2"]},{"server":"https://notification.server2.eu", "api_keys":["key3", "key4"]}]'
|
||||||
|
|
||||||
|
#NTFY_HOST = "http://192.168.0.113:80"
|
||||||
|
#NTFY_USERNAME="username"
|
||||||
|
#NTFY_PASSWD="password"
|
||||||
|
@ -1,15 +1,18 @@
|
|||||||
/** Notifikace pro gotify*/
|
/** Notifikace pro gotify*/
|
||||||
import { GotifyServer, NotififaceInput, NotifikaceData } from '../../types';
|
import { ClientData, GotifyServer, NotififaceInput, NotifikaceData } from '../../types';
|
||||||
import axios, { AxiosError } from 'axios';
|
import axios, { AxiosError } from 'axios';
|
||||||
import dotenv from 'dotenv';
|
import dotenv from 'dotenv';
|
||||||
import path from 'path';
|
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'
|
const ENVIRONMENT = process.env.NODE_ENV || 'production'
|
||||||
dotenv.config({ path: path.resolve(__dirname, `../.env.${ENVIRONMENT}`) });
|
dotenv.config({ path: path.resolve(__dirname, `../.env.${ENVIRONMENT}`) });
|
||||||
|
|
||||||
const gotifyDataRaw = process.env.GOTIFY_SERVERS_AND_KEYS || "{}";
|
const gotifyDataRaw = process.env.GOTIFY_SERVERS_AND_KEYS || "{}";
|
||||||
const gotifyData: GotifyServer[] = JSON.parse(gotifyDataRaw);
|
const gotifyData: GotifyServer[] = JSON.parse(gotifyDataRaw);
|
||||||
|
|
||||||
export const gotifyCall = async (data: NotififaceInput, gotifyServers?: GotifyServer[]): Promise<any[]> => {
|
export const gotifyCall = async (data: NotififaceInput, gotifyServers?: GotifyServer[]): Promise<any[]> => {
|
||||||
if (!Array.isArray(gotifyServers)) {
|
if (!Array.isArray(gotifyServers)) {
|
||||||
return []
|
return []
|
||||||
@ -51,15 +54,56 @@ export const gotifyCall = async (data: NotififaceInput, gotifyServers?: GotifySe
|
|||||||
return promises;
|
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 ntfyCall = async (data: NotififaceInput) => {
|
||||||
export const callNotifikace = async ({ input, teams = true, gotify = true }: NotifikaceData) => {
|
const url = process.env.NTFY_HOST
|
||||||
const notifications = [];
|
const username = process.env.NTFY_USERNAME;
|
||||||
|
const password = process.env.NTFY_PASSWD;
|
||||||
if (gotify) {
|
if (!url) {
|
||||||
const gotifyPromises = await gotifyCall(input, gotifyData);
|
console.log("NTFY_HOST není definován v env")
|
||||||
notifications.push(...gotifyPromises);
|
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í
|
/* Zatím není
|
||||||
if (teams) {
|
if (teams) {
|
||||||
notifications.push(teamsCall(input));
|
notifications.push(teamsCall(input));
|
||||||
@ -67,6 +111,12 @@ export const callNotifikace = async ({ input, teams = true, gotify = true }: Not
|
|||||||
|
|
||||||
// Add more notifications as necessary
|
// Add more notifications as necessary
|
||||||
|
|
||||||
|
//gotify bych řekl, že už je deprecated
|
||||||
|
if (gotify) {
|
||||||
|
const gotifyPromises = await gotifyCall(input, gotifyData);
|
||||||
|
notifications.push(...gotifyPromises);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const results = await Promise.all(notifications);
|
const results = await Promise.all(notifications);
|
||||||
return results;
|
return results;
|
||||||
|
@ -1,8 +1,10 @@
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import { getLogin, getTrusted } from "../auth";
|
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 { getDayOfWeekIndex, parseToken } from "../utils";
|
||||||
import { getWebsocket } from "../websocket";
|
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ň
|
* 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) }
|
} 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;
|
export default router;
|
@ -1,3 +1,5 @@
|
|||||||
|
import { Choices } from "../../types";
|
||||||
|
|
||||||
/** Vrátí datum v ISO formátu. */
|
/** Vrátí datum v ISO formátu. */
|
||||||
export function formatDate(date: Date) {
|
export function formatDate(date: Date) {
|
||||||
let currentDay = String(date.getDate()).padStart(2, '0');
|
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
|
// 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;
|
||||||
|
}
|
@ -121,7 +121,8 @@ export enum Locations {
|
|||||||
|
|
||||||
export enum UdalostEnum {
|
export enum UdalostEnum {
|
||||||
ZAHAJENA_PIZZA = "Zahájen pizza day",
|
ZAHAJENA_PIZZA = "Zahájen pizza day",
|
||||||
OBJEDNANA_PIZZA = "Objednána pizza"
|
OBJEDNANA_PIZZA = "Objednána pizza",
|
||||||
|
JDEME_OBED = "Jdeme oběd",
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface NotififaceInput {
|
export interface NotififaceInput {
|
||||||
@ -133,6 +134,7 @@ export interface NotifikaceData {
|
|||||||
input: NotififaceInput,
|
input: NotififaceInput,
|
||||||
gotify?: boolean,
|
gotify?: boolean,
|
||||||
teams?: boolean,
|
teams?: boolean,
|
||||||
|
ntfy?: boolean,
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GotifyServer {
|
export interface GotifyServer {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user