mirror of
https://github.com/Ravinou/borgwarehouse
synced 2024-05-17 21:16:39 +02:00
feat: notify multiple Apprise services URLs
This commit is contained in:
parent
95451e8bb4
commit
c87a01728d
|
@ -0,0 +1,152 @@
|
|||
//Lib
|
||||
import { useEffect } from 'react';
|
||||
import classes from '../../UserSettings.module.css';
|
||||
import { useState } from 'react';
|
||||
import { SpinnerCircularFixed } from 'spinners-react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
|
||||
//Components
|
||||
import Error from '../../../../Components/UI/Error/Error';
|
||||
|
||||
export default function AppriseURLs() {
|
||||
//Var
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm({ mode: 'onBlur' });
|
||||
|
||||
////State
|
||||
const [formIsLoading, setFormIsLoading] = useState(false);
|
||||
const [urlsFormIsSaved, setUrlsFormIsSaved] = useState(false);
|
||||
const [appriseServicesList, setAppriseServicesList] = useState();
|
||||
const [error, setError] = useState();
|
||||
|
||||
////LifeCycle
|
||||
//Component did mount
|
||||
useEffect(() => {
|
||||
//Initial fetch to build the list of Apprise Services enabled
|
||||
const getAppriseServices = async () => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
'/api/account/getAppriseServices',
|
||||
{
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-type': 'application/json',
|
||||
},
|
||||
}
|
||||
);
|
||||
let servicesArray = (await response.json()).appriseServices;
|
||||
const AppriseServicesListToText = () => {
|
||||
let list = '';
|
||||
for (let service of servicesArray) {
|
||||
list += service + '\n';
|
||||
}
|
||||
return list;
|
||||
};
|
||||
setAppriseServicesList(AppriseServicesListToText());
|
||||
} catch (error) {
|
||||
console.log('Fetching Apprise services list failed.');
|
||||
}
|
||||
};
|
||||
getAppriseServices();
|
||||
}, []);
|
||||
|
||||
////Functions
|
||||
//Form submit handler to modify Apprise services
|
||||
const urlsFormSubmitHandler = async (data) => {
|
||||
//Remove old error
|
||||
setError();
|
||||
//Loading button on submit to avoid multiple send.
|
||||
setFormIsLoading(true);
|
||||
//POST API to update Apprise Services
|
||||
const response = await fetch('/api/account/updateAppriseServices', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
const result = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
setFormIsLoading(false);
|
||||
setError(result.message);
|
||||
setTimeout(() => setError(), 4000);
|
||||
} else {
|
||||
setFormIsLoading(false);
|
||||
setUrlsFormIsSaved(true);
|
||||
setTimeout(() => setUrlsFormIsSaved(false), 3000);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* APPRISE SERVICES URLS */}
|
||||
<div className={classes.headerFormAppriseUrls}>
|
||||
<div style={{ marginRight: '10px' }}>Apprise URLs</div>
|
||||
{error && <Error message={error} />}
|
||||
<div style={{ display: 'flex' }}>
|
||||
{formIsLoading && (
|
||||
<SpinnerCircularFixed
|
||||
size={18}
|
||||
thickness={150}
|
||||
speed={150}
|
||||
color='#704dff'
|
||||
secondaryColor='#c3b6fa'
|
||||
/>
|
||||
)}
|
||||
{urlsFormIsSaved && (
|
||||
<div className={classes.formIsSavedMessage}>
|
||||
✅ Apprise configuration has been saved.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<form
|
||||
onBlur={handleSubmit(urlsFormSubmitHandler)}
|
||||
className={classes.bwForm + ' ' + classes.currentSetting}
|
||||
>
|
||||
<textarea
|
||||
style={{ height: '100px' }}
|
||||
type='text'
|
||||
placeholder={
|
||||
'matrixs://{user}:{password}@{matrixhost}\ndiscord://{WebhookID}/{WebhookToken}\nmmosts://user@hostname/authkey'
|
||||
}
|
||||
defaultValue={appriseServicesList}
|
||||
{...register('appriseURLs', {
|
||||
pattern: {
|
||||
value: /^.+:\/\/.+$/gm,
|
||||
message: 'Invalid URLs format.',
|
||||
},
|
||||
})}
|
||||
/>
|
||||
{errors.appriseURLs && (
|
||||
<small className={classes.errorMessage}>
|
||||
{errors.appriseURLs.message}
|
||||
</small>
|
||||
)}
|
||||
</form>
|
||||
<div
|
||||
style={{
|
||||
color: '#6c737f',
|
||||
fontSize: '0.875rem',
|
||||
marginBottom: '20px',
|
||||
}}
|
||||
>
|
||||
Use{' '}
|
||||
<a
|
||||
style={{
|
||||
color: '#6d4aff',
|
||||
textDecoration: 'none',
|
||||
}}
|
||||
href='https://github.com/caronc/apprise#supported-notifications'
|
||||
>
|
||||
Apprise URLs
|
||||
</a>{' '}
|
||||
to send a notification to any service. Only one URL per line.
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
|
@ -0,0 +1,85 @@
|
|||
//Lib
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import { authOptions } from '../auth/[...nextauth]';
|
||||
import { unstable_getServerSession } from 'next-auth/next';
|
||||
|
||||
export default async function handler(req, res) {
|
||||
if (req.method == 'PUT') {
|
||||
//Verify that the user is logged in.
|
||||
const session = await unstable_getServerSession(req, res, authOptions);
|
||||
if (!session) {
|
||||
res.status(401).json({ message: 'You must be logged in.' });
|
||||
return;
|
||||
}
|
||||
|
||||
//The data we expect to receive
|
||||
let { appriseURLs } = req.body;
|
||||
|
||||
//Read the users file
|
||||
//Find the absolute path of the json directory
|
||||
const jsonDirectory = path.join(process.cwd(), '/config');
|
||||
let usersList = await fs.readFile(
|
||||
jsonDirectory + '/users.json',
|
||||
'utf8'
|
||||
);
|
||||
//Parse the usersList
|
||||
usersList = JSON.parse(usersList);
|
||||
|
||||
//1 : Verify that the user of the session exists
|
||||
const userIndex = usersList
|
||||
.map((user) => user.username)
|
||||
.indexOf(session.user.name);
|
||||
if (userIndex === -1) {
|
||||
res.status(400).json({
|
||||
message:
|
||||
'User is incorrect. Please, logout to update your session.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
//2 : Update Apprise URLs list
|
||||
try {
|
||||
//Build the services URLs list from form
|
||||
const appriseURLsArray = appriseURLs
|
||||
.replace(/ /g, '')
|
||||
.split('\n')
|
||||
.filter((el) => el != '');
|
||||
|
||||
//Save the list for the user
|
||||
let newUsersList = usersList.map((user) =>
|
||||
user.username == session.user.name
|
||||
? {
|
||||
...user,
|
||||
appriseServices: appriseURLsArray,
|
||||
}
|
||||
: user
|
||||
);
|
||||
//Stringify the new users list
|
||||
newUsersList = JSON.stringify(newUsersList);
|
||||
//Write the new JSON
|
||||
fs.writeFile(jsonDirectory + '/users.json', newUsersList, (err) => {
|
||||
if (err) console.log(err);
|
||||
});
|
||||
res.status(200).json({ message: 'Successful API send' });
|
||||
} catch (error) {
|
||||
//Log for backend
|
||||
console.log(error);
|
||||
//Log for frontend
|
||||
if (error.code == 'ENOENT') {
|
||||
res.status(500).json({
|
||||
status: 500,
|
||||
message: 'No such file or directory',
|
||||
});
|
||||
} else {
|
||||
res.status(500).json({
|
||||
status: 500,
|
||||
message: 'API error, contact the administrator',
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
res.status(405).json({ message: 'Bad request on API' });
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue