ntfy/web/src/components/SubscribeDialog.jsx

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

422 lines
15 KiB
React
Raw Normal View History

2022-02-20 16:26:58 +13:00
import * as React from "react";
2023-01-10 14:37:13 +13:00
import { useContext, useState } from "react";
import {
Button,
TextField,
Dialog,
DialogContent,
DialogContentText,
DialogTitle,
Autocomplete,
FormControlLabel,
FormGroup,
useMediaQuery,
Switch,
Stack,
} from "@mui/material";
2022-04-09 02:44:35 +12:00
import { useTranslation } from "react-i18next";
import { Warning } from "@mui/icons-material";
import { useLiveQuery } from "dexie-react-hooks";
2022-02-26 07:40:03 +13:00
import theme from "./theme";
2022-12-26 05:59:44 +13:00
import api from "../app/Api";
2022-12-09 03:16:59 +13:00
import { randomAlphanumericString, topicUrl, validTopic, validUrl } from "../app/utils";
import userManager from "../app/UserManager";
import subscriptionManager, { NotificationType } from "../app/SubscriptionManager";
import poller from "../app/Poller";
2022-03-30 08:22:26 +13:00
import DialogFooter from "./DialogFooter";
2022-12-09 14:50:48 +13:00
import session from "../app/Session";
import routes from "./routes";
2023-02-12 14:38:13 +13:00
import accountApi, { Permission, Role } from "../app/AccountApi";
2023-01-05 14:34:22 +13:00
import ReserveTopicSelect from "./ReserveTopicSelect";
2023-01-10 14:37:13 +13:00
import { AccountContext } from "./App";
2023-02-03 09:19:37 +13:00
import { TopicReservedError, UnauthorizedError } from "../app/errors";
2023-02-11 15:19:44 +13:00
import { ReserveLimitChip } from "./SubscriptionPopup";
import notifier from "../app/Notifier";
import prefs from "../app/Prefs";
2022-02-20 16:26:58 +13:00
const publicBaseUrl = "https://ntfy.sh";
2022-02-20 16:26:58 +13:00
export const subscribeTopic = async (baseUrl, topic, opts) => {
const subscription = await subscriptionManager.add(baseUrl, topic, opts);
if (session.exists()) {
try {
await accountApi.addSubscription(baseUrl, topic);
} catch (e) {
console.log(`[SubscribeDialog] Subscribing to topic ${topic} failed`, e);
if (e instanceof UnauthorizedError) {
session.resetAndRedirect(routes.login);
}
}
}
return subscription;
};
2022-02-25 14:18:46 +13:00
const SubscribeDialog = (props) => {
2022-03-01 10:56:38 +13:00
const [baseUrl, setBaseUrl] = useState("");
2022-02-20 16:26:58 +13:00
const [topic, setTopic] = useState("");
2022-02-26 07:40:03 +13:00
const [showLoginPage, setShowLoginPage] = useState(false);
const fullScreen = useMediaQuery(theme.breakpoints.down("sm"));
2023-01-05 14:34:22 +13:00
const webPushDefaultEnabled = useLiveQuery(async () => prefs.webPushDefaultEnabled());
const handleSuccess = async (notificationType) => {
console.log(`[SubscribeDialog] Subscribing to topic ${topic}`);
2023-01-05 16:47:12 +13:00
const actualBaseUrl = baseUrl || config.base_url;
const subscription = await subscribeTopic(actualBaseUrl, topic, {
notificationType,
});
poller.pollInBackground(subscription); // Dangle!
// if the user hasn't changed the default web push setting yet, set it to enabled
if (notificationType === "background" && webPushDefaultEnabled === "initial") {
await prefs.setWebPushDefaultEnabled(true);
}
props.onSuccess(subscription);
2022-02-20 16:26:58 +13:00
};
2023-01-05 14:34:22 +13:00
// wait for liveQuery load
if (webPushDefaultEnabled === undefined) {
return <></>;
}
2022-02-26 07:40:03 +13:00
return (
2022-03-01 10:56:38 +13:00
<Dialog open={props.open} onClose={props.onCancel} fullScreen={fullScreen}>
2022-02-26 07:40:03 +13:00
{!showLoginPage && (
<SubscribePage
baseUrl={baseUrl}
2022-03-01 10:56:38 +13:00
setBaseUrl={setBaseUrl}
2022-02-26 07:40:03 +13:00
topic={topic}
setTopic={setTopic}
subscriptions={props.subscriptions}
onCancel={props.onCancel}
onNeedsLogin={() => setShowLoginPage(true)}
onSuccess={handleSuccess}
webPushDefaultEnabled={webPushDefaultEnabled}
2022-02-26 07:40:03 +13:00
/>
)}
{showLoginPage && <LoginPage baseUrl={baseUrl} topic={topic} onBack={() => setShowLoginPage(false)} onSuccess={handleSuccess} />}
</Dialog>
);
};
const browserNotificationsSupported = notifier.supported();
const pushNotificationsSupported = notifier.pushSupported();
const iosInstallRequired = notifier.iosSupportedButInstallRequired();
const getNotificationTypeFromToggles = (browserNotificationsEnabled, backgroundNotificationsEnabled) => {
if (backgroundNotificationsEnabled) {
return NotificationType.BACKGROUND;
}
if (browserNotificationsEnabled) {
return NotificationType.BROWSER;
}
return NotificationType.SOUND;
};
2022-02-26 07:40:03 +13:00
const SubscribePage = (props) => {
2022-04-09 02:44:35 +12:00
const { t } = useTranslation();
2023-01-10 14:37:13 +13:00
const { account } = useContext(AccountContext);
2023-02-03 09:19:37 +13:00
const [error, setError] = useState("");
2023-01-05 14:34:22 +13:00
const [reserveTopicVisible, setReserveTopicVisible] = useState(false);
2022-03-01 10:56:38 +13:00
const [anotherServerVisible, setAnotherServerVisible] = useState(false);
2023-02-12 14:38:13 +13:00
const [everyone, setEveryone] = useState(Permission.DENY_ALL);
2023-01-05 16:47:12 +13:00
const baseUrl = anotherServerVisible ? props.baseUrl : config.base_url;
const { topic } = props;
2022-03-03 10:16:30 +13:00
const existingTopicUrls = props.subscriptions.map((s) => topicUrl(s.baseUrl, s.topic));
const existingBaseUrls = Array.from(new Set([publicBaseUrl, ...props.subscriptions.map((s) => s.baseUrl)])).filter(
(s) => s !== config.base_url
);
2023-02-12 08:32:50 +13:00
const showReserveTopicCheckbox = config.enable_reservations && !anotherServerVisible && (config.enable_payments || account);
const reserveTopicEnabled =
session.exists() && (account?.role === Role.ADMIN || (account?.role === Role.USER && (account?.stats.reservations_remaining || 0) > 0));
// load initial value, but update it in `handleBrowserNotificationsChanged`
// if we interact with the API and therefore possibly change it (from default -> denied)
const [notificationsExplicitlyDenied, setNotificationsExplicitlyDenied] = useState(notifier.denied());
// default to on if notifications are already granted
const [browserNotificationsEnabled, setBrowserNotificationsEnabled] = useState(notifier.granted());
const [backgroundNotificationsEnabled, setBackgroundNotificationsEnabled] = useState(props.webPushDefaultEnabled === "enabled");
const handleBrowserNotificationsChanged = async (e) => {
if (e.target.checked && (await notifier.maybeRequestPermission())) {
setBrowserNotificationsEnabled(true);
if (props.webPushDefaultEnabled === "enabled") {
setBackgroundNotificationsEnabled(true);
}
} else {
setNotificationsExplicitlyDenied(notifier.denied());
setBrowserNotificationsEnabled(false);
setBackgroundNotificationsEnabled(false);
}
};
const handleBackgroundNotificationsChanged = (e) => {
setBackgroundNotificationsEnabled(e.target.checked);
};
const handleSubscribe = async () => {
2022-03-05 06:10:11 +13:00
const user = await userManager.get(baseUrl); // May be undefined
2022-04-09 02:44:35 +12:00
const username = user ? user.username : t("subscribe_dialog_error_user_anonymous");
2023-01-05 14:34:22 +13:00
// Check read access to topic
2022-12-03 09:37:48 +13:00
const success = await api.topicAuth(baseUrl, topic, user);
if (!success) {
2022-03-05 06:10:11 +13:00
console.log(`[SubscribeDialog] Login to ${topicUrl(baseUrl, topic)} failed for user ${username}`);
if (user) {
2023-02-03 09:19:37 +13:00
setError(
t("subscribe_dialog_error_user_not_authorized", {
username,
})
);
2022-03-05 06:10:11 +13:00
return;
}
2022-03-05 06:10:11 +13:00
props.onNeedsLogin();
2023-05-24 19:03:28 +12:00
return;
2023-05-24 07:13:01 +12:00
}
2023-01-05 14:34:22 +13:00
// Reserve topic (if requested)
2023-01-05 16:47:12 +13:00
if (session.exists() && baseUrl === config.base_url && reserveTopicVisible) {
2023-01-05 14:34:22 +13:00
console.log(`[SubscribeDialog] Reserving topic ${topic} with everyone access ${everyone}`);
try {
2023-01-15 00:43:44 +13:00
await accountApi.upsertReservation(topic, everyone);
2023-01-05 14:34:22 +13:00
} catch (e) {
console.log(`[SubscribeDialog] Error reserving topic`, e);
2023-02-03 09:19:37 +13:00
if (e instanceof UnauthorizedError) {
2023-01-05 14:34:22 +13:00
session.resetAndRedirect(routes.login);
2023-02-03 09:19:37 +13:00
} else if (e instanceof TopicReservedError) {
setError(t("subscribe_dialog_error_topic_already_reserved"));
2023-01-05 14:34:22 +13:00
return;
}
2023-05-24 07:13:01 +12:00
}
}
2023-01-05 14:34:22 +13:00
2022-03-05 06:10:11 +13:00
console.log(`[SubscribeDialog] Successful login to ${topicUrl(baseUrl, topic)} for user ${username}`);
props.onSuccess(getNotificationTypeFromToggles(browserNotificationsEnabled, backgroundNotificationsEnabled));
};
2022-03-01 10:56:38 +13:00
const handleUseAnotherChanged = (e) => {
props.setBaseUrl("");
setAnotherServerVisible(e.target.checked);
if (e.target.checked) {
setBackgroundNotificationsEnabled(false);
}
2022-03-01 10:56:38 +13:00
};
2022-03-01 10:56:38 +13:00
const subscribeButtonEnabled = (() => {
if (anotherServerVisible) {
const isExistingTopicUrl = existingTopicUrls.includes(topicUrl(baseUrl, topic));
return validTopic(topic) && validUrl(baseUrl) && !isExistingTopicUrl;
}
2023-01-05 16:47:12 +13:00
const isExistingTopicUrl = existingTopicUrls.includes(topicUrl(config.base_url, topic));
2022-03-01 10:56:38 +13:00
return validTopic(topic) && !isExistingTopicUrl;
})();
const updateBaseUrl = (ev, newVal) => {
if (validUrl(newVal)) {
2022-10-10 01:50:28 +13:00
props.setBaseUrl(newVal.replace(/\/$/, "")); // strip trailing slash after https?://
} else {
props.setBaseUrl(newVal);
}
};
2022-02-26 07:40:03 +13:00
return (
<>
2022-04-09 02:44:35 +12:00
<DialogTitle>{t("subscribe_dialog_subscribe_title")}</DialogTitle>
2022-02-26 07:40:03 +13:00
<DialogContent>
2022-04-09 02:44:35 +12:00
<DialogContentText>{t("subscribe_dialog_subscribe_description")}</DialogContentText>
2023-01-05 14:34:22 +13:00
<div style={{ display: "flex", paddingBottom: "8px" }} role="row">
<TextField
autoFocus
margin="dense"
id="topic"
placeholder={t("subscribe_dialog_subscribe_topic_placeholder")}
value={props.topic}
onChange={(ev) => props.setTopic(ev.target.value)}
type="text"
fullWidth
variant="standard"
inputProps={{
maxLength: 64,
"aria-label": t("subscribe_dialog_subscribe_topic_placeholder"),
}}
/>
<Button
onClick={() => {
props.setTopic(randomAlphanumericString(16));
}}
style={{ flexShrink: "0", marginTop: "0.5em" }}
>
{t("subscribe_dialog_subscribe_button_generate_topic_name")}
</Button>
</div>
2023-02-11 15:19:44 +13:00
{showReserveTopicCheckbox && (
2023-01-05 14:34:22 +13:00
<FormGroup>
<FormControlLabel
2022-05-04 06:53:07 +12:00
variant="standard"
2023-01-05 14:34:22 +13:00
control={
<Switch
2023-01-10 14:37:13 +13:00
disabled={!reserveTopicEnabled}
2023-01-05 14:34:22 +13:00
checked={reserveTopicVisible}
onChange={(ev) => setReserveTopicVisible(ev.target.checked)}
inputProps={{
2023-02-01 15:39:30 +13:00
"aria-label": t("reserve_dialog_checkbox_label"),
2023-01-05 14:34:22 +13:00
}}
/>
}
2023-02-08 17:18:41 +13:00
label={
<>
{t("reserve_dialog_checkbox_label")}
2023-02-11 15:19:44 +13:00
<ReserveLimitChip />
2023-02-08 17:18:41 +13:00
</>
}
2022-05-04 06:53:07 +12:00
/>
2023-01-05 14:34:22 +13:00
{reserveTopicVisible && <ReserveTopicSelect value={everyone} onChange={setEveryone} />}
</FormGroup>
)}
{!reserveTopicVisible && (
<FormGroup>
<FormControlLabel
control={
<Switch
2023-01-05 14:34:22 +13:00
onChange={handleUseAnotherChanged}
checked={anotherServerVisible}
2023-01-05 14:34:22 +13:00
inputProps={{
"aria-label": t("subscribe_dialog_subscribe_use_another_label"),
}}
/>
}
label={t("subscribe_dialog_subscribe_use_another_label")}
/>
{anotherServerVisible && (
<Autocomplete
freeSolo
options={existingBaseUrls}
inputValue={props.baseUrl}
onInputChange={updateBaseUrl}
renderInput={(params) => (
<TextField
{...params}
placeholder={config.base_url}
variant="standard"
aria-label={t("subscribe_dialog_subscribe_base_url_label")}
/>
2023-05-24 07:13:01 +12:00
)}
2023-01-05 14:34:22 +13:00
/>
)}
</FormGroup>
)}
{browserNotificationsSupported && (
<FormGroup>
<FormControlLabel
control={
<Switch
onChange={handleBrowserNotificationsChanged}
checked={browserNotificationsEnabled}
disabled={notificationsExplicitlyDenied}
inputProps={{
"aria-label": t("subscribe_dialog_subscribe_enable_browser_notifications_label"),
}}
/>
}
label={
<Stack direction="row" gap={1} alignItems="center">
{t("subscribe_dialog_subscribe_enable_browser_notifications_label")}
{notificationsExplicitlyDenied && <Warning />}
</Stack>
}
/>
{pushNotificationsSupported && !anotherServerVisible && browserNotificationsEnabled && (
<FormControlLabel
control={
<Switch
onChange={handleBackgroundNotificationsChanged}
checked={backgroundNotificationsEnabled}
disabled={iosInstallRequired}
inputProps={{
"aria-label": t("subscribe_dialog_subscribe_enable_background_notifications_label"),
}}
/>
}
label={t("subscribe_dialog_subscribe_enable_background_notifications_label")}
/>
)}
</FormGroup>
)}
2022-02-26 07:40:03 +13:00
</DialogContent>
2023-02-03 09:19:37 +13:00
<DialogFooter status={error}>
2022-04-09 02:44:35 +12:00
<Button onClick={props.onCancel}>{t("subscribe_dialog_subscribe_button_cancel")}</Button>
<Button onClick={handleSubscribe} disabled={!subscribeButtonEnabled}>
{t("subscribe_dialog_subscribe_button_subscribe")}
</Button>
2022-03-05 06:10:11 +13:00
</DialogFooter>
2022-02-26 07:40:03 +13:00
</>
);
};
const LoginPage = (props) => {
2022-04-09 02:44:35 +12:00
const { t } = useTranslation();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
2023-02-03 09:19:37 +13:00
const [error, setError] = useState("");
2023-01-05 16:47:12 +13:00
const baseUrl = props.baseUrl ? props.baseUrl : config.base_url;
2022-12-03 09:37:48 +13:00
const { topic } = props;
2023-02-03 09:19:37 +13:00
2022-04-09 02:44:35 +12:00
const handleLogin = async () => {
2022-02-26 07:40:03 +13:00
const user = { baseUrl, username, password };
const success = await api.topicAuth(baseUrl, topic, user);
if (!success) {
2022-04-09 02:44:35 +12:00
console.log(`[SubscribeDialog] Login to ${topicUrl(baseUrl, topic)} failed for user ${username}`);
2022-05-04 06:53:07 +12:00
setError(t("subscribe_dialog_error_user_not_authorized", { username }));
return;
2022-05-04 06:53:07 +12:00
}
2022-04-09 02:44:35 +12:00
console.log(`[SubscribeDialog] Successful login to ${topicUrl(baseUrl, topic)} for user ${username}`);
await userManager.save(user);
props.onSuccess();
2023-05-24 07:13:01 +12:00
};
return (
<>
2022-04-09 02:44:35 +12:00
<DialogTitle>{t("subscribe_dialog_login_title")}</DialogTitle>
2022-02-26 07:40:03 +13:00
<DialogContent>
2022-04-09 02:44:35 +12:00
<DialogContentText>{t("subscribe_dialog_login_description")}</DialogContentText>
2022-02-26 07:40:03 +13:00
<TextField
2023-05-24 07:13:01 +12:00
autoFocus
2022-02-26 07:40:03 +13:00
margin="dense"
id="username"
2022-04-09 02:44:35 +12:00
label={t("subscribe_dialog_login_username_label")}
value={username}
onChange={(ev) => setUsername(ev.target.value)}
2022-02-26 07:40:03 +13:00
type="text"
fullWidth
variant="standard"
2022-05-04 06:53:07 +12:00
inputProps={{
"aria-label": t("subscribe_dialog_login_username_label"),
2023-05-24 07:13:01 +12:00
}}
/>
2022-02-26 07:40:03 +13:00
<TextField
margin="dense"
id="password"
2022-04-09 02:44:35 +12:00
label={t("subscribe_dialog_login_password_label")}
2022-02-26 07:40:03 +13:00
type="password"
value={password}
onChange={(ev) => setPassword(ev.target.value)}
2022-02-26 07:40:03 +13:00
fullWidth
variant="standard"
2022-05-04 06:53:07 +12:00
inputProps={{
"aria-label": t("subscribe_dialog_login_password_label"),
2023-05-24 07:13:01 +12:00
}}
/>
2022-02-26 07:40:03 +13:00
</DialogContent>
2023-02-03 09:19:37 +13:00
<DialogFooter status={error}>
2023-05-13 13:47:41 +12:00
<Button onClick={props.onBack}>{t("common_back")}</Button>
2022-04-09 02:44:35 +12:00
<Button onClick={handleLogin}>{t("subscribe_dialog_login_button_login")}</Button>
</DialogFooter>
2023-05-24 07:13:01 +12:00
</>
);
2022-02-20 16:26:58 +13:00
};
2022-02-25 14:18:46 +13:00
export default SubscribeDialog;