Debian Codegraph @

web/src/components/SubscriptionPopup.jsx

raw
1 import * as React from "react";
2 import { useContext, useState } from "react";
3 import {
4 Button,
5 TextField,
6 Dialog,
7 DialogContent,
8 DialogContentText,
9 DialogTitle,
10 Chip,
11 InputAdornment,
12 Portal,
13 Snackbar,
14 useMediaQuery,
15 MenuItem,
16 IconButton,
17 ListItemIcon,
18 useTheme,
19 } from "@mui/material";
20 import { useTranslation } from "react-i18next";
21 import { useNavigate } from "react-router-dom";
22 import Clear from "@mui/icons-material/Clear";
23 import ClearAll from "@mui/icons-material/ClearAll";
24 import Edit from "@mui/icons-material/Edit";
25 import EnhancedEncryption from "@mui/icons-material/EnhancedEncryption";
26 import Lock from "@mui/icons-material/Lock";
27 import LockOpen from "@mui/icons-material/LockOpen";
28 import Notifications from "@mui/icons-material/Notifications";
29 import NotificationsOff from "@mui/icons-material/NotificationsOff";
30 import RemoveCircle from "@mui/icons-material/RemoveCircle";
31 import Send from "@mui/icons-material/Send";
32 import subscriptionManager from "../app/SubscriptionManager";
33 import DialogFooter from "./DialogFooter";
34 import accountApi, { Role } from "../app/AccountApi";
35 import session from "../app/Session";
36 import routes from "./routes";
37 import PopupMenu from "./PopupMenu";
38 import { formatDateTime, shuffle } from "../app/utils";
39 import api from "../app/Api";
40 import AccountContext from "./AccountContext";
41 import { usePrefCache } from "./PrefCache";
42 import { ReserveAddDialog, ReserveDeleteDialog, ReserveEditDialog } from "./ReserveDialogs";
43 import { UnauthorizedError } from "../app/errors";
44
45 export const SubscriptionPopup = (props) => {
46 const { t } = useTranslation();
47 const { dateFormat, timeFormat } = usePrefCache();
48 const { account } = useContext(AccountContext);
49 const navigate = useNavigate();
50 const [displayNameDialogOpen, setDisplayNameDialogOpen] = useState(false);
51 const [reserveAddDialogOpen, setReserveAddDialogOpen] = useState(false);
52 const [reserveEditDialogOpen, setReserveEditDialogOpen] = useState(false);
53 const [reserveDeleteDialogOpen, setReserveDeleteDialogOpen] = useState(false);
54 const [showPublishError, setShowPublishError] = useState(false);
55 const { subscription } = props;
56 const placement = props.placement ?? "left";
57 const reservations = account?.reservations || [];
58
59 const showReservationAdd = config.enable_reservations && !subscription?.reservation && account?.stats.reservations_remaining > 0;
60 const showReservationAddDisabled =
61 !showReservationAdd &&
62 config.enable_reservations &&
63 !subscription?.reservation &&
64 (config.enable_payments || account?.stats.reservations_remaining === 0);
65 const showReservationEdit = config.enable_reservations && !!subscription?.reservation;
66 const showReservationDelete = config.enable_reservations && !!subscription?.reservation;
67
68 const handleChangeDisplayName = async () => {
69 setDisplayNameDialogOpen(true);
70 };
71
72 const handleReserveAdd = async () => {
73 setReserveAddDialogOpen(true);
74 };
75
76 const handleReserveEdit = async () => {
77 setReserveEditDialogOpen(true);
78 };
79
80 const handleReserveDelete = async () => {
81 setReserveDeleteDialogOpen(true);
82 };
83
84 const handleSendTestMessage = async () => {
85 const { baseUrl, topic } = props.subscription;
86 const tags = shuffle([
87 "grinning",
88 "octopus",
89 "upside_down_face",
90 "palm_tree",
91 "maple_leaf",
92 "apple",
93 "skull",
94 "warning",
95 "jack_o_lantern",
96 "de-server-1",
97 "backups",
98 "cron-script",
99 "script-error",
100 "phils-automation",
101 "mouse",
102 "go-rocks",
103 "hi-ben",
104 ]).slice(0, Math.round(Math.random() * 4));
105 const priority = shuffle([1, 2, 3, 4, 5])[0];
106 const title = shuffle([
107 "",
108 "",
109 "", // Higher chance of no title
110 "Oh my, another test message?",
111 "Titles are optional, did you know that?",
112 "ntfy is open source, and will always be free. Cool, right?",
113 "I don't really like apples",
114 "My favorite TV show is The Wire. You should watch it!",
115 "You can attach files and URLs to messages too",
116 "You can delay messages up to 3 days",
117 ])[0];
118 const nowSeconds = Math.round(Date.now() / 1000);
119 const message = shuffle([
120 `Hello friend, this is a test notification from ntfy web. It's ${formatDateTime(
121 nowSeconds,
122 dateFormat,
123 timeFormat,
124 )} right now. Is that early or late?`,
125 `So I heard you like ntfy? If that's true, go to GitHub and star it, or to the Play store and rate it. Thanks! Oh yeah, this is a test notification.`,
126 `It's almost like you want to hear what I have to say. I'm not even a machine. I'm just a sentence that Phil typed on a random Thursday.`,
127 `Alright then, it's ${formatDateTime(
128 nowSeconds,
129 dateFormat,
130 timeFormat,
131 )} already. Boy oh boy, where did the time go? I hope you're alright, friend.`,
132 `There are nine million bicycles in Beijing That's a fact; It's a thing we can't deny. I wonder if that's true ...`,
133 `I'm really excited that you're trying out ntfy. Did you know that there are a few public topics, such as ntfy.sh/stats and ntfy.sh/announcements.`,
134 `It's interesting to hear what people use ntfy for. I've heard people talk about using it for so many cool things. What do you use it for?`,
135 ])[0];
136 try {
137 await api.publish(baseUrl, topic, message, {
138 title,
139 priority,
140 tags,
141 });
142 } catch (e) {
143 console.log(`[SubscriptionPopup] Error publishing message`, e);
144 setShowPublishError(true);
145 }
146 };
147
148 const handleClearAll = async () => {
149 console.log(`[SubscriptionPopup] Deleting all notifications from ${props.subscription.id}`);
150 await subscriptionManager.deleteNotifications(props.subscription.id);
151 };
152
153 const handleSetMutedUntil = async (mutedUntil) => {
154 await subscriptionManager.setMutedUntil(subscription.id, mutedUntil);
155 };
156
157 const handleUnsubscribe = async () => {
158 console.log(`[SubscriptionPopup] Unsubscribing from ${props.subscription.id}`, props.subscription);
159 await subscriptionManager.remove(props.subscription);
160 if (session.exists() && !subscription.internal) {
161 try {
162 await accountApi.deleteSubscription(props.subscription.baseUrl, props.subscription.topic);
163 } catch (e) {
164 console.log(`[SubscriptionPopup] Error unsubscribing`, e);
165 if (e instanceof UnauthorizedError) {
166 await session.resetAndRedirect(routes.login);
167 }
168 }
169 }
170 const newSelected = await subscriptionManager.first(); // May be undefined
171 if (newSelected && !newSelected.internal) {
172 navigate(routes.forSubscription(newSelected));
173 } else {
174 navigate(routes.app);
175 }
176 };
177
178 return (
179 <>
180 <PopupMenu horizontal={placement} anchorEl={props.anchor} open={!!props.anchor} onClose={props.onClose}>
181 <MenuItem onClick={handleChangeDisplayName}>
182 <ListItemIcon>
183 <Edit fontSize="small" />
184 </ListItemIcon>
185 {t("action_bar_change_display_name")}
186 </MenuItem>
187 {showReservationAdd && (
188 <MenuItem onClick={handleReserveAdd}>
189 <ListItemIcon>
190 <Lock fontSize="small" />
191 </ListItemIcon>
192 {t("action_bar_reservation_add")}
193 </MenuItem>
194 )}
195 {showReservationAddDisabled && (
196 <MenuItem sx={{ cursor: "default" }}>
197 <ListItemIcon>
198 <Lock fontSize="small" color="disabled" />
199 </ListItemIcon>
200 <span style={{ opacity: 0.3 }}>{t("action_bar_reservation_add")}</span>
201 <ReserveLimitChip />
202 </MenuItem>
203 )}
204 {showReservationEdit && (
205 <MenuItem onClick={handleReserveEdit}>
206 <ListItemIcon>
207 <EnhancedEncryption fontSize="small" />
208 </ListItemIcon>
209 {t("action_bar_reservation_edit")}
210 </MenuItem>
211 )}
212 {showReservationDelete && (
213 <MenuItem onClick={handleReserveDelete}>
214 <ListItemIcon>
215 <LockOpen fontSize="small" />
216 </ListItemIcon>
217 {t("action_bar_reservation_delete")}
218 </MenuItem>
219 )}
220 <MenuItem onClick={handleSendTestMessage}>
221 <ListItemIcon>
222 <Send fontSize="small" />
223 </ListItemIcon>
224 {t("action_bar_send_test_notification")}
225 </MenuItem>
226 <MenuItem onClick={handleClearAll}>
227 <ListItemIcon>
228 <ClearAll fontSize="small" />
229 </ListItemIcon>
230 {t("action_bar_clear_notifications")}
231 </MenuItem>
232 {!!subscription.mutedUntil && (
233 <MenuItem onClick={() => handleSetMutedUntil(0)}>
234 <ListItemIcon>
235 <Notifications fontSize="small" />
236 </ListItemIcon>
237 {t("action_bar_unmute_notifications")}
238 </MenuItem>
239 )}
240 {!subscription.mutedUntil && (
241 <MenuItem onClick={() => handleSetMutedUntil(1)}>
242 <ListItemIcon>
243 <NotificationsOff fontSize="small" />
244 </ListItemIcon>
245 {t("action_bar_mute_notifications")}
246 </MenuItem>
247 )}
248 <MenuItem onClick={handleUnsubscribe}>
249 <ListItemIcon>
250 <RemoveCircle fontSize="small" />
251 </ListItemIcon>
252 {t("action_bar_unsubscribe")}
253 </MenuItem>
254 </PopupMenu>
255 <Portal>
256 <Snackbar
257 open={showPublishError}
258 autoHideDuration={3000}
259 onClose={() => setShowPublishError(false)}
260 message={t("message_bar_error_publishing")}
261 />
262 <DisplayNameDialog open={displayNameDialogOpen} subscription={subscription} onClose={() => setDisplayNameDialogOpen(false)} />
263 {showReservationAdd && (
264 <ReserveAddDialog
265 open={reserveAddDialogOpen}
266 topic={subscription.topic}
267 reservations={reservations}
268 onClose={() => setReserveAddDialogOpen(false)}
269 />
270 )}
271 {showReservationEdit && (
272 <ReserveEditDialog
273 open={reserveEditDialogOpen}
274 reservation={subscription.reservation}
275 reservations={props.reservations}
276 onClose={() => setReserveEditDialogOpen(false)}
277 />
278 )}
279 {showReservationDelete && (
280 <ReserveDeleteDialog
281 open={reserveDeleteDialogOpen}
282 topic={subscription.topic}
283 onClose={() => setReserveDeleteDialogOpen(false)}
284 />
285 )}
286 </Portal>
287 </>
288 );
289 };
290
291 const DisplayNameDialog = (props) => {
292 const theme = useTheme();
293 const { t } = useTranslation();
294 const { subscription } = props;
295 const [error, setError] = useState("");
296 const [displayName, setDisplayName] = useState(subscription.displayName ?? "");
297 const fullScreen = useMediaQuery(theme.breakpoints.down("sm"));
298
299 const handleSave = async () => {
300 await subscriptionManager.setDisplayName(subscription.id, displayName);
301 if (session.exists() && !subscription.internal) {
302 try {
303 console.log(`[SubscriptionSettingsDialog] Updating subscription display name to ${displayName}`);
304 await accountApi.updateSubscription(subscription.baseUrl, subscription.topic, { display_name: displayName });
305 } catch (e) {
306 console.log(`[SubscriptionSettingsDialog] Error updating subscription`, e);
307 if (e instanceof UnauthorizedError) {
308 await session.resetAndRedirect(routes.login);
309 } else {
310 setError(e.message);
311 return;
312 }
313 }
314 }
315 props.onClose();
316 };
317
318 return (
319 <Dialog open={props.open} onClose={props.onClose} maxWidth="sm" fullWidth fullScreen={fullScreen}>
320 <DialogTitle>{t("display_name_dialog_title")}</DialogTitle>
321 <DialogContent>
322 <DialogContentText>{t("display_name_dialog_description")}</DialogContentText>
323 <TextField
324 autoFocus
325 placeholder={t("display_name_dialog_placeholder")}
326 value={displayName}
327 onChange={(ev) => setDisplayName(ev.target.value)}
328 type="text"
329 fullWidth
330 variant="standard"
331 slotProps={{
332 htmlInput: {
333 maxLength: 64,
334 "aria-label": t("display_name_dialog_placeholder"),
335 },
336 input: {
337 endAdornment: (
338 <InputAdornment position="end">
339 <IconButton onClick={() => setDisplayName("")} edge="end">
340 <Clear />
341 </IconButton>
342 </InputAdornment>
343 ),
344 },
345 }}
346 />
347 </DialogContent>
348 <DialogFooter status={error}>
349 <Button onClick={props.onClose}>{t("common_cancel")}</Button>
350 <Button onClick={handleSave}>{t("common_save")}</Button>
351 </DialogFooter>
352 </Dialog>
353 );
354 };
355
356 export const ReserveLimitChip = () => {
357 const { account } = useContext(AccountContext);
358 if (account?.role === Role.ADMIN || account?.stats.reservations_remaining > 0) {
359 return <></>;
360 }
361 if (config.enable_payments) {
362 return account?.limits.reservations > 0 ? <LimitReachedChip /> : <ProChip />;
363 }
364 if (account) {
365 return <LimitReachedChip />;
366 }
367 return <></>;
368 };
369
370 const LimitReachedChip = () => {
371 const { t } = useTranslation();
372 return (
373 <Chip
374 label={t("action_bar_reservation_limit_reached")}
375 variant="outlined"
376 color="primary"
377 sx={{
378 opacity: 0.8,
379 borderWidth: "2px",
380 height: "24px",
381 marginLeft: "5px",
382 }}
383 />
384 );
385 };
386
387 export const ProChip = () => (
388 <Chip
389 label="ntfy Pro"
390 variant="outlined"
391 color="primary"
392 sx={{
393 opacity: 0.8,
394 fontWeight: "bold",
395 borderWidth: "2px",
396 height: "24px",
397 marginLeft: "5px",
398 }}
399 />
400 );