ntfy/web/src/components/SubscribeDialog.jsx

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

315 lines
11 KiB
React
Raw Normal View History

2022-02-20 04:26:58 +01:00
import * as React from "react";
2023-01-10 02:37:13 +01:00
import { useContext, useState } from "react";
2022-02-20 04:26:58 +01:00
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent";
import DialogContentText from "@mui/material/DialogContentText";
import DialogTitle from "@mui/material/DialogTitle";
2023-02-11 03:19:44 +01:00
import { Autocomplete, Checkbox, FormControlLabel, FormGroup, useMediaQuery } from "@mui/material";
2023-05-24 09:03:28 +02:00
import { useTranslation } from "react-i18next";
2022-02-25 19:40:03 +01:00
import theme from "./theme";
2022-12-25 17:59:44 +01:00
import api from "../app/Api";
2022-12-08 15:16:59 +01:00
import { randomAlphanumericString, topicUrl, validTopic, validUrl } from "../app/utils";
import userManager from "../app/UserManager";
import subscriptionManager from "../app/SubscriptionManager";
import poller from "../app/Poller";
2022-03-29 21:22:26 +02:00
import DialogFooter from "./DialogFooter";
2022-12-09 02:50:48 +01:00
import session from "../app/Session";
import routes from "./routes";
2023-02-12 02:38:13 +01:00
import accountApi, { Permission, Role } from "../app/AccountApi";
2023-01-05 02:34:22 +01:00
import ReserveTopicSelect from "./ReserveTopicSelect";
2023-01-10 02:37:13 +01:00
import { AccountContext } from "./App";
2023-02-02 21:19:37 +01:00
import { TopicReservedError, UnauthorizedError } from "../app/errors";
2023-02-11 03:19:44 +01:00
import { ReserveLimitChip } from "./SubscriptionPopup";
2022-02-20 04:26:58 +01:00
const publicBaseUrl = "https://ntfy.sh";
2022-02-20 04:26:58 +01:00
export const subscribeTopic = async (baseUrl, topic) => {
const subscription = await subscriptionManager.add(baseUrl, topic);
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 02:18:46 +01:00
const SubscribeDialog = (props) => {
2022-02-28 22:56:38 +01:00
const [baseUrl, setBaseUrl] = useState("");
2022-02-20 04:26:58 +01:00
const [topic, setTopic] = useState("");
2022-02-25 19:40:03 +01:00
const [showLoginPage, setShowLoginPage] = useState(false);
const fullScreen = useMediaQuery(theme.breakpoints.down("sm"));
2023-01-05 02:34:22 +01:00
const handleSuccess = async () => {
console.log(`[SubscribeDialog] Subscribing to topic ${topic}`);
2023-05-24 09:03:28 +02:00
const actualBaseUrl = baseUrl || config.base_url;
2023-02-11 03:19:44 +01:00
const subscription = await subscribeTopic(actualBaseUrl, topic);
poller.pollInBackground(subscription); // Dangle!
props.onSuccess(subscription);
2022-02-20 04:26:58 +01:00
};
2023-01-05 02:34:22 +01:00
2022-02-25 19:40:03 +01:00
return (
2022-02-28 22:56:38 +01:00
<Dialog open={props.open} onClose={props.onCancel} fullScreen={fullScreen}>
2022-02-25 19:40:03 +01:00
{!showLoginPage && (
<SubscribePage
baseUrl={baseUrl}
2022-02-28 22:56:38 +01:00
setBaseUrl={setBaseUrl}
2022-02-25 19:40:03 +01:00
topic={topic}
setTopic={setTopic}
subscriptions={props.subscriptions}
onCancel={props.onCancel}
onNeedsLogin={() => setShowLoginPage(true)}
onSuccess={handleSuccess}
2022-02-25 19:40:03 +01:00
/>
)}
{showLoginPage && <LoginPage baseUrl={baseUrl} topic={topic} onBack={() => setShowLoginPage(false)} onSuccess={handleSuccess} />}
</Dialog>
);
};
const SubscribePage = (props) => {
2022-04-08 16:44:35 +02:00
const { t } = useTranslation();
2023-01-10 02:37:13 +01:00
const { account } = useContext(AccountContext);
2023-02-02 21:19:37 +01:00
const [error, setError] = useState("");
2023-01-05 02:34:22 +01:00
const [reserveTopicVisible, setReserveTopicVisible] = useState(false);
2022-02-28 22:56:38 +01:00
const [anotherServerVisible, setAnotherServerVisible] = useState(false);
2023-02-12 02:38:13 +01:00
const [everyone, setEveryone] = useState(Permission.DENY_ALL);
2023-01-05 04:47:12 +01:00
const baseUrl = anotherServerVisible ? props.baseUrl : config.base_url;
2023-05-24 09:03:28 +02:00
const { topic } = props;
2022-03-02 22:16:30 +01: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-11 20:32:50 +01: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));
const handleSubscribe = async () => {
2022-03-04 18:10:11 +01:00
const user = await userManager.get(baseUrl); // May be undefined
2022-04-08 16:44:35 +02:00
const username = user ? user.username : t("subscribe_dialog_error_user_anonymous");
2023-01-05 02:34:22 +01:00
// Check read access to topic
2022-12-02 21:37:48 +01:00
const success = await api.topicAuth(baseUrl, topic, user);
if (!success) {
2022-03-04 18:10:11 +01:00
console.log(`[SubscribeDialog] Login to ${topicUrl(baseUrl, topic)} failed for user ${username}`);
if (user) {
2023-02-02 21:19:37 +01:00
setError(
t("subscribe_dialog_error_user_not_authorized", {
2023-05-24 09:03:28 +02:00
username,
2023-02-02 21:19:37 +01:00
})
);
2022-03-04 18:10:11 +01:00
return;
}
2023-05-24 09:03:28 +02:00
props.onNeedsLogin();
return;
2023-05-23 21:13:01 +02:00
}
2023-01-05 02:34:22 +01:00
// Reserve topic (if requested)
2023-01-05 04:47:12 +01:00
if (session.exists() && baseUrl === config.base_url && reserveTopicVisible) {
2023-01-05 02:34:22 +01:00
console.log(`[SubscribeDialog] Reserving topic ${topic} with everyone access ${everyone}`);
try {
2023-01-14 12:43:44 +01:00
await accountApi.upsertReservation(topic, everyone);
2023-01-05 02:34:22 +01:00
} catch (e) {
console.log(`[SubscribeDialog] Error reserving topic`, e);
2023-02-02 21:19:37 +01:00
if (e instanceof UnauthorizedError) {
2023-01-05 02:34:22 +01:00
session.resetAndRedirect(routes.login);
2023-02-02 21:19:37 +01:00
} else if (e instanceof TopicReservedError) {
setError(t("subscribe_dialog_error_topic_already_reserved"));
2023-01-05 02:34:22 +01:00
return;
}
2023-05-23 21:13:01 +02:00
}
}
2023-01-05 02:34:22 +01:00
2022-03-04 18:10:11 +01:00
console.log(`[SubscribeDialog] Successful login to ${topicUrl(baseUrl, topic)} for user ${username}`);
props.onSuccess();
};
2022-02-28 22:56:38 +01:00
const handleUseAnotherChanged = (e) => {
props.setBaseUrl("");
setAnotherServerVisible(e.target.checked);
};
2022-02-28 22:56:38 +01:00
const subscribeButtonEnabled = (() => {
if (anotherServerVisible) {
const isExistingTopicUrl = existingTopicUrls.includes(topicUrl(baseUrl, topic));
return validTopic(topic) && validUrl(baseUrl) && !isExistingTopicUrl;
}
2023-05-24 09:03:28 +02:00
const isExistingTopicUrl = existingTopicUrls.includes(topicUrl(config.base_url, topic));
return validTopic(topic) && !isExistingTopicUrl;
2022-02-28 22:56:38 +01:00
})();
const updateBaseUrl = (ev, newVal) => {
if (validUrl(newVal)) {
2022-10-09 14:50:28 +02:00
props.setBaseUrl(newVal.replace(/\/$/, "")); // strip trailing slash after https?://
} else {
props.setBaseUrl(newVal);
}
};
2022-02-25 19:40:03 +01:00
return (
<>
2022-04-08 16:44:35 +02:00
<DialogTitle>{t("subscribe_dialog_subscribe_title")}</DialogTitle>
2022-02-25 19:40:03 +01:00
<DialogContent>
2022-04-08 16:44:35 +02:00
<DialogContentText>{t("subscribe_dialog_subscribe_description")}</DialogContentText>
2023-01-05 02:34:22 +01: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 03:19:44 +01:00
{showReserveTopicCheckbox && (
2023-01-05 02:34:22 +01:00
<FormGroup>
<FormControlLabel
2022-05-03 20:53:07 +02:00
variant="standard"
2023-01-05 02:34:22 +01:00
control={
<Checkbox
fullWidth
2023-01-10 02:37:13 +01:00
disabled={!reserveTopicEnabled}
2023-01-05 02:34:22 +01:00
checked={reserveTopicVisible}
onChange={(ev) => setReserveTopicVisible(ev.target.checked)}
inputProps={{
2023-02-01 03:39:30 +01:00
"aria-label": t("reserve_dialog_checkbox_label"),
2023-01-05 02:34:22 +01:00
}}
/>
}
2023-02-08 05:18:41 +01:00
label={
<>
{t("reserve_dialog_checkbox_label")}
2023-02-11 03:19:44 +01:00
<ReserveLimitChip />
2023-02-08 05:18:41 +01:00
</>
}
2022-05-03 20:53:07 +02:00
/>
2023-01-05 02:34:22 +01:00
{reserveTopicVisible && <ReserveTopicSelect value={everyone} onChange={setEveryone} />}
</FormGroup>
)}
{!reserveTopicVisible && (
<FormGroup>
<FormControlLabel
control={
<Checkbox
onChange={handleUseAnotherChanged}
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-23 21:13:01 +02:00
)}
2023-01-05 02:34:22 +01:00
/>
)}
</FormGroup>
)}
2022-02-25 19:40:03 +01:00
</DialogContent>
2023-02-02 21:19:37 +01:00
<DialogFooter status={error}>
2022-04-08 16:44:35 +02: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-04 18:10:11 +01:00
</DialogFooter>
2022-02-25 19:40:03 +01:00
</>
);
};
const LoginPage = (props) => {
2022-04-08 16:44:35 +02:00
const { t } = useTranslation();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
2023-02-02 21:19:37 +01:00
const [error, setError] = useState("");
2023-01-05 04:47:12 +01:00
const baseUrl = props.baseUrl ? props.baseUrl : config.base_url;
2023-05-24 09:03:28 +02:00
const { topic } = props;
2023-02-02 21:19:37 +01:00
2022-04-08 16:44:35 +02:00
const handleLogin = async () => {
2022-02-25 19:40:03 +01:00
const user = { baseUrl, username, password };
const success = await api.topicAuth(baseUrl, topic, user);
if (!success) {
2022-04-08 16:44:35 +02:00
console.log(`[SubscribeDialog] Login to ${topicUrl(baseUrl, topic)} failed for user ${username}`);
2023-05-24 09:03:28 +02:00
setError(t("subscribe_dialog_error_user_not_authorized", { username }));
return;
2022-05-03 20:53:07 +02:00
}
2022-04-08 16:44:35 +02:00
console.log(`[SubscribeDialog] Successful login to ${topicUrl(baseUrl, topic)} for user ${username}`);
await userManager.save(user);
props.onSuccess();
2023-05-23 21:13:01 +02:00
};
return (
<>
2022-04-08 16:44:35 +02:00
<DialogTitle>{t("subscribe_dialog_login_title")}</DialogTitle>
2022-02-25 19:40:03 +01:00
<DialogContent>
2022-04-08 16:44:35 +02:00
<DialogContentText>{t("subscribe_dialog_login_description")}</DialogContentText>
2022-02-25 19:40:03 +01:00
<TextField
2023-05-23 21:13:01 +02:00
autoFocus
2022-02-25 19:40:03 +01:00
margin="dense"
id="username"
2022-04-08 16:44:35 +02:00
label={t("subscribe_dialog_login_username_label")}
value={username}
onChange={(ev) => setUsername(ev.target.value)}
2022-02-25 19:40:03 +01:00
type="text"
fullWidth
variant="standard"
2022-05-03 20:53:07 +02:00
inputProps={{
"aria-label": t("subscribe_dialog_login_username_label"),
2023-05-23 21:13:01 +02:00
}}
/>
2022-02-25 19:40:03 +01:00
<TextField
margin="dense"
id="password"
2022-04-08 16:44:35 +02:00
label={t("subscribe_dialog_login_password_label")}
2022-02-25 19:40:03 +01:00
type="password"
value={password}
onChange={(ev) => setPassword(ev.target.value)}
2022-02-25 19:40:03 +01:00
fullWidth
variant="standard"
2022-05-03 20:53:07 +02:00
inputProps={{
"aria-label": t("subscribe_dialog_login_password_label"),
2023-05-23 21:13:01 +02:00
}}
/>
2022-02-25 19:40:03 +01:00
</DialogContent>
2023-02-02 21:19:37 +01:00
<DialogFooter status={error}>
2023-05-13 03:47:41 +02:00
<Button onClick={props.onBack}>{t("common_back")}</Button>
2022-04-08 16:44:35 +02:00
<Button onClick={handleLogin}>{t("subscribe_dialog_login_button_login")}</Button>
</DialogFooter>
2023-05-23 21:13:01 +02:00
</>
);
2022-02-20 04:26:58 +01:00
};
2022-02-25 02:18:46 +01:00
export default SubscribeDialog;