feat(notif): allow users to enable/disable specific agents (#1172)
* refactor(ui): add tabs to user notification settings * feat(notif): allow users to enable/disable specific agents * fix(ui): only enforce required fields when agent is enabled * fix(ui): hide unavailable notification agents * feat(notif): mention admin users for admin Discord notifications * fix(ui): modify styling of PGP key textareas to suit expected input * fix(notif): mention all admins when there are multiple and fix rebase error * fix: add missing form values, and fix Yup validation * refactor: reduce repeated logic/code in email notif agent * refactor: move 'Notification Types' label into NotificationTypeSelector component * fix(email): correct inconsistencies in email template formatting * refactor: use bitfields for storing user-enabled notif agent types * feat: improve notification agent logging * fix(ui): mark string fields as nullable so empty values are not type errors * fix: add validation for PGP-related inputs * fix: correctly fetch user in user settings & log mentioned IDs for Discord notifs * fix(ui): fix mobile nav dropdown text & add hover effect to button-style tabs * fix(notif): process admin email notifications asynchronously * fix(logging): log name of notification type instead of its enum value * fix: mark required fields and pass all user settings values to API * fix(frontend): call mutate after changing email/Discord/Telegram global notif settings * refactor: get global notif settings from relevant API endpoints instead of adding to public settings * fix(notif): fall back to email notifications being enabled (default) if user settings do not exist * fix(notif): do not set notifyUser for MEDIA_PENDING or MEDIA_AUTO_APPROVED * fix: expose notif enabled settings in user notif endpoints & remove global enable notif setting * fix(notif): remove unnecessary allowed_mentions object from Discord payload * fix(notif): use form values for email test notification * fix: make suggested changes and regenerate DB migration * fix: loosen validation of PGP keys * fix: fix user profile settings routes * fix: remove route guard from profile pagespull/1413/head
parent
bed850dce9
commit
46c4ee1625
@ -0,0 +1,16 @@
|
||||
export enum NotificationAgentType {
|
||||
NONE = 0,
|
||||
EMAIL = 2,
|
||||
DISCORD = 4,
|
||||
TELEGRAM = 8,
|
||||
PUSHOVER = 16,
|
||||
PUSHBULLET = 32,
|
||||
SLACK = 64,
|
||||
}
|
||||
|
||||
export const hasNotificationAgentEnabled = (
|
||||
agent: NotificationAgentType,
|
||||
value: number
|
||||
): boolean => {
|
||||
return !!(value & agent);
|
||||
};
|
@ -0,0 +1,52 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
export class AddUserSettingsNotificationAgentsField1617730837489
|
||||
implements MigrationInterface {
|
||||
name = 'AddUserSettingsNotificationAgentsField1617730837489';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "temporary_user_settings" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "notificationAgents" NOT NULL DEFAULT (2), "discordId" varchar, "userId" integer, "region" varchar, "originalLanguage" varchar, "telegramChatId" varchar, "telegramSendSilently" boolean, "pgpKey" varchar, CONSTRAINT "UQ_986a2b6d3c05eb4091bb8066f78" UNIQUE ("userId"), CONSTRAINT "FK_986a2b6d3c05eb4091bb8066f78" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "temporary_user_settings"("id", "discordId", "userId", "region", "originalLanguage", "telegramChatId", "telegramSendSilently", "pgpKey") SELECT "id", "discordId", "userId", "region", "originalLanguage", "telegramChatId", "telegramSendSilently", "pgpKey" FROM "user_settings"`
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "user_settings"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "temporary_user_settings" RENAME TO "user_settings"`
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "temporary_user_settings" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "notificationAgents" integer NOT NULL DEFAULT (2), "discordId" varchar, "userId" integer, "region" varchar, "originalLanguage" varchar, "telegramChatId" varchar, "telegramSendSilently" boolean, "pgpKey" varchar, CONSTRAINT "UQ_986a2b6d3c05eb4091bb8066f78" UNIQUE ("userId"), CONSTRAINT "FK_986a2b6d3c05eb4091bb8066f78" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "temporary_user_settings"("id", "notificationAgents", "discordId", "userId", "region", "originalLanguage", "telegramChatId", "telegramSendSilently", "pgpKey") SELECT "id", "notificationAgents", "discordId", "userId", "region", "originalLanguage", "telegramChatId", "telegramSendSilently", "pgpKey" FROM "user_settings"`
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "user_settings"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "temporary_user_settings" RENAME TO "user_settings"`
|
||||
);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "user_settings" RENAME TO "temporary_user_settings"`
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "user_settings" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "notificationAgents" NOT NULL DEFAULT (2), "discordId" varchar, "userId" integer, "region" varchar, "originalLanguage" varchar, "telegramChatId" varchar, "telegramSendSilently" boolean, "pgpKey" varchar, CONSTRAINT "UQ_986a2b6d3c05eb4091bb8066f78" UNIQUE ("userId"), CONSTRAINT "FK_986a2b6d3c05eb4091bb8066f78" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "user_settings"("id", "notificationAgents", "discordId", "userId", "region", "originalLanguage", "telegramChatId", "telegramSendSilently", "pgpKey") SELECT "id", "notificationAgents", "discordId", "userId", "region", "originalLanguage", "telegramChatId", "telegramSendSilently", "pgpKey" FROM "temporary_user_settings"`
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "temporary_user_settings"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "user_settings" RENAME TO "temporary_user_settings"`
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE "user_settings" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "enableNotifications" boolean NOT NULL DEFAULT (1), "discordId" varchar, "userId" integer, "region" varchar, "originalLanguage" varchar, "telegramChatId" varchar, "telegramSendSilently" boolean, "pgpKey" varchar, CONSTRAINT "UQ_986a2b6d3c05eb4091bb8066f78" UNIQUE ("userId"), CONSTRAINT "FK_986a2b6d3c05eb4091bb8066f78" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`
|
||||
);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "user_settings"("id", "discordId", "userId", "region", "originalLanguage", "telegramChatId", "telegramSendSilently", "pgpKey") SELECT "id", "discordId", "userId", "region", "originalLanguage", "telegramChatId", "telegramSendSilently", "pgpKey" FROM "temporary_user_settings"`
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "temporary_user_settings"`);
|
||||
}
|
||||
}
|
@ -0,0 +1,173 @@
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/router';
|
||||
import React from 'react';
|
||||
import { hasPermission, Permission } from '../../../../server/lib/permissions';
|
||||
import { useUser } from '../../../hooks/useUser';
|
||||
|
||||
export interface SettingsRoute {
|
||||
text: string;
|
||||
content?: React.ReactNode;
|
||||
route: string;
|
||||
regex: RegExp;
|
||||
requiredPermission?: Permission | Permission[];
|
||||
permissionType?: { type: 'and' | 'or' };
|
||||
hidden?: boolean;
|
||||
}
|
||||
|
||||
const SettingsLink: React.FC<{
|
||||
tabType: 'default' | 'button';
|
||||
currentPath: string;
|
||||
route: string;
|
||||
regex: RegExp;
|
||||
hidden?: boolean;
|
||||
isMobile?: boolean;
|
||||
}> = ({
|
||||
children,
|
||||
tabType,
|
||||
currentPath,
|
||||
route,
|
||||
regex,
|
||||
hidden = false,
|
||||
isMobile = false,
|
||||
}) => {
|
||||
if (hidden) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return <option value={route}>{children}</option>;
|
||||
}
|
||||
|
||||
let linkClasses =
|
||||
'px-1 py-4 ml-8 text-sm font-medium leading-5 transition duration-300 border-b-2 border-transparent whitespace-nowrap first:ml-0';
|
||||
let activeLinkColor = 'text-indigo-500 border-indigo-600';
|
||||
let inactiveLinkColor =
|
||||
'text-gray-500 border-transparent hover:text-gray-300 hover:border-gray-400 focus:text-gray-300 focus:border-gray-400';
|
||||
|
||||
if (tabType === 'button') {
|
||||
linkClasses =
|
||||
'px-3 py-2 ml-8 text-sm font-medium transition duration-300 rounded-md whitespace-nowrap first:ml-0';
|
||||
activeLinkColor = 'bg-indigo-700';
|
||||
inactiveLinkColor = 'bg-gray-800 hover:bg-gray-700 focus:bg-gray-700';
|
||||
}
|
||||
|
||||
return (
|
||||
<Link href={route}>
|
||||
<a
|
||||
className={`${linkClasses} ${
|
||||
currentPath.match(regex) ? activeLinkColor : inactiveLinkColor
|
||||
}`}
|
||||
aria-current="page"
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
</Link>
|
||||
);
|
||||
};
|
||||
|
||||
const SettingsTabs: React.FC<{
|
||||
tabType?: 'default' | 'button';
|
||||
settingsRoutes: SettingsRoute[];
|
||||
}> = ({ tabType = 'default', settingsRoutes }) => {
|
||||
const router = useRouter();
|
||||
const { user: currentUser } = useUser();
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="sm:hidden">
|
||||
<label htmlFor="tabs" className="sr-only">
|
||||
Select a Tab
|
||||
</label>
|
||||
<select
|
||||
onChange={(e) => {
|
||||
router.push(e.target.value);
|
||||
}}
|
||||
onBlur={(e) => {
|
||||
router.push(e.target.value);
|
||||
}}
|
||||
defaultValue={
|
||||
settingsRoutes.find((route) => !!router.pathname.match(route.regex))
|
||||
?.route
|
||||
}
|
||||
aria-label="Selected Tab"
|
||||
>
|
||||
{settingsRoutes
|
||||
.filter(
|
||||
(route) =>
|
||||
!route.hidden &&
|
||||
(route.requiredPermission
|
||||
? hasPermission(
|
||||
route.requiredPermission,
|
||||
currentUser?.permissions ?? 0,
|
||||
route.permissionType
|
||||
)
|
||||
: true)
|
||||
)
|
||||
.map((route, index) => (
|
||||
<SettingsLink
|
||||
tabType={tabType}
|
||||
currentPath={router.pathname}
|
||||
route={route.route}
|
||||
regex={route.regex}
|
||||
hidden={route.hidden ?? false}
|
||||
isMobile
|
||||
key={`mobile-settings-link-${index}`}
|
||||
>
|
||||
{route.text}
|
||||
</SettingsLink>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
{tabType === 'button' ? (
|
||||
<div className="hidden overflow-x-scroll overflow-y-hidden sm:block hide-scrollbar">
|
||||
<nav className="flex space-x-4" aria-label="Tabs">
|
||||
{settingsRoutes.map((route, index) => (
|
||||
<SettingsLink
|
||||
tabType={tabType}
|
||||
currentPath={router.pathname}
|
||||
route={route.route}
|
||||
regex={route.regex}
|
||||
hidden={route.hidden ?? false}
|
||||
key={`button-settings-link-${index}`}
|
||||
>
|
||||
{route.content ?? route.text}
|
||||
</SettingsLink>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
) : (
|
||||
<div className="hidden sm:block">
|
||||
<div className="border-b border-gray-600">
|
||||
<nav className="flex -mb-px">
|
||||
{settingsRoutes
|
||||
.filter(
|
||||
(route) =>
|
||||
!route.hidden &&
|
||||
(route.requiredPermission
|
||||
? hasPermission(
|
||||
route.requiredPermission,
|
||||
currentUser?.permissions ?? 0,
|
||||
route.permissionType
|
||||
)
|
||||
: true)
|
||||
)
|
||||
.map((route, index) => (
|
||||
<SettingsLink
|
||||
tabType={tabType}
|
||||
currentPath={router.pathname}
|
||||
route={route.route}
|
||||
regex={route.regex}
|
||||
key={`standard-settings-link-${index}`}
|
||||
>
|
||||
{route.text}
|
||||
</SettingsLink>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default SettingsTabs;
|
@ -0,0 +1,178 @@
|
||||
import axios from 'axios';
|
||||
import { Field, Form, Formik } from 'formik';
|
||||
import { useRouter } from 'next/router';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { defineMessages, useIntl } from 'react-intl';
|
||||
import { useToasts } from 'react-toast-notifications';
|
||||
import useSWR from 'swr';
|
||||
import * as Yup from 'yup';
|
||||
import { UserSettingsNotificationsResponse } from '../../../../../server/interfaces/api/userSettingsInterfaces';
|
||||
import {
|
||||
hasNotificationAgentEnabled,
|
||||
NotificationAgentType,
|
||||
} from '../../../../../server/lib/notifications/agenttypes';
|
||||
import { useUser } from '../../../../hooks/useUser';
|
||||
import globalMessages from '../../../../i18n/globalMessages';
|
||||
import Button from '../../../Common/Button';
|
||||
import LoadingSpinner from '../../../Common/LoadingSpinner';
|
||||
|
||||
const messages = defineMessages({
|
||||
discordsettingssaved: 'Discord notification settings saved successfully!',
|
||||
discordsettingsfailed: 'Discord notification settings failed to save.',
|
||||
enableDiscord: 'Enable Mentions',
|
||||
discordId: 'User ID',
|
||||
discordIdTip:
|
||||
'The <FindDiscordIdLink>ID number</FindDiscordIdLink> for your user account',
|
||||
validationDiscordId: 'You must provide a valid user ID',
|
||||
});
|
||||
|
||||
const UserNotificationsDiscord: React.FC = () => {
|
||||
const intl = useIntl();
|
||||
const { addToast } = useToasts();
|
||||
const router = useRouter();
|
||||
const [notificationAgents, setNotificationAgents] = useState(0);
|
||||
const { user } = useUser({ id: Number(router.query.userId) });
|
||||
const { data, error, revalidate } = useSWR<UserSettingsNotificationsResponse>(
|
||||
user ? `/api/v1/user/${user?.id}/settings/notifications` : null
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setNotificationAgents(
|
||||
data?.notificationAgents ?? NotificationAgentType.EMAIL
|
||||
);
|
||||
}, [data]);
|
||||
|
||||
const UserNotificationsDiscordSchema = Yup.object().shape({
|
||||
discordId: Yup.string()
|
||||
.when('enableDiscord', {
|
||||
is: true,
|
||||
then: Yup.string()
|
||||
.nullable()
|
||||
.required(intl.formatMessage(messages.validationDiscordId)),
|
||||
otherwise: Yup.string().nullable(),
|
||||
})
|
||||
.matches(/^\d{17,18}$/, intl.formatMessage(messages.validationDiscordId)),
|
||||
});
|
||||
|
||||
if (!data && !error) {
|
||||
return <LoadingSpinner />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Formik
|
||||
initialValues={{
|
||||
enableDiscord: hasNotificationAgentEnabled(
|
||||
NotificationAgentType.DISCORD,
|
||||
data?.notificationAgents ?? NotificationAgentType.EMAIL
|
||||
),
|
||||
discordId: data?.discordId,
|
||||
}}
|
||||
validationSchema={UserNotificationsDiscordSchema}
|
||||
enableReinitialize
|
||||
onSubmit={async (values) => {
|
||||
try {
|
||||
await axios.post(`/api/v1/user/${user?.id}/settings/notifications`, {
|
||||
notificationAgents,
|
||||
pgpKey: data?.pgpKey,
|
||||
discordId: values.discordId,
|
||||
telegramChatId: data?.telegramChatId,
|
||||
telegramSendSilently: data?.telegramSendSilently,
|
||||
});
|
||||
addToast(intl.formatMessage(messages.discordsettingssaved), {
|
||||
appearance: 'success',
|
||||
autoDismiss: true,
|
||||
});
|
||||
} catch (e) {
|
||||
addToast(intl.formatMessage(messages.discordsettingsfailed), {
|
||||
appearance: 'error',
|
||||
autoDismiss: true,
|
||||
});
|
||||
} finally {
|
||||
revalidate();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{({ errors, touched, isSubmitting, isValid, values, setFieldValue }) => {
|
||||
return (
|
||||
<Form className="section">
|
||||
{data?.discordEnabled && (
|
||||
<div className="form-row">
|
||||
<label htmlFor="enableDiscord" className="checkbox-label">
|
||||
{intl.formatMessage(messages.enableDiscord)}
|
||||
</label>
|
||||
<div className="form-input">
|
||||
<Field
|
||||
type="checkbox"
|
||||
id="enableDiscord"
|
||||
name="enableDiscord"
|
||||
checked={hasNotificationAgentEnabled(
|
||||
NotificationAgentType.DISCORD,
|
||||
notificationAgents
|
||||
)}
|
||||
onChange={() => {
|
||||
setNotificationAgents(
|
||||
hasNotificationAgentEnabled(
|
||||
NotificationAgentType.DISCORD,
|
||||
notificationAgents
|
||||
)
|
||||
? notificationAgents - NotificationAgentType.DISCORD
|
||||
: notificationAgents + NotificationAgentType.DISCORD
|
||||
);
|
||||
setFieldValue('enableDiscord', !values.enableDiscord);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="form-row">
|
||||
<label htmlFor="discordId" className="text-label">
|
||||
<span>{intl.formatMessage(messages.discordId)}</span>
|
||||
<span className="label-required">*</span>
|
||||
<span className="label-tip">
|
||||
{intl.formatMessage(messages.discordIdTip, {
|
||||
FindDiscordIdLink: function FindDiscordIdLink(msg) {
|
||||
return (
|
||||
<a
|
||||
href="https://support.discord.com/hc/en-us/articles/206346498-Where-can-I-find-my-User-Server-Message-ID-"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
{msg}
|
||||
</a>
|
||||
);
|
||||
},
|
||||
})}
|
||||
</span>
|
||||
</label>
|
||||
<div className="form-input">
|
||||
<div className="form-input-field">
|
||||
<Field id="discordId" name="discordId" type="text" />
|
||||
</div>
|
||||
{errors.discordId && touched.discordId && (
|
||||
<div className="error">{errors.discordId}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="actions">
|
||||
<div className="flex justify-end">
|
||||
<span className="inline-flex ml-3 rounded-md shadow-sm">
|
||||
<Button
|
||||
buttonType="primary"
|
||||
type="submit"
|
||||
disabled={isSubmitting || !isValid}
|
||||
>
|
||||
{isSubmitting
|
||||
? intl.formatMessage(globalMessages.saving)
|
||||
: intl.formatMessage(globalMessages.save)}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
);
|
||||
}}
|
||||
</Formik>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserNotificationsDiscord;
|
@ -0,0 +1,175 @@
|
||||
import axios from 'axios';
|
||||
import { Field, Form, Formik } from 'formik';
|
||||
import { useRouter } from 'next/router';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { defineMessages, useIntl } from 'react-intl';
|
||||
import { useToasts } from 'react-toast-notifications';
|
||||
import useSWR from 'swr';
|
||||
import * as Yup from 'yup';
|
||||
import { UserSettingsNotificationsResponse } from '../../../../../server/interfaces/api/userSettingsInterfaces';
|
||||
import {
|
||||
hasNotificationAgentEnabled,
|
||||
NotificationAgentType,
|
||||
} from '../../../../../server/lib/notifications/agenttypes';
|
||||
import { useUser } from '../../../../hooks/useUser';
|
||||
import globalMessages from '../../../../i18n/globalMessages';
|
||||
import Badge from '../../../Common/Badge';
|
||||
import Button from '../../../Common/Button';
|
||||
import LoadingSpinner from '../../../Common/LoadingSpinner';
|
||||
import { OpenPgpLink } from '../../../Settings/Notifications/NotificationsEmail';
|
||||
|
||||
const messages = defineMessages({
|
||||
emailsettingssaved: 'Email notification settings saved successfully!',
|
||||
emailsettingsfailed: 'Email notification settings failed to save.',
|
||||
enableEmail: 'Enable Notifications',
|
||||
pgpPublicKey: 'PGP Public Key',
|
||||
pgpPublicKeyTip:
|
||||
'Encrypt email messages using <OpenPgpLink>OpenPGP</OpenPgpLink>',
|
||||
validationPgpPublicKey: 'You must provide a valid PGP public key',
|
||||
});
|
||||
|
||||
const UserEmailSettings: React.FC = () => {
|
||||
const intl = useIntl();
|
||||
const { addToast } = useToasts();
|
||||
const router = useRouter();
|
||||
const [notificationAgents, setNotificationAgents] = useState(0);
|
||||
const { user } = useUser({ id: Number(router.query.userId) });
|
||||
const { data, error, revalidate } = useSWR<UserSettingsNotificationsResponse>(
|
||||
user ? `/api/v1/user/${user?.id}/settings/notifications` : null
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setNotificationAgents(
|
||||
data?.notificationAgents ?? NotificationAgentType.EMAIL
|
||||
);
|
||||
}, [data]);
|
||||
|
||||
const UserNotificationsEmailSchema = Yup.object().shape({
|
||||
pgpKey: Yup.string()
|
||||
.nullable()
|
||||
.matches(
|
||||
/^-----BEGIN PGP PUBLIC KEY BLOCK-----.+-----END PGP PUBLIC KEY BLOCK-----$/,
|
||||
intl.formatMessage(messages.validationPgpPublicKey)
|
||||
),
|
||||
});
|
||||
|
||||
if (!data && !error) {
|
||||
return <LoadingSpinner />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Formik
|
||||
initialValues={{
|
||||
enableEmail: hasNotificationAgentEnabled(
|
||||
NotificationAgentType.EMAIL,
|
||||
data?.notificationAgents ?? NotificationAgentType.EMAIL
|
||||
),
|
||||
pgpKey: data?.pgpKey,
|
||||
}}
|
||||
validationSchema={UserNotificationsEmailSchema}
|
||||
enableReinitialize
|
||||
onSubmit={async (values) => {
|
||||
try {
|
||||
await axios.post(`/api/v1/user/${user?.id}/settings/notifications`, {
|
||||
notificationAgents,
|
||||
pgpKey: values.pgpKey,
|
||||
discordId: data?.discordId,
|
||||
telegramChatId: data?.telegramChatId,
|
||||
telegramSendSilently: data?.telegramSendSilently,
|
||||
});
|
||||
addToast(intl.formatMessage(messages.emailsettingssaved), {
|
||||
appearance: 'success',
|
||||
autoDismiss: true,
|
||||
});
|
||||
} catch (e) {
|
||||
addToast(intl.formatMessage(messages.emailsettingsfailed), {
|
||||
appearance: 'error',
|
||||
autoDismiss: true,
|
||||
});
|
||||
} finally {
|
||||
revalidate();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{({ errors, touched, isSubmitting, isValid, values, setFieldValue }) => {
|
||||
return (
|
||||
<Form className="section">
|
||||
<div className="form-row">
|
||||
<label htmlFor="enableEmail" className="checkbox-label">
|
||||
{intl.formatMessage(messages.enableEmail)}
|
||||
</label>
|
||||
<div className="form-input">
|
||||
<Field
|
||||
type="checkbox"
|
||||
id="enableEmail"
|
||||
name="enableEmail"
|
||||
checked={hasNotificationAgentEnabled(
|
||||
NotificationAgentType.EMAIL,
|
||||
notificationAgents
|
||||
)}
|
||||
onChange={() => {
|
||||
setNotificationAgents(
|
||||
hasNotificationAgentEnabled(
|
||||
NotificationAgentType.EMAIL,
|
||||
notificationAgents
|
||||
)
|
||||
? notificationAgents - NotificationAgentType.EMAIL
|
||||
: notificationAgents + NotificationAgentType.EMAIL
|
||||
);
|
||||
setFieldValue('enableEmail', !values.enableEmail);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label htmlFor="pgpKey" className="text-label">
|
||||
<span className="mr-2">
|
||||
{intl.formatMessage(messages.pgpPublicKey)}
|
||||
</span>
|
||||
<Badge badgeType="danger">
|
||||
{intl.formatMessage(globalMessages.advanced)}
|
||||
</Badge>
|
||||
<span className="label-tip">
|
||||
{intl.formatMessage(messages.pgpPublicKeyTip, {
|
||||
OpenPgpLink: OpenPgpLink,
|
||||
})}
|
||||
</span>
|
||||
</label>
|
||||
<div className="form-input">
|
||||
<div className="form-input-field">
|
||||
<Field
|
||||
as="textarea"
|
||||
id="pgpKey"
|
||||
name="pgpKey"
|
||||
rows="10"
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
{errors.pgpKey && touched.pgpKey && (
|
||||
<div className="error">{errors.pgpKey}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="actions">
|
||||
<div className="flex justify-end">
|
||||
<span className="inline-flex ml-3 rounded-md shadow-sm">
|
||||
<Button
|
||||
buttonType="primary"
|
||||
type="submit"
|
||||
disabled={isSubmitting || !isValid}
|
||||
>
|
||||
{isSubmitting
|
||||
? intl.formatMessage(globalMessages.saving)
|
||||
: intl.formatMessage(globalMessages.save)}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
);
|
||||
}}
|
||||
</Formik>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserEmailSettings;
|
@ -0,0 +1,217 @@
|
||||
import axios from 'axios';
|
||||
import { Field, Form, Formik } from 'formik';
|
||||
import { useRouter } from 'next/router';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { defineMessages, useIntl } from 'react-intl';
|
||||
import { useToasts } from 'react-toast-notifications';
|
||||
import useSWR from 'swr';
|
||||
import * as Yup from 'yup';
|
||||
import { UserSettingsNotificationsResponse } from '../../../../../server/interfaces/api/userSettingsInterfaces';
|
||||
import {
|
||||
hasNotificationAgentEnabled,
|
||||
NotificationAgentType,
|
||||
} from '../../../../../server/lib/notifications/agenttypes';
|
||||
import { useUser } from '../../../../hooks/useUser';
|
||||
import globalMessages from '../../../../i18n/globalMessages';
|
||||
import Button from '../../../Common/Button';
|
||||
import LoadingSpinner from '../../../Common/LoadingSpinner';
|
||||
|
||||
const messages = defineMessages({
|
||||
telegramsettingssaved: 'Telegram notification settings saved successfully!',
|
||||
telegramsettingsfailed: 'Telegram notification settings failed to save.',
|
||||
enableTelegram: 'Enable Notifications',
|
||||
telegramChatId: 'Chat ID',
|
||||
telegramChatIdTipLong:
|
||||
'<TelegramBotLink>Start a chat</TelegramBotLink>, add <GetIdBotLink>@get_id_bot</GetIdBotLink>, and issue the <code>/my_id</code> command',
|
||||
sendSilently: 'Send Silently',
|
||||
sendSilentlyDescription: 'Send notifications with no sound',
|
||||
validationTelegramChatId: 'You must provide a valid chat ID',
|
||||
});
|
||||
|
||||
const UserTelegramSettings: React.FC = () => {
|
||||
const intl = useIntl();
|
||||
const { addToast } = useToasts();
|
||||
const router = useRouter();
|
||||
const [notificationAgents, setNotificationAgents] = useState(0);
|
||||
const { user } = useUser({ id: Number(router.query.userId) });
|
||||
const { data, error, revalidate } = useSWR<UserSettingsNotificationsResponse>(
|
||||
user ? `/api/v1/user/${user?.id}/settings/notifications` : null
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setNotificationAgents(
|
||||
data?.notificationAgents ?? NotificationAgentType.EMAIL
|
||||
);
|
||||
}, [data]);
|
||||
|
||||
const UserNotificationsTelegramSchema = Yup.object().shape({
|
||||
telegramChatId: Yup.string()
|
||||
.when('enableTelegram', {
|
||||
is: true,
|
||||
then: Yup.string()
|
||||
.nullable()
|
||||
.required(intl.formatMessage(messages.validationTelegramChatId)),
|
||||
otherwise: Yup.string().nullable(),
|
||||
})
|
||||
.matches(
|
||||
/^-?\d+$/,
|
||||
intl.formatMessage(messages.validationTelegramChatId)
|
||||
),
|
||||
});
|
||||
|
||||
if (!data && !error) {
|
||||
return <LoadingSpinner />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Formik
|
||||
initialValues={{
|
||||
enableTelegram: hasNotificationAgentEnabled(
|
||||
NotificationAgentType.TELEGRAM,
|
||||
data?.notificationAgents ?? NotificationAgentType.EMAIL
|
||||
),
|
||||
telegramChatId: data?.telegramChatId,
|
||||
telegramSendSilently: data?.telegramSendSilently,
|
||||
}}
|
||||
validationSchema={UserNotificationsTelegramSchema}
|
||||
enableReinitialize
|
||||
onSubmit={async (values) => {
|
||||
try {
|
||||
await axios.post(`/api/v1/user/${user?.id}/settings/notifications`, {
|
||||
notificationAgents,
|
||||
pgpKey: data?.pgpKey,
|
||||
discordId: data?.discordId,
|
||||
telegramChatId: values.telegramChatId,
|
||||
telegramSendSilently: values.telegramSendSilently,
|
||||
});
|
||||
addToast(intl.formatMessage(messages.telegramsettingssaved), {
|
||||
appearance: 'success',
|
||||
autoDismiss: true,
|
||||
});
|
||||
} catch (e) {
|
||||
addToast(intl.formatMessage(messages.telegramsettingsfailed), {
|
||||
appearance: 'error',
|
||||
autoDismiss: true,
|
||||
});
|
||||
} finally {
|
||||
revalidate();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{({ errors, touched, isSubmitting, isValid, values, setFieldValue }) => {
|
||||
return (
|
||||
<Form className="section">
|
||||
<div className="form-row">
|
||||
<label htmlFor="enableTelegram" className="checkbox-label">
|
||||
{intl.formatMessage(messages.enableTelegram)}
|
||||
</label>
|
||||
<div className="form-input">
|
||||
<Field
|
||||
type="checkbox"
|
||||
id="enableTelegram"
|
||||
name="enableTelegram"
|
||||
checked={hasNotificationAgentEnabled(
|
||||
NotificationAgentType.TELEGRAM,
|
||||
notificationAgents
|
||||
)}
|
||||
onChange={() => {
|
||||
setNotificationAgents(
|
||||
hasNotificationAgentEnabled(
|
||||
NotificationAgentType.TELEGRAM,
|
||||
notificationAgents
|
||||
)
|
||||
? notificationAgents - NotificationAgentType.TELEGRAM
|
||||
: notificationAgents + NotificationAgentType.TELEGRAM
|
||||
);
|
||||
setFieldValue('enableTelegram', !values.enableTelegram);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label htmlFor="telegramChatId" className="text-label">
|
||||
{intl.formatMessage(messages.telegramChatId)}
|
||||
<span className="label-required">*</span>
|
||||
{data?.telegramBotUsername && (
|
||||
<span className="label-tip">
|
||||
{intl.formatMessage(messages.telegramChatIdTipLong, {
|
||||
TelegramBotLink: function TelegramBotLink(msg) {
|
||||
return (
|
||||
<a
|
||||
href={`https://telegram.me/${data.telegramBotUsername}`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
{msg}
|
||||
</a>
|
||||
);
|
||||
},
|
||||
GetIdBotLink: function GetIdBotLink(msg) {
|
||||
return (
|
||||
<a
|
||||
href="https://telegram.me/get_id_bot"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
{msg}
|
||||
</a>
|
||||
);
|
||||
},
|
||||
code: function code(msg) {
|
||||
return <code>{msg}</code>;
|
||||
},
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
<div className="form-input">
|
||||
<div className="form-input-field">
|
||||
<Field
|
||||
id="telegramChatId"
|
||||
name="telegramChatId"
|
||||
type="text"
|
||||
/>
|
||||
</div>
|
||||
{errors.telegramChatId && touched.telegramChatId && (
|
||||
<div className="error">{errors.telegramChatId}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label htmlFor="telegramSendSilently" className="checkbox-label">
|
||||
{intl.formatMessage(messages.sendSilently)}
|
||||
<span className="label-tip">
|
||||
{intl.formatMessage(messages.sendSilentlyDescription)}
|
||||
</span>
|
||||
</label>
|
||||
<div className="form-input">
|
||||
<Field
|
||||
type="checkbox"
|
||||
id="telegramSendSilently"
|
||||
name="telegramSendSilently"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="actions">
|
||||
<div className="flex justify-end">
|
||||
<span className="inline-flex ml-3 rounded-md shadow-sm">
|
||||
<Button
|
||||
buttonType="primary"
|
||||
type="submit"
|
||||
disabled={isSubmitting || !isValid}
|
||||
>
|
||||
{isSubmitting
|
||||
? intl.formatMessage(globalMessages.saving)
|
||||
: intl.formatMessage(globalMessages.save)}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
);
|
||||
}}
|
||||
</Formik>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserTelegramSettings;
|
@ -1,14 +0,0 @@
|
||||
import { NextPage } from 'next';
|
||||
import React from 'react';
|
||||
import UserSettings from '../../../components/UserProfile/UserSettings';
|
||||
import UserNotificationSettings from '../../../components/UserProfile/UserSettings/UserNotificationSettings';
|
||||
|
||||
const UserSettingsMainPage: NextPage = () => {
|
||||
return (
|
||||
<UserSettings>
|
||||
<UserNotificationSettings />
|
||||
</UserSettings>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserSettingsMainPage;
|
@ -0,0 +1,17 @@
|
||||
import { NextPage } from 'next';
|
||||
import React from 'react';
|
||||
import UserSettings from '../../../../components/UserProfile/UserSettings';
|
||||
import UserNotificationSettings from '../../../../components/UserProfile/UserSettings/UserNotificationSettings';
|
||||
import UserNotificationsDiscord from '../../../../components/UserProfile/UserSettings/UserNotificationSettings/UserNotificationsDiscord';
|
||||
|
||||
const NotificationsPage: NextPage = () => {
|
||||
return (
|
||||
<UserSettings>
|
||||
<UserNotificationSettings>
|
||||
<UserNotificationsDiscord />
|
||||
</UserNotificationSettings>
|
||||
</UserSettings>
|
||||
);
|
||||
};
|
||||
|
||||
export default NotificationsPage;
|
@ -0,0 +1,17 @@
|
||||
import { NextPage } from 'next';
|
||||
import React from 'react';
|
||||
import UserSettings from '../../../../components/UserProfile/UserSettings';
|
||||
import UserNotificationSettings from '../../../../components/UserProfile/UserSettings/UserNotificationSettings';
|
||||
import UserNotificationsEmail from '../../../../components/UserProfile/UserSettings/UserNotificationSettings/UserNotificationsEmail';
|
||||
|
||||
const NotificationsPage: NextPage = () => {
|
||||
return (
|
||||
<UserSettings>
|
||||
<UserNotificationSettings>
|
||||
<UserNotificationsEmail />
|
||||
</UserNotificationSettings>
|
||||
</UserSettings>
|
||||
);
|
||||
};
|
||||
|
||||
export default NotificationsPage;
|
@ -0,0 +1,17 @@
|
||||
import { NextPage } from 'next';
|
||||
import React from 'react';
|
||||
import UserSettings from '../../../../components/UserProfile/UserSettings';
|
||||
import UserNotificationSettings from '../../../../components/UserProfile/UserSettings/UserNotificationSettings';
|
||||
import UserNotificationsTelegram from '../../../../components/UserProfile/UserSettings/UserNotificationSettings/UserNotificationsTelegram';
|
||||
|
||||
const NotificationsPage: NextPage = () => {
|
||||
return (
|
||||
<UserSettings>
|
||||
<UserNotificationSettings>
|
||||
<UserNotificationsTelegram />
|
||||
</UserNotificationSettings>
|
||||
</UserSettings>
|
||||
);
|
||||
};
|
||||
|
||||
export default NotificationsPage;
|
@ -1,17 +0,0 @@
|
||||
import { NextPage } from 'next';
|
||||
import React from 'react';
|
||||
import UserSettings from '../../../../components/UserProfile/UserSettings';
|
||||
import UserNotificationSettings from '../../../../components/UserProfile/UserSettings/UserNotificationSettings';
|
||||
import useRouteGuard from '../../../../hooks/useRouteGuard';
|
||||
import { Permission } from '../../../../hooks/useUser';
|
||||
|
||||
const UserSettingsMainPage: NextPage = () => {
|
||||
useRouteGuard(Permission.MANAGE_USERS);
|
||||
return (
|
||||
<UserSettings>
|
||||
<UserNotificationSettings />
|
||||
</UserSettings>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserSettingsMainPage;
|
@ -0,0 +1,20 @@
|
||||
import { NextPage } from 'next';
|
||||
import React from 'react';
|
||||
import UserSettings from '../../../../../components/UserProfile/UserSettings';
|
||||
import UserNotificationSettings from '../../../../../components/UserProfile/UserSettings/UserNotificationSettings';
|
||||
import UserNotificationsDiscord from '../../../../../components/UserProfile/UserSettings/UserNotificationSettings/UserNotificationsDiscord';
|
||||
import useRouteGuard from '../../../../../hooks/useRouteGuard';
|
||||
import { Permission } from '../../../../../hooks/useUser';
|
||||
|
||||
const NotificationsPage: NextPage = () => {
|
||||
useRouteGuard(Permission.MANAGE_USERS);
|
||||
return (
|
||||
<UserSettings>
|
||||
<UserNotificationSettings>
|
||||
<UserNotificationsDiscord />
|
||||
</UserNotificationSettings>
|
||||
</UserSettings>
|
||||
);
|
||||
};
|
||||
|
||||
export default NotificationsPage;
|
@ -0,0 +1,20 @@
|
||||
import { NextPage } from 'next';
|
||||
import React from 'react';
|
||||
import UserSettings from '../../../../../components/UserProfile/UserSettings';
|
||||
import UserNotificationSettings from '../../../../../components/UserProfile/UserSettings/UserNotificationSettings';
|
||||
import UserNotificationsEmail from '../../../../../components/UserProfile/UserSettings/UserNotificationSettings/UserNotificationsEmail';
|
||||
import useRouteGuard from '../../../../../hooks/useRouteGuard';
|
||||
import { Permission } from '../../../../../hooks/useUser';
|
||||
|
||||
const NotificationsPage: NextPage = () => {
|
||||
useRouteGuard(Permission.MANAGE_USERS);
|
||||
return (
|
||||
<UserSettings>
|
||||
<UserNotificationSettings>
|
||||
<UserNotificationsEmail />
|
||||
</UserNotificationSettings>
|
||||
</UserSettings>
|
||||
);
|
||||
};
|
||||
|
||||
export default NotificationsPage;
|
@ -0,0 +1,20 @@
|
||||
import { NextPage } from 'next';
|
||||
import React from 'react';
|
||||
import UserSettings from '../../../../../components/UserProfile/UserSettings';
|
||||
import UserNotificationSettings from '../../../../../components/UserProfile/UserSettings/UserNotificationSettings';
|
||||
import UserNotificationsTelegram from '../../../../../components/UserProfile/UserSettings/UserNotificationSettings/UserNotificationsTelegram';
|
||||
import useRouteGuard from '../../../../../hooks/useRouteGuard';
|
||||
import { Permission } from '../../../../../hooks/useUser';
|
||||
|
||||
const NotificationsPage: NextPage = () => {
|
||||
useRouteGuard(Permission.MANAGE_USERS);
|
||||
return (
|
||||
<UserSettings>
|
||||
<UserNotificationSettings>
|
||||
<UserNotificationsTelegram />
|
||||
</UserNotificationSettings>
|
||||
</UserSettings>
|
||||
);
|
||||
};
|
||||
|
||||
export default NotificationsPage;
|
Loading…
Reference in new issue