refactor: organized placement of new button + added comments

pull/3421/head
Brandon 2 years ago committed by Brandon Cohen
parent 8dcce0e569
commit e6c054fb73

@ -3652,34 +3652,6 @@ paths:
type: array type: array
items: items:
$ref: '#/components/schemas/MediaRequest' $ref: '#/components/schemas/MediaRequest'
/user/{userId}/pushSubscription:
get:
summary: Get web push notification settings for a user
description: |
Returns web push notification settings for a user in a JSON object.
tags:
- users
parameters:
- in: path
name: userId
required: true
schema:
type: number
responses:
'200':
description: User web push notification settings in JSON
content:
application/json:
schema:
type: object
properties:
endpoint:
type: string
p256dh:
type: string
auth:
type: string
/user/{userId}/quota: /user/{userId}/quota:
get: get:
summary: Get quotas for a specific user summary: Get quotas for a specific user

@ -1,7 +1,6 @@
import type Media from '@server/entity/Media'; import type Media from '@server/entity/Media';
import type { MediaRequest } from '@server/entity/MediaRequest'; import type { MediaRequest } from '@server/entity/MediaRequest';
import type { User } from '@server/entity/User'; import type { User } from '@server/entity/User';
import type { UserPushSubscription } from '@server/entity/UserPushSubscription';
import type { PaginatedResponse } from './common'; import type { PaginatedResponse } from './common';
export interface UserResultsResponse extends PaginatedResponse { export interface UserResultsResponse extends PaginatedResponse {
@ -29,7 +28,3 @@ export interface UserWatchDataResponse {
recentlyWatched: Media[]; recentlyWatched: Media[];
playCount: number; playCount: number;
} }
export interface UserPushSubscriptionResponse {
result: UserPushSubscription;
}

@ -180,30 +180,6 @@ router.post<
} }
}); });
router.get<{ id: string }>('/:id/pushSubscription', async (req, res, next) => {
try {
const userPushSubRepository = getRepository(UserPushSubscription);
const userSubscription = await userPushSubRepository.findOneOrFail({
relations: {
user: true,
},
where: {
user: {
id: Number(req.params.id),
},
},
});
console.log({ id: Number(req.params.id), userSubscription });
return res.status(200).json(userSubscription);
// console.log('hello is this owrking');
} catch (e) {
next({ status: 404, message: 'User subscription not found.' });
}
});
router.get<{ id: string }>('/:id', async (req, res, next) => { router.get<{ id: string }>('/:id', async (req, res, next) => {
try { try {
const userRepository = getRepository(User); const userRepository = getRepository(User);

@ -7,6 +7,10 @@ import useSettings from '@app/hooks/useSettings';
import { useUser } from '@app/hooks/useUser'; import { useUser } from '@app/hooks/useUser';
import globalMessages from '@app/i18n/globalMessages'; import globalMessages from '@app/i18n/globalMessages';
import { ArrowDownOnSquareIcon } from '@heroicons/react/24/outline'; import { ArrowDownOnSquareIcon } from '@heroicons/react/24/outline';
import {
CloudArrowDownIcon,
CloudArrowUpIcon,
} from '@heroicons/react/24/solid';
import type { UserSettingsNotificationsResponse } from '@server/interfaces/api/userSettingsInterfaces'; import type { UserSettingsNotificationsResponse } from '@server/interfaces/api/userSettingsInterfaces';
import axios from 'axios'; import axios from 'axios';
import { Form, Formik } from 'formik'; import { Form, Formik } from 'formik';
@ -19,6 +23,8 @@ import useSWR, { mutate } from 'swr';
const messages = defineMessages({ const messages = defineMessages({
webpushsettingssaved: 'Web push notification settings saved successfully!', webpushsettingssaved: 'Web push notification settings saved successfully!',
webpushsettingsfailed: 'Web push notification settings failed to save.', webpushsettingsfailed: 'Web push notification settings failed to save.',
enablewebpush: 'Enable web push',
disablewebpush: 'Disable web push',
}); });
const UserWebPushSettings = () => { const UserWebPushSettings = () => {
@ -27,6 +33,7 @@ const UserWebPushSettings = () => {
const router = useRouter(); const router = useRouter();
const { user } = useUser({ id: Number(router.query.userId) }); const { user } = useUser({ id: Number(router.query.userId) });
const { currentSettings } = useSettings(); const { currentSettings } = useSettings();
const [webPushEnabled, setWebPushEnabled] = useState(false);
const { const {
data, data,
error, error,
@ -34,8 +41,9 @@ const UserWebPushSettings = () => {
} = useSWR<UserSettingsNotificationsResponse>( } = useSWR<UserSettingsNotificationsResponse>(
user ? `/api/v1/user/${user?.id}/settings/notifications` : null user ? `/api/v1/user/${user?.id}/settings/notifications` : null
); );
const [webPushEnabled, setWebPushEnabled] = useState(false);
// Subscribes to the push manager
// Will only add to the database if subscribing for the first time
const enablePushNotifications = () => { const enablePushNotifications = () => {
if ('serviceWorker' in navigator && user?.id) { if ('serviceWorker' in navigator && user?.id) {
navigator.serviceWorker navigator.serviceWorker
@ -67,6 +75,7 @@ const UserWebPushSettings = () => {
} }
}) })
.catch(function (error) { .catch(function (error) {
// eslint-disable-next-line no-console
console.log( console.log(
'[SW] Failure subscribing to push manager, error:', '[SW] Failure subscribing to push manager, error:',
error error
@ -75,6 +84,7 @@ const UserWebPushSettings = () => {
} }
}; };
// Unsubscribes to the push manager
const disablePushNotifications = () => { const disablePushNotifications = () => {
if ('serviceWorker' in navigator && user?.id) { if ('serviceWorker' in navigator && user?.id) {
navigator.serviceWorker.getRegistration('/sw.js').then((registration) => { navigator.serviceWorker.getRegistration('/sw.js').then((registration) => {
@ -85,6 +95,7 @@ const UserWebPushSettings = () => {
?.unsubscribe() ?.unsubscribe()
.then(() => setWebPushEnabled(false)) .then(() => setWebPushEnabled(false))
.catch(function (error) { .catch(function (error) {
// eslint-disable-next-line no-console
console.log( console.log(
'[SW] Failure unsubscribing to push manager, error:', '[SW] Failure unsubscribing to push manager, error:',
error error
@ -95,6 +106,8 @@ const UserWebPushSettings = () => {
} }
}; };
// Checks our current subscription on page load
// Will set the web push state to true if subscribed
useEffect(() => { useEffect(() => {
if ('serviceWorker' in navigator && user?.id) { if ('serviceWorker' in navigator && user?.id) {
navigator.serviceWorker navigator.serviceWorker
@ -105,6 +118,13 @@ const UserWebPushSettings = () => {
setWebPushEnabled(true); setWebPushEnabled(true);
} }
}); });
})
.catch(function (error) {
// eslint-disable-next-line no-console
console.log(
'[SW] Failure retrieving push manager subscription, error:',
error
);
}); });
} }
}, [user?.id]); }, [user?.id]);
@ -158,64 +178,63 @@ const UserWebPushSettings = () => {
setFieldTouched, setFieldTouched,
}) => { }) => {
return ( return (
<> <Form className="section">
{webPushEnabled ? ( {webPushEnabled && (
<Form className="section"> <NotificationTypeSelector
<NotificationTypeSelector user={user}
user={user} currentTypes={values.types}
currentTypes={values.types} onUpdate={(newTypes) => {
onUpdate={(newTypes) => { setFieldValue('types', newTypes);
setFieldValue('types', newTypes); setFieldTouched('types');
setFieldTouched('types'); }}
}} error={
error={ errors.types && touched.types
errors.types && touched.types ? (errors.types as string)
? (errors.types as string) : undefined
: undefined }
} />
/> )}
<div className="actions"> <div className="actions">
<div className="flex justify-end"> <div className="flex justify-end">
<span className="ml-3 inline-flex rounded-md shadow-sm"> <span className="ml-3 inline-flex rounded-md shadow-sm">
<Button <Button
buttonType="primary" buttonType={`${webPushEnabled ? 'danger' : 'warning'}`}
type="submit" type="button"
disabled={isSubmitting || !isValid} onClick={() =>
> webPushEnabled
<ArrowDownOnSquareIcon /> ? disablePushNotifications()
<span> : enablePushNotifications()
{isSubmitting }
? intl.formatMessage(globalMessages.saving) >
: intl.formatMessage(globalMessages.save)} {webPushEnabled ? (
</span> <CloudArrowDownIcon />
</Button> ) : (
<CloudArrowUpIcon />
)}
<span>
{webPushEnabled
? intl.formatMessage(messages.disablewebpush)
: intl.formatMessage(messages.enablewebpush)}
</span> </span>
</div> </Button>
</div> </span>
</Form> <span className="ml-3 inline-flex rounded-md shadow-sm">
) : ( <Button
<div className="actions"> buttonType="primary"
<div className="flex justify-end"> type="submit"
<span className="ml-3 inline-flex rounded-md shadow-sm"> disabled={isSubmitting || !isValid}
<Button >
buttonType="primary" <ArrowDownOnSquareIcon />
onClick={() => enablePushNotifications()} <span>
> {isSubmitting
<ArrowDownOnSquareIcon /> ? intl.formatMessage(globalMessages.saving)
<span>Enable Web Push</span> : intl.formatMessage(globalMessages.save)}
</Button> </span>
</span> </Button>
</div> </span>
</div> </div>
)} </div>
<Button </Form>
buttonType="primary"
onClick={() => disablePushNotifications()}
>
<ArrowDownOnSquareIcon />
<span>Disable Web Push</span>
</Button>
</>
); );
}} }}
</Formik> </Formik>

@ -1101,6 +1101,7 @@
"components.UserProfile.UserSettings.UserGeneralSettings.toastSettingsSuccess": "Settings saved successfully!", "components.UserProfile.UserSettings.UserGeneralSettings.toastSettingsSuccess": "Settings saved successfully!",
"components.UserProfile.UserSettings.UserGeneralSettings.user": "User", "components.UserProfile.UserSettings.UserGeneralSettings.user": "User",
"components.UserProfile.UserSettings.UserGeneralSettings.validationDiscordId": "You must provide a valid Discord user ID", "components.UserProfile.UserSettings.UserGeneralSettings.validationDiscordId": "You must provide a valid Discord user ID",
"components.UserProfile.UserSettings.UserNotificationSettings.disablewebpush": "Disable web push",
"components.UserProfile.UserSettings.UserNotificationSettings.discordId": "User ID", "components.UserProfile.UserSettings.UserNotificationSettings.discordId": "User ID",
"components.UserProfile.UserSettings.UserNotificationSettings.discordIdTip": "The <FindDiscordIdLink>multi-digit ID number</FindDiscordIdLink> associated with your user account", "components.UserProfile.UserSettings.UserNotificationSettings.discordIdTip": "The <FindDiscordIdLink>multi-digit ID number</FindDiscordIdLink> associated with your user account",
"components.UserProfile.UserSettings.UserNotificationSettings.discordsettingsfailed": "Discord notification settings failed to save.", "components.UserProfile.UserSettings.UserNotificationSettings.discordsettingsfailed": "Discord notification settings failed to save.",
@ -1108,6 +1109,7 @@
"components.UserProfile.UserSettings.UserNotificationSettings.email": "Email", "components.UserProfile.UserSettings.UserNotificationSettings.email": "Email",
"components.UserProfile.UserSettings.UserNotificationSettings.emailsettingsfailed": "Email notification settings failed to save.", "components.UserProfile.UserSettings.UserNotificationSettings.emailsettingsfailed": "Email notification settings failed to save.",
"components.UserProfile.UserSettings.UserNotificationSettings.emailsettingssaved": "Email notification settings saved successfully!", "components.UserProfile.UserSettings.UserNotificationSettings.emailsettingssaved": "Email notification settings saved successfully!",
"components.UserProfile.UserSettings.UserNotificationSettings.enablewebpush": "Enable web push",
"components.UserProfile.UserSettings.UserNotificationSettings.notifications": "Notifications", "components.UserProfile.UserSettings.UserNotificationSettings.notifications": "Notifications",
"components.UserProfile.UserSettings.UserNotificationSettings.notificationsettings": "Notification Settings", "components.UserProfile.UserSettings.UserNotificationSettings.notificationsettings": "Notification Settings",
"components.UserProfile.UserSettings.UserNotificationSettings.pgpPublicKey": "PGP Public Key", "components.UserProfile.UserSettings.UserNotificationSettings.pgpPublicKey": "PGP Public Key",

Loading…
Cancel
Save