| 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 |
Autocomplete, |
| 11 |
FormControlLabel, |
| 12 |
FormGroup, |
| 13 |
useMediaQuery, |
| 14 |
Switch, |
| 15 |
useTheme, |
| 16 |
} from "@mui/material"; |
| 17 |
import { useTranslation } from "react-i18next"; |
| 18 |
import { useLiveQuery } from "dexie-react-hooks"; |
| 19 |
import api from "../app/Api"; |
| 20 |
import { randomAlphanumericString, topicUrl, validTopic, validUrl } from "../app/utils"; |
| 21 |
import userManager from "../app/UserManager"; |
| 22 |
import subscriptionManager from "../app/SubscriptionManager"; |
| 23 |
import poller from "../app/Poller"; |
| 24 |
import DialogFooter from "./DialogFooter"; |
| 25 |
import session from "../app/Session"; |
| 26 |
import routes from "./routes"; |
| 27 |
import accountApi, { Permission, Role } from "../app/AccountApi"; |
| 28 |
import ReserveTopicSelect from "./ReserveTopicSelect"; |
| 29 |
import AccountContext from "./AccountContext"; |
| 30 |
import { TopicReservedError, UnauthorizedError } from "../app/errors"; |
| 31 |
import { ReserveLimitChip } from "./SubscriptionPopup"; |
| 32 |
import prefs from "../app/Prefs"; |
| 33 |
|
| 34 |
const publicBaseUrl = "https://ntfy.sh"; |
| 35 |
|
| 36 |
export const subscribeTopic = async (baseUrl, topic, opts) => { |
| 37 |
const subscription = await subscriptionManager.upsert(baseUrl, topic, opts); |
| 38 |
if (session.exists()) { |
| 39 |
try { |
| 40 |
await accountApi.addSubscription(baseUrl, topic); |
| 41 |
} catch (e) { |
| 42 |
console.log(`[SubscribeDialog] Subscribing to topic ${topic} failed`, e); |
| 43 |
if (e instanceof UnauthorizedError) { |
| 44 |
await session.resetAndRedirect(routes.login); |
| 45 |
} |
| 46 |
} |
| 47 |
} |
| 48 |
return subscription; |
| 49 |
}; |
| 50 |
|
| 51 |
const SubscribeDialog = (props) => { |
| 52 |
const theme = useTheme(); |
| 53 |
const [baseUrl, setBaseUrl] = useState(""); |
| 54 |
const [topic, setTopic] = useState(""); |
| 55 |
const [showLoginPage, setShowLoginPage] = useState(false); |
| 56 |
const fullScreen = useMediaQuery(theme.breakpoints.down("sm")); |
| 57 |
|
| 58 |
const handleSuccess = async () => { |
| 59 |
console.log(`[SubscribeDialog] Subscribing to topic ${topic}`); |
| 60 |
const actualBaseUrl = baseUrl || config.base_url; |
| 61 |
const subscription = await subscribeTopic(actualBaseUrl, topic, {}); |
| 62 |
poller.pollInBackground(subscription); // Dangle! |
| 63 |
props.onSuccess(subscription); |
| 64 |
}; |
| 65 |
|
| 66 |
return ( |
| 67 |
<Dialog open={props.open} onClose={props.onCancel} fullScreen={fullScreen}> |
| 68 |
{!showLoginPage && ( |
| 69 |
<SubscribePage |
| 70 |
baseUrl={baseUrl} |
| 71 |
setBaseUrl={setBaseUrl} |
| 72 |
topic={topic} |
| 73 |
setTopic={setTopic} |
| 74 |
subscriptions={props.subscriptions} |
| 75 |
onCancel={props.onCancel} |
| 76 |
onNeedsLogin={() => setShowLoginPage(true)} |
| 77 |
onSuccess={handleSuccess} |
| 78 |
/> |
| 79 |
)} |
| 80 |
{showLoginPage && <LoginPage baseUrl={baseUrl} topic={topic} onBack={() => setShowLoginPage(false)} onSuccess={handleSuccess} />} |
| 81 |
</Dialog> |
| 82 |
); |
| 83 |
}; |
| 84 |
|
| 85 |
const SubscribePage = (props) => { |
| 86 |
const { t } = useTranslation(); |
| 87 |
const { account } = useContext(AccountContext); |
| 88 |
const [error, setError] = useState(""); |
| 89 |
const [reserveTopicVisible, setReserveTopicVisible] = useState(false); |
| 90 |
const [anotherServerVisible, setAnotherServerVisible] = useState(false); |
| 91 |
const [everyone, setEveryone] = useState(Permission.DENY_ALL); |
| 92 |
const baseUrl = anotherServerVisible ? props.baseUrl : config.base_url; |
| 93 |
const { topic } = props; |
| 94 |
const existingTopicUrls = props.subscriptions.map((s) => topicUrl(s.baseUrl, s.topic)); |
| 95 |
const existingBaseUrls = Array.from(new Set([publicBaseUrl, ...props.subscriptions.map((s) => s.baseUrl)])).filter( |
| 96 |
(s) => s !== config.base_url, |
| 97 |
); |
| 98 |
const showReserveTopicCheckbox = config.enable_reservations && !anotherServerVisible && (config.enable_payments || account); |
| 99 |
const reserveTopicEnabled = |
| 100 |
session.exists() && (account?.role === Role.ADMIN || (account?.role === Role.USER && (account?.stats.reservations_remaining || 0) > 0)); |
| 101 |
|
| 102 |
const webPushEnabled = useLiveQuery(() => prefs.webPushEnabled()); |
| 103 |
|
| 104 |
const handleSubscribe = async () => { |
| 105 |
const user = await userManager.get(baseUrl); // May be undefined |
| 106 |
const username = user ? user.username : t("subscribe_dialog_error_user_anonymous"); |
| 107 |
|
| 108 |
// Check read access to topic |
| 109 |
const success = await api.topicAuth(baseUrl, topic, user); |
| 110 |
if (!success) { |
| 111 |
console.log(`[SubscribeDialog] Login to ${topicUrl(baseUrl, topic)} failed for user ${username}`); |
| 112 |
if (user) { |
| 113 |
setError( |
| 114 |
t("subscribe_dialog_error_user_not_authorized", { |
| 115 |
username, |
| 116 |
}), |
| 117 |
); |
| 118 |
return; |
| 119 |
} |
| 120 |
props.onNeedsLogin(); |
| 121 |
return; |
| 122 |
} |
| 123 |
|
| 124 |
// Reserve topic (if requested) |
| 125 |
if (session.exists() && baseUrl === config.base_url && reserveTopicVisible) { |
| 126 |
console.log(`[SubscribeDialog] Reserving topic ${topic} with everyone access ${everyone}`); |
| 127 |
try { |
| 128 |
await accountApi.upsertReservation(topic, everyone); |
| 129 |
} catch (e) { |
| 130 |
console.log(`[SubscribeDialog] Error reserving topic`, e); |
| 131 |
if (e instanceof UnauthorizedError) { |
| 132 |
await session.resetAndRedirect(routes.login); |
| 133 |
} else if (e instanceof TopicReservedError) { |
| 134 |
setError(t("subscribe_dialog_error_topic_already_reserved")); |
| 135 |
return; |
| 136 |
} |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
console.log(`[SubscribeDialog] Successful login to ${topicUrl(baseUrl, topic)} for user ${username}`); |
| 141 |
props.onSuccess(); |
| 142 |
}; |
| 143 |
|
| 144 |
const handleUseAnotherChanged = (e) => { |
| 145 |
props.setBaseUrl(""); |
| 146 |
setAnotherServerVisible(e.target.checked); |
| 147 |
}; |
| 148 |
|
| 149 |
const subscribeButtonEnabled = (() => { |
| 150 |
if (anotherServerVisible) { |
| 151 |
const isExistingTopicUrl = existingTopicUrls.includes(topicUrl(baseUrl, topic)); |
| 152 |
return validTopic(topic) && validUrl(baseUrl) && !isExistingTopicUrl; |
| 153 |
} |
| 154 |
const isExistingTopicUrl = existingTopicUrls.includes(topicUrl(config.base_url, topic)); |
| 155 |
return validTopic(topic) && !isExistingTopicUrl; |
| 156 |
})(); |
| 157 |
|
| 158 |
const updateBaseUrl = (ev, newVal) => { |
| 159 |
if (validUrl(newVal)) { |
| 160 |
props.setBaseUrl(newVal.replace(/\/$/, "")); // strip trailing slash after https?:// |
| 161 |
} else { |
| 162 |
props.setBaseUrl(newVal); |
| 163 |
} |
| 164 |
}; |
| 165 |
|
| 166 |
return ( |
| 167 |
<> |
| 168 |
<DialogTitle>{t("subscribe_dialog_subscribe_title")}</DialogTitle> |
| 169 |
<DialogContent> |
| 170 |
<DialogContentText>{t("subscribe_dialog_subscribe_description")}</DialogContentText> |
| 171 |
<div style={{ display: "flex", paddingBottom: "8px" }} role="row"> |
| 172 |
<TextField |
| 173 |
autoFocus |
| 174 |
margin="dense" |
| 175 |
id="topic" |
| 176 |
placeholder={t("subscribe_dialog_subscribe_topic_placeholder")} |
| 177 |
value={props.topic} |
| 178 |
onChange={(ev) => props.setTopic(ev.target.value)} |
| 179 |
type="text" |
| 180 |
fullWidth |
| 181 |
variant="standard" |
| 182 |
slotProps={{ |
| 183 |
htmlInput: { |
| 184 |
maxLength: 64, |
| 185 |
"aria-label": t("subscribe_dialog_subscribe_topic_placeholder"), |
| 186 |
}, |
| 187 |
}} |
| 188 |
/> |
| 189 |
<Button |
| 190 |
onClick={() => { |
| 191 |
props.setTopic(randomAlphanumericString(16)); |
| 192 |
}} |
| 193 |
style={{ flexShrink: "0", marginTop: "0.5em" }} |
| 194 |
> |
| 195 |
{t("subscribe_dialog_subscribe_button_generate_topic_name")} |
| 196 |
</Button> |
| 197 |
</div> |
| 198 |
{showReserveTopicCheckbox && ( |
| 199 |
<FormGroup> |
| 200 |
<FormControlLabel |
| 201 |
variant="standard" |
| 202 |
control={ |
| 203 |
<Switch |
| 204 |
disabled={!reserveTopicEnabled} |
| 205 |
checked={reserveTopicVisible} |
| 206 |
onChange={(ev) => setReserveTopicVisible(ev.target.checked)} |
| 207 |
slotProps={{ |
| 208 |
input: { |
| 209 |
"aria-label": t("reserve_dialog_checkbox_label"), |
| 210 |
}, |
| 211 |
}} |
| 212 |
/> |
| 213 |
} |
| 214 |
label={ |
| 215 |
<> |
| 216 |
{t("reserve_dialog_checkbox_label")} |
| 217 |
<ReserveLimitChip /> |
| 218 |
</> |
| 219 |
} |
| 220 |
/> |
| 221 |
{reserveTopicVisible && <ReserveTopicSelect value={everyone} onChange={setEveryone} />} |
| 222 |
</FormGroup> |
| 223 |
)} |
| 224 |
{!reserveTopicVisible && ( |
| 225 |
<FormGroup> |
| 226 |
<FormControlLabel |
| 227 |
control={ |
| 228 |
<Switch |
| 229 |
onChange={handleUseAnotherChanged} |
| 230 |
checked={anotherServerVisible} |
| 231 |
slotProps={{ |
| 232 |
input: { |
| 233 |
"aria-label": t("subscribe_dialog_subscribe_use_another_label"), |
| 234 |
}, |
| 235 |
}} |
| 236 |
/> |
| 237 |
} |
| 238 |
label={t("subscribe_dialog_subscribe_use_another_label")} |
| 239 |
/> |
| 240 |
{anotherServerVisible && ( |
| 241 |
<Autocomplete |
| 242 |
freeSolo |
| 243 |
options={existingBaseUrls} |
| 244 |
inputValue={props.baseUrl} |
| 245 |
onInputChange={updateBaseUrl} |
| 246 |
renderInput={(params) => ( |
| 247 |
<> |
| 248 |
<TextField |
| 249 |
{...params} |
| 250 |
placeholder={config.base_url} |
| 251 |
variant="standard" |
| 252 |
aria-label={t("subscribe_dialog_subscribe_base_url_label")} |
| 253 |
/> |
| 254 |
{webPushEnabled && ( |
| 255 |
<div style={{ width: "100%", color: "#aaa", fontSize: "0.75rem", marginTop: "0.5rem" }}> |
| 256 |
{t("subscribe_dialog_subscribe_use_another_background_info")} |
| 257 |
</div> |
| 258 |
)} |
| 259 |
</> |
| 260 |
)} |
| 261 |
/> |
| 262 |
)} |
| 263 |
</FormGroup> |
| 264 |
)} |
| 265 |
</DialogContent> |
| 266 |
<DialogFooter status={error}> |
| 267 |
<Button onClick={props.onCancel}>{t("subscribe_dialog_subscribe_button_cancel")}</Button> |
| 268 |
<Button onClick={handleSubscribe} disabled={!subscribeButtonEnabled}> |
| 269 |
{t("subscribe_dialog_subscribe_button_subscribe")} |
| 270 |
</Button> |
| 271 |
</DialogFooter> |
| 272 |
</> |
| 273 |
); |
| 274 |
}; |
| 275 |
|
| 276 |
const LoginPage = (props) => { |
| 277 |
const { t } = useTranslation(); |
| 278 |
const [username, setUsername] = useState(""); |
| 279 |
const [password, setPassword] = useState(""); |
| 280 |
const [error, setError] = useState(""); |
| 281 |
const baseUrl = props.baseUrl ? props.baseUrl : config.base_url; |
| 282 |
const { topic } = props; |
| 283 |
|
| 284 |
const handleLogin = async () => { |
| 285 |
const user = { baseUrl, username, password }; |
| 286 |
const success = await api.topicAuth(baseUrl, topic, user); |
| 287 |
if (!success) { |
| 288 |
console.log(`[SubscribeDialog] Login to ${topicUrl(baseUrl, topic)} failed for user ${username}`); |
| 289 |
setError(t("subscribe_dialog_error_user_not_authorized", { username })); |
| 290 |
return; |
| 291 |
} |
| 292 |
console.log(`[SubscribeDialog] Successful login to ${topicUrl(baseUrl, topic)} for user ${username}`); |
| 293 |
await userManager.save(user); |
| 294 |
props.onSuccess(); |
| 295 |
}; |
| 296 |
|
| 297 |
return ( |
| 298 |
<> |
| 299 |
<DialogTitle>{t("subscribe_dialog_login_title")}</DialogTitle> |
| 300 |
<DialogContent> |
| 301 |
<DialogContentText>{t("subscribe_dialog_login_description")}</DialogContentText> |
| 302 |
<TextField |
| 303 |
autoFocus |
| 304 |
margin="dense" |
| 305 |
id="username" |
| 306 |
label={t("subscribe_dialog_login_username_label")} |
| 307 |
value={username} |
| 308 |
onChange={(ev) => setUsername(ev.target.value)} |
| 309 |
type="text" |
| 310 |
fullWidth |
| 311 |
variant="standard" |
| 312 |
slotProps={{ |
| 313 |
htmlInput: { |
| 314 |
"aria-label": t("subscribe_dialog_login_username_label"), |
| 315 |
}, |
| 316 |
}} |
| 317 |
/> |
| 318 |
<TextField |
| 319 |
margin="dense" |
| 320 |
id="password" |
| 321 |
label={t("subscribe_dialog_login_password_label")} |
| 322 |
type="password" |
| 323 |
value={password} |
| 324 |
onChange={(ev) => setPassword(ev.target.value)} |
| 325 |
fullWidth |
| 326 |
variant="standard" |
| 327 |
slotProps={{ |
| 328 |
htmlInput: { |
| 329 |
"aria-label": t("subscribe_dialog_login_password_label"), |
| 330 |
}, |
| 331 |
}} |
| 332 |
/> |
| 333 |
</DialogContent> |
| 334 |
<DialogFooter status={error}> |
| 335 |
<Button onClick={props.onBack}>{t("common_back")}</Button> |
| 336 |
<Button onClick={handleLogin}>{t("subscribe_dialog_login_button_login")}</Button> |
| 337 |
</DialogFooter> |
| 338 |
</> |
| 339 |
); |
| 340 |
}; |
| 341 |
|
| 342 |
export default SubscribeDialog; |