Switch everything to Dexie.js

This commit is contained in:
Philipp Heckel 2022-03-02 16:16:30 -05:00
parent 39f4613719
commit 349872bdb3
16 changed files with 243 additions and 316 deletions

View file

@ -10,11 +10,12 @@ class ConnectionManager {
return; return;
} }
console.log(`[ConnectionManager] Refreshing connections`); console.log(`[ConnectionManager] Refreshing connections`);
const subscriptionIds = subscriptions.ids(); const subscriptionIds = subscriptions.map(s => s.id);
const deletedIds = Array.from(this.connections.keys()).filter(id => !subscriptionIds.includes(id)); const deletedIds = Array.from(this.connections.keys()).filter(id => !subscriptionIds.includes(id));
// Create and add new connections // Create and add new connections
subscriptions.forEach((id, subscription) => { subscriptions.forEach(subscription => {
const id = subscription.id;
const added = !this.connections.get(id) const added = !this.connections.get(id)
if (added) { if (added) {
const baseUrl = subscription.baseUrl; const baseUrl = subscription.baseUrl;

View file

@ -1,5 +1,5 @@
import {formatMessage, formatTitleWithFallback, topicShortUrl} from "./utils"; import {formatMessage, formatTitleWithFallback, topicShortUrl} from "./utils";
import repository from "./Repository"; import prefs from "./Prefs";
class NotificationManager { class NotificationManager {
async notify(subscription, notification, onClickFallback) { async notify(subscription, notification, onClickFallback) {
@ -7,8 +7,11 @@ class NotificationManager {
if (!shouldNotify) { if (!shouldNotify) {
return; return;
} }
const shortUrl = topicShortUrl(subscription.baseUrl, subscription.topic);
const message = formatMessage(notification); const message = formatMessage(notification);
const title = formatTitleWithFallback(notification, topicShortUrl(subscription.baseUrl, subscription.topic)); const title = formatTitleWithFallback(notification, shortUrl);
console.log(`[NotificationManager, ${shortUrl}] Displaying notification ${notification.id}: ${message}`);
const n = new Notification(title, { const n = new Notification(title, {
body: message, body: message,
icon: '/static/img/favicon.png' icon: '/static/img/favicon.png'
@ -35,7 +38,7 @@ class NotificationManager {
async shouldNotify(subscription, notification) { async shouldNotify(subscription, notification) {
const priority = (notification.priority) ? notification.priority : 3; const priority = (notification.priority) ? notification.priority : 3;
const minPriority = await repository.getMinPriority(); const minPriority = await prefs.minPriority();
if (priority < minPriority) { if (priority < minPriority) {
return false; return false;
} }

49
web/src/app/Poller.js Normal file
View file

@ -0,0 +1,49 @@
import db from "./db";
import api from "./Api";
const delayMillis = 3000; // 3 seconds
const intervalMillis = 300000; // 5 minutes
class Poller {
constructor() {
this.timer = null;
}
startWorker() {
if (this.timer !== null) {
return;
}
this.timer = setInterval(() => this.pollAll(), intervalMillis);
setTimeout(() => this.pollAll(), delayMillis);
}
async pollAll() {
console.log(`[Poller] Polling all subscriptions`);
const subscriptions = await db.subscriptions.toArray();
for (const s of subscriptions) {
try {
await this.poll(s);
} catch (e) {
console.log(`[Poller] Error polling ${s.id}`, e);
}
}
}
async poll(subscription) {
console.log(`[Poller] Polling ${subscription.id}`);
const since = subscription.last;
const notifications = await api.poll(subscription.baseUrl, subscription.topic, since);
if (!notifications || notifications.length === 0) {
console.log(`[Poller] No new notifications found for ${subscription.id}`);
return;
}
const notificationsWithSubscriptionId = notifications
.map(notification => ({ ...notification, subscriptionId: subscription.id }));
await db.notifications.bulkPut(notificationsWithSubscriptionId); // FIXME
await db.subscriptions.update(subscription.id, {last: notifications.at(-1).id}); // FIXME
};
}
const poller = new Poller();
export default poller;

33
web/src/app/Prefs.js Normal file
View file

@ -0,0 +1,33 @@
import db from "./db";
class Prefs {
async setSelectedSubscriptionId(selectedSubscriptionId) {
db.prefs.put({key: 'selectedSubscriptionId', value: selectedSubscriptionId});
}
async selectedSubscriptionId() {
const selectedSubscriptionId = await db.prefs.get('selectedSubscriptionId');
return (selectedSubscriptionId) ? selectedSubscriptionId.value : "";
}
async setMinPriority(minPriority) {
db.prefs.put({key: 'minPriority', value: minPriority.toString()});
}
async minPriority() {
const minPriority = await db.prefs.get('minPriority');
return (minPriority) ? Number(minPriority.value) : 1;
}
async setDeleteAfter(deleteAfter) {
db.prefs.put({key:'deleteAfter', value: deleteAfter.toString()});
}
async deleteAfter() {
const deleteAfter = await db.prefs.get('deleteAfter');
return (deleteAfter) ? Number(deleteAfter.value) : 604800; // Default is one week
}
}
const prefs = new Prefs();
export default prefs;

39
web/src/app/Pruner.js Normal file
View file

@ -0,0 +1,39 @@
import db from "./db";
import prefs from "./Prefs";
const delayMillis = 15000; // 15 seconds
const intervalMillis = 1800000; // 30 minutes
class Pruner {
constructor() {
this.timer = null;
}
startWorker() {
if (this.timer !== null) {
return;
}
this.timer = setInterval(() => this.prune(), intervalMillis);
setTimeout(() => this.prune(), delayMillis);
}
async prune() {
const deleteAfterSeconds = await prefs.deleteAfter();
const pruneThresholdTimestamp = Math.round(Date.now()/1000) - deleteAfterSeconds;
if (deleteAfterSeconds === 0) {
console.log(`[Pruner] Pruning is disabled. Skipping.`);
return;
}
console.log(`[Pruner] Pruning notifications older than ${deleteAfterSeconds}s (timestamp ${pruneThresholdTimestamp})`);
try {
await db.notifications
.where("time").below(pruneThresholdTimestamp)
.delete();
} catch (e) {
console.log(`[Pruner] Error pruning old subscriptions`, e);
}
}
}
const pruner = new Pruner();
export default pruner;

View file

@ -1,83 +0,0 @@
import Subscription from "./Subscription";
import Subscriptions from "./Subscriptions";
import db from "./db";
class Repository {
loadSubscriptions() {
console.log(`[Repository] Loading subscriptions from localStorage`);
const subscriptions = new Subscriptions();
subscriptions.loaded = true;
const serialized = localStorage.getItem('subscriptions');
if (serialized === null) {
return subscriptions;
}
try {
JSON.parse(serialized).forEach(s => {
const subscription = new Subscription(s.baseUrl, s.topic);
subscription.addNotifications(s.notifications);
subscription.last = s.last; // Explicitly set, in case old notifications have been deleted
subscriptions.add(subscription);
});
console.log(`[Repository] Loaded ${subscriptions.size()} subscription(s) from localStorage`);
return subscriptions;
} catch (e) {
console.log(`[Repository] Unable to deserialize subscriptions: ${e.message}`);
return subscriptions;
}
}
saveSubscriptions(subscriptions) {
if (!subscriptions.loaded) {
return; // Avoid saving invalid state, triggered by initial useEffect hook
}
console.log(`[Repository] Saving ${subscriptions.size()} subscription(s) to localStorage`);
const serialized = JSON.stringify(subscriptions.map( (id, subscription) => {
return {
baseUrl: subscription.baseUrl,
topic: subscription.topic,
last: subscription.last
}
}));
localStorage.setItem('subscriptions', serialized);
}
async setSelectedSubscriptionId(selectedSubscriptionId) {
console.log(`[Repository] Saving selected subscription ${selectedSubscriptionId}`);
db.prefs.put({key: 'selectedSubscriptionId', value: selectedSubscriptionId});
}
async getSelectedSubscriptionId() {
console.log(`[Repository] Loading selected subscription ID`);
const selectedSubscriptionId = await db.prefs.get('selectedSubscriptionId');
return (selectedSubscriptionId) ? selectedSubscriptionId.value : "";
}
async setMinPriority(minPriority) {
db.prefs.put({key: 'minPriority', value: minPriority.toString()});
}
async getMinPriority() {
const minPriority = await db.prefs.get('minPriority');
return (minPriority) ? Number(minPriority.value) : 1;
}
minPriority() {
return db.prefs.get('minPriority');
}
async setDeleteAfter(deleteAfter) {
db.prefs.put({key:'deleteAfter', value: deleteAfter.toString()});
}
async getDeleteAfter() {
const deleteAfter = await db.prefs.get('deleteAfter');
return (deleteAfter) ? Number(deleteAfter.value) : 604800; // Default is one week
}
deleteAfter() {
return db.prefs.get('deleteAfter');
}
}
const repository = new Repository();
export default repository;

View file

@ -1,33 +0,0 @@
import {topicShortUrl, topicUrl} from './utils';
class Subscription {
constructor(baseUrl, topic) {
this.id = topicUrl(baseUrl, topic);
this.baseUrl = baseUrl;
this.topic = topic;
this.last = null; // Last message ID
}
addNotification(notification) {
if (!notification.event || notification.event !== 'message') {
return false;
}
this.last = notification.id;
return true;
}
addNotifications(notifications) {
notifications.forEach(n => this.addNotification(n));
return this;
}
url() {
return topicUrl(this.baseUrl, this.topic);
}
shortUrl() {
return topicShortUrl(this.baseUrl, this.topic);
}
}
export default Subscription;

View file

@ -1,56 +0,0 @@
class Subscriptions {
constructor() {
this.loaded = false; // FIXME I hate this
this.subscriptions = new Map();
}
add(subscription) {
this.subscriptions.set(subscription.id, subscription);
return this;
}
get(subscriptionId) {
const subscription = this.subscriptions.get(subscriptionId);
return (subscription) ? subscription : null;
}
update(subscription) {
return this.add(subscription);
}
remove(subscriptionId) {
this.subscriptions.delete(subscriptionId);
return this;
}
forEach(cb) {
this.subscriptions.forEach((value, key) => cb(key, value));
}
map(cb) {
return Array.from(this.subscriptions.values())
.map(subscription => cb(subscription.id, subscription));
}
ids() {
return Array.from(this.subscriptions.keys());
}
firstOrNull() {
const first = this.subscriptions.values().next().value;
return (first) ? first : null;
}
size() {
return this.subscriptions.size;
}
clone() {
const c = new Subscriptions();
c.loaded = this.loaded;
c.subscriptions = new Map(this.subscriptions);
return c;
}
}
export default Subscriptions;

View file

@ -9,8 +9,8 @@ import Dexie from 'dexie';
const db = new Dexie('ntfy'); const db = new Dexie('ntfy');
db.version(1).stores({ db.version(1).stores({
subscriptions: '&id', subscriptions: '&id,baseUrl',
notifications: '&id,subscriptionId', notifications: '&id,subscriptionId,time',
users: '&baseUrl,username', users: '&baseUrl,username',
prefs: '&key' prefs: '&key'
}); });

View file

@ -7,10 +7,11 @@ import Typography from "@mui/material/Typography";
import IconSubscribeSettings from "./IconSubscribeSettings"; import IconSubscribeSettings from "./IconSubscribeSettings";
import * as React from "react"; import * as React from "react";
import Box from "@mui/material/Box"; import Box from "@mui/material/Box";
import {topicShortUrl} from "../app/utils";
const ActionBar = (props) => { const ActionBar = (props) => {
const title = (props.selectedSubscription !== null) const title = (props.selectedSubscription)
? props.selectedSubscription.shortUrl() ? topicShortUrl(props.selectedSubscription.baseUrl, props.selectedSubscription.topic)
: "ntfy"; : "ntfy";
return ( return (
<AppBar position="fixed" sx={{ <AppBar position="fixed" sx={{
@ -37,7 +38,6 @@ const ActionBar = (props) => {
</Typography> </Typography>
{props.selectedSubscription !== null && <IconSubscribeSettings {props.selectedSubscription !== null && <IconSubscribeSettings
subscription={props.selectedSubscription} subscription={props.selectedSubscription}
onClearAll={props.onClearAll}
onUnsubscribe={props.onUnsubscribe} onUnsubscribe={props.onUnsubscribe}
/>} />}
</Toolbar> </Toolbar>
@ -45,17 +45,4 @@ const ActionBar = (props) => {
); );
}; };
/*
To add a top left corner logo box:
<Typography variant="h5" noWrap component="div" sx={{
display: { xs: 'none', sm: 'block' },
width: { sm: `${Navigation.width}px` }
}}>
ntfy
</Typography>
To make the size of the top bar dynamic based on the drawer:
width: { sm: `calc(100% - ${Navigation.width}px)` }
*/
export default ActionBar; export default ActionBar;

View file

@ -6,10 +6,8 @@ import CssBaseline from '@mui/material/CssBaseline';
import Toolbar from '@mui/material/Toolbar'; import Toolbar from '@mui/material/Toolbar';
import Notifications from "./Notifications"; import Notifications from "./Notifications";
import theme from "./theme"; import theme from "./theme";
import api from "../app/Api"; import prefs from "../app/Prefs";
import repository from "../app/Repository";
import connectionManager from "../app/ConnectionManager"; import connectionManager from "../app/ConnectionManager";
import Subscriptions from "../app/Subscriptions";
import Navigation from "./Navigation"; import Navigation from "./Navigation";
import ActionBar from "./ActionBar"; import ActionBar from "./ActionBar";
import notificationManager from "../app/NotificationManager"; import notificationManager from "../app/NotificationManager";
@ -17,52 +15,52 @@ import NoTopics from "./NoTopics";
import Preferences from "./Preferences"; import Preferences from "./Preferences";
import db from "../app/db"; import db from "../app/db";
import {useLiveQuery} from "dexie-react-hooks"; import {useLiveQuery} from "dexie-react-hooks";
import {topicUrl} from "../app/utils"; import poller from "../app/Poller";
import pruner from "../app/Pruner";
// TODO subscribe dialog: // TODO subscribe dialog:
// - check/use existing user // - check/use existing user
// - add baseUrl // - add baseUrl
// TODO embed into ntfy server // TODO embed into ntfy server
// TODO make default server functional // TODO make default server functional
// TODO indexeddb for notifications + subscriptions
// TODO business logic with callbacks // TODO business logic with callbacks
// TODO connection indicator in subscription list // TODO connection indicator in subscription list
// TODO connectionmanager should react on users changes
// TODO attachments
const App = () => { const App = () => {
console.log(`[App] Rendering main view`); console.log(`[App] Rendering main view`);
const [mobileDrawerOpen, setMobileDrawerOpen] = useState(false); const [mobileDrawerOpen, setMobileDrawerOpen] = useState(false);
const [prefsOpen, setPrefsOpen] = useState(false); const [prefsOpen, setPrefsOpen] = useState(false);
const [subscriptions, setSubscriptions] = useState(new Subscriptions());
const [selectedSubscription, setSelectedSubscription] = useState(null); const [selectedSubscription, setSelectedSubscription] = useState(null);
const [notificationsGranted, setNotificationsGranted] = useState(notificationManager.granted()); const [notificationsGranted, setNotificationsGranted] = useState(notificationManager.granted());
const subscriptions = useLiveQuery(() => db.subscriptions.toArray());
const users = useLiveQuery(() => db.users.toArray()); const users = useLiveQuery(() => db.users.toArray());
const handleSubscriptionClick = (subscriptionId) => { const handleSubscriptionClick = async (subscriptionId) => {
setSelectedSubscription(subscriptions.get(subscriptionId)); const subscription = await db.subscriptions.get(subscriptionId); // FIXME
setSelectedSubscription(subscription);
setPrefsOpen(false); setPrefsOpen(false);
} }
const handleSubscribeSubmit = (subscription) => { const handleSubscribeSubmit = async (subscription) => {
console.log(`[App] New subscription: ${subscription.id}`); console.log(`[App] New subscription: ${subscription.id}`, subscription);
setSubscriptions(prev => prev.add(subscription).clone()); await db.subscriptions.put(subscription); // FIXME
setSelectedSubscription(subscription); setSelectedSubscription(subscription);
poll(subscription);
handleRequestPermission(); handleRequestPermission();
try {
await poller.poll(subscription);
} catch (e) {
console.error(`[App] Error polling newly added subscription ${subscription.id}`, e);
}
}; };
const handleDeleteNotification = (subscriptionId, notificationId) => { const handleUnsubscribe = async (subscriptionId) => {
console.log(`[App] Deleting notification ${notificationId} from ${subscriptionId}`);
db.notifications.delete(notificationId); // FIXME
};
const handleDeleteAllNotifications = (subscriptionId) => {
console.log(`[App] Deleting all notifications from ${subscriptionId}`);
db.notifications.where({subscriptionId}).delete(); // FIXME
};
const handleUnsubscribe = (subscriptionId) => {
console.log(`[App] Unsubscribing from ${subscriptionId}`); console.log(`[App] Unsubscribing from ${subscriptionId}`);
setSubscriptions(prev => { await db.subscriptions.delete(subscriptionId); // FIXME
const newSubscriptions = prev.remove(subscriptionId).clone(); await db.notifications
setSelectedSubscription(newSubscriptions.firstOrNull()); .where({subscriptionId: subscriptionId})
return newSubscriptions; .delete(); // FIXME
}); const newSelected = await db.subscriptions.toCollection().first(); // FIXME May be undefined
setSelectedSubscription(newSelected);
}; };
const handleRequestPermission = () => { const handleRequestPermission = () => {
notificationManager.maybeRequestPermission((granted) => { notificationManager.maybeRequestPermission((granted) => {
@ -73,61 +71,41 @@ const App = () => {
setPrefsOpen(true); setPrefsOpen(true);
setSelectedSubscription(null); setSelectedSubscription(null);
}; };
const poll = (subscription) => {
const since = subscription.last;
api.poll(subscription.baseUrl, subscription.topic, since)
.then(notifications => {
setSubscriptions(prev => {
subscription.addNotifications(notifications);
const subscriptionId = topicUrl(subscription.baseUrl, subscription.topic);
const notificationsWithSubscriptionId = notifications
.map(notification => ({ ...notification, subscriptionId }));
db.notifications.bulkPut(notificationsWithSubscriptionId); // FIXME
return prev.update(subscription).clone();
});
});
};
// Define hooks: Note that the order of the hooks is important. The "loading" hooks // Define hooks: Note that the order of the hooks is important. The "loading" hooks
// must be before the "saving" hooks. // must be before the "saving" hooks.
useEffect(() => { useEffect(() => {
poller.startWorker();
pruner.startWorker();
const load = async () => { const load = async () => {
// Load subscriptions const subs = await db.subscriptions.toArray(); // Cannot be 'subscriptions'
const subscriptions = repository.loadSubscriptions(); const selectedSubscriptionId = await prefs.selectedSubscriptionId();
const selectedSubscriptionId = await repository.getSelectedSubscriptionId();
setSubscriptions(subscriptions);
// Set selected subscription // Set selected subscription
const maybeSelectedSubscription = subscriptions.get(selectedSubscriptionId); const maybeSelectedSubscription = subs?.filter(s => s.id = selectedSubscriptionId);
if (maybeSelectedSubscription) { if (maybeSelectedSubscription.length > 0) {
setSelectedSubscription(maybeSelectedSubscription); setSelectedSubscription(maybeSelectedSubscription[0]);
} }
// Poll all subscriptions
subscriptions.forEach((subscriptionId, subscription) => {
poll(subscription);
});
}; };
load(); setTimeout(() => load(), 5000);
}, [/* initial render */]); }, [/* initial render */]);
useEffect(() => { useEffect(() => {
const notificationClickFallback = (subscription) => setSelectedSubscription(subscription); const notificationClickFallback = (subscription) => setSelectedSubscription(subscription);
const handleNotification = (subscriptionId, notification) => { const handleNotification = async (subscriptionId, notification) => {
db.notifications.put({ ...notification, subscriptionId }); // FIXME try {
setSubscriptions(prev => { const subscription = await db.subscriptions.get(subscriptionId); // FIXME
const subscription = prev.get(subscriptionId); await db.notifications.add({ ...notification, subscriptionId }); // FIXME, will throw if exists!
if (subscription.addNotification(notification)) { await db.subscriptions.update(subscriptionId, { last: notification.id });
notificationManager.notify(subscription, notification, notificationClickFallback) await notificationManager.notify(subscription, notification, notificationClickFallback)
} catch (e) {
console.error(`[App] Error handling notification`, e);
} }
return prev.update(subscription).clone();
});
}; };
connectionManager.refresh(subscriptions, users, handleNotification); connectionManager.refresh(subscriptions, users, handleNotification);
}, [subscriptions, users]); }, [subscriptions, users]);
useEffect(() => repository.saveSubscriptions(subscriptions), [subscriptions]);
useEffect(() => { useEffect(() => {
const subscriptionId = (selectedSubscription) ? selectedSubscription.id : ""; const subscriptionId = (selectedSubscription) ? selectedSubscription.id : "";
repository.setSelectedSubscriptionId(subscriptionId) prefs.setSelectedSubscriptionId(subscriptionId)
}, [selectedSubscription]); }, [selectedSubscription]);
return ( return (
@ -137,7 +115,6 @@ const App = () => {
<CssBaseline/> <CssBaseline/>
<ActionBar <ActionBar
selectedSubscription={selectedSubscription} selectedSubscription={selectedSubscription}
onClearAll={handleDeleteAllNotifications}
onUnsubscribe={handleUnsubscribe} onUnsubscribe={handleUnsubscribe}
onMobileDrawerToggle={() => setMobileDrawerOpen(!mobileDrawerOpen)} onMobileDrawerToggle={() => setMobileDrawerOpen(!mobileDrawerOpen)}
/> />
@ -155,6 +132,20 @@ const App = () => {
onRequestPermissionClick={handleRequestPermission} onRequestPermissionClick={handleRequestPermission}
/> />
</Box> </Box>
<Main>
<Toolbar/>
<Content
subscription={selectedSubscription}
prefsOpen={prefsOpen}
/>
</Main>
</Box>
</ThemeProvider>
);
}
const Main = (props) => {
return (
<Box <Box
component="main" component="main"
sx={{ sx={{
@ -168,32 +159,19 @@ const App = () => {
backgroundColor: (theme) => theme.palette.mode === 'light' ? theme.palette.grey[100] : theme.palette.grey[900] backgroundColor: (theme) => theme.palette.mode === 'light' ? theme.palette.grey[100] : theme.palette.grey[900]
}} }}
> >
<Toolbar/> {props.children}
<MainContent
subscription={selectedSubscription}
prefsOpen={prefsOpen}
onDeleteNotification={handleDeleteNotification}
/>
</Box> </Box>
</Box>
</ThemeProvider>
); );
} };
const MainContent = (props) => { const Content = (props) => {
if (props.prefsOpen) { if (props.prefsOpen) {
return <Preferences/>; return <Preferences/>;
} }
if (props.subscription !== null) { if (props.subscription) {
return ( return <Notifications subscription={props.subscription}/>;
<Notifications
subscription={props.subscription}
onDeleteNotification={props.onDeleteNotification}
/>
);
} else {
return <NoTopics/>;
} }
return <NoTopics/>;
}; };
export default App; export default App;

View file

@ -9,6 +9,7 @@ import MenuList from '@mui/material/MenuList';
import IconButton from "@mui/material/IconButton"; import IconButton from "@mui/material/IconButton";
import MoreVertIcon from "@mui/icons-material/MoreVert"; import MoreVertIcon from "@mui/icons-material/MoreVert";
import api from "../app/Api"; import api from "../app/Api";
import db from "../app/db";
// Originally from https://mui.com/components/menus/#MenuListComposition.js // Originally from https://mui.com/components/menus/#MenuListComposition.js
const IconSubscribeSettings = (props) => { const IconSubscribeSettings = (props) => {
@ -28,7 +29,10 @@ const IconSubscribeSettings = (props) => {
const handleClearAll = (event) => { const handleClearAll = (event) => {
handleClose(event); handleClose(event);
props.onClearAll(props.subscription.id); console.log(`[IconSubscribeSettings] Deleting all notifications from ${props.subscription.id}`);
db.notifications
.where({subscriptionId: props.subscription.id})
.delete(); // FIXME
}; };
const handleUnsubscribe = (event) => { const handleUnsubscribe = (event) => {
@ -59,7 +63,6 @@ const IconSubscribeSettings = (props) => {
if (prevOpen.current === true && open === false) { if (prevOpen.current === true && open === false) {
anchorRef.current.focus(); anchorRef.current.focus();
} }
prevOpen.current = open; prevOpen.current = open;
}, [open]); }, [open]);
@ -71,9 +74,6 @@ const IconSubscribeSettings = (props) => {
edge="end" edge="end"
ref={anchorRef} ref={anchorRef}
id="composition-button" id="composition-button"
aria-controls={open ? 'composition-menu' : undefined}
aria-expanded={open ? 'true' : undefined}
aria-haspopup="true"
onClick={handleToggle} onClick={handleToggle}
> >
<MoreVertIcon/> <MoreVertIcon/>
@ -99,7 +99,6 @@ const IconSubscribeSettings = (props) => {
<MenuList <MenuList
autoFocusItem={open} autoFocusItem={open}
id="composition-menu" id="composition-menu"
aria-labelledby="composition-button"
onKeyDown={handleListKeyDown} onKeyDown={handleListKeyDown}
> >
<MenuItem onClick={handleSendTestMessage}>Send test notification</MenuItem> <MenuItem onClick={handleSendTestMessage}>Send test notification</MenuItem>

View file

@ -14,6 +14,7 @@ import SubscribeDialog from "./SubscribeDialog";
import {Alert, AlertTitle, ListSubheader} from "@mui/material"; import {Alert, AlertTitle, ListSubheader} from "@mui/material";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import {topicShortUrl} from "../app/utils";
const navWidth = 240; const navWidth = 240;
@ -61,8 +62,8 @@ const NavList = (props) => {
handleSubscribeReset(); handleSubscribeReset();
props.onSubscribeSubmit(subscription); props.onSubscribeSubmit(subscription);
} }
const showSubscriptionsList = props.subscriptions.size() > 0; const showSubscriptionsList = props.subscriptions?.length > 0;
const showGrantPermissionsBox = props.subscriptions.size() > 0 && !props.notificationsGranted; const showGrantPermissionsBox = props.subscriptions?.length > 0 && !props.notificationsGranted;
return ( return (
<> <>
<Toolbar sx={{ <Toolbar sx={{
@ -115,14 +116,14 @@ const NavList = (props) => {
const SubscriptionList = (props) => { const SubscriptionList = (props) => {
return ( return (
<> <>
{props.subscriptions.map((id, subscription) => {props.subscriptions.map(subscription =>
<ListItemButton <ListItemButton
key={id} key={subscription.id}
onClick={() => props.onSubscriptionClick(id)} onClick={() => props.onSubscriptionClick(subscription.id)}
selected={props.selectedSubscription && !props.prefsOpen && props.selectedSubscription.id === id} selected={props.selectedSubscription && !props.prefsOpen && props.selectedSubscription.id === subscription.id}
> >
<ListItemIcon><ChatBubbleOutlineIcon /></ListItemIcon> <ListItemIcon><ChatBubbleOutlineIcon /></ListItemIcon>
<ListItemText primary={subscription.shortUrl()}/> <ListItemText primary={topicShortUrl(subscription.baseUrl, subscription.topic)}/>
</ListItemButton> </ListItemButton>
)} )}
</> </>

View file

@ -3,7 +3,7 @@ import {CardContent, Link, Stack} from "@mui/material";
import Card from "@mui/material/Card"; import Card from "@mui/material/Card";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import * as React from "react"; import * as React from "react";
import {formatMessage, formatTitle, topicUrl, unmatchedTags} from "../app/utils"; import {formatMessage, formatTitle, topicShortUrl, unmatchedTags} from "../app/utils";
import IconButton from "@mui/material/IconButton"; import IconButton from "@mui/material/IconButton";
import CloseIcon from '@mui/icons-material/Close'; import CloseIcon from '@mui/icons-material/Close';
import {Paragraph, VerticallyCenteredContainer} from "./styles"; import {Paragraph, VerticallyCenteredContainer} from "./styles";
@ -12,16 +12,16 @@ import db from "../app/db";
const Notifications = (props) => { const Notifications = (props) => {
const subscription = props.subscription; const subscription = props.subscription;
const subscriptionId = topicUrl(subscription.baseUrl, subscription.topic);
const notifications = useLiveQuery(() => { const notifications = useLiveQuery(() => {
return db.notifications return db.notifications
.where({ subscriptionId: subscriptionId }) .where({ subscriptionId: subscription.id })
.toArray(); .toArray();
}, [subscription]); }, [subscription]);
if (!notifications || notifications.length === 0) { if (!notifications || notifications.length === 0) {
return <NothingHereYet subscription={subscription}/>; return <NothingHereYet subscription={subscription}/>;
} }
const sortedNotifications = Array.from(notifications).sort((a, b) => a.time < b.time ? 1 : -1); const sortedNotifications = Array.from(notifications)
.sort((a, b) => a.time < b.time ? 1 : -1);
return ( return (
<Container maxWidth="lg" sx={{marginTop: 3, marginBottom: 3}}> <Container maxWidth="lg" sx={{marginTop: 3, marginBottom: 3}}>
<Stack spacing={3}> <Stack spacing={3}>
@ -30,7 +30,6 @@ const Notifications = (props) => {
key={notification.id} key={notification.id}
subscriptionId={subscription.id} subscriptionId={subscription.id}
notification={notification} notification={notification}
onDelete={(notificationId) => props.onDeleteNotification(subscription.id, notificationId)}
/>)} />)}
</Stack> </Stack>
</Container> </Container>
@ -38,15 +37,20 @@ const Notifications = (props) => {
} }
const NotificationItem = (props) => { const NotificationItem = (props) => {
const subscriptionId = props.subscriptionId;
const notification = props.notification; const notification = props.notification;
const date = new Intl.DateTimeFormat('default', {dateStyle: 'short', timeStyle: 'short'}) const date = new Intl.DateTimeFormat('default', {dateStyle: 'short', timeStyle: 'short'})
.format(new Date(notification.time * 1000)); .format(new Date(notification.time * 1000));
const otherTags = unmatchedTags(notification.tags); const otherTags = unmatchedTags(notification.tags);
const tags = (otherTags.length > 0) ? otherTags.join(', ') : null; const tags = (otherTags.length > 0) ? otherTags.join(', ') : null;
const handleDelete = async () => {
console.log(`[Notifications] Deleting notification ${notification.id} from ${subscriptionId}`);
await db.notifications.delete(notification.id); // FIXME
}
return ( return (
<Card sx={{ minWidth: 275 }}> <Card sx={{ minWidth: 275 }}>
<CardContent> <CardContent>
<IconButton onClick={() => props.onDelete(notification.id)} sx={{ float: 'right', marginRight: -1, marginTop: -1 }}> <IconButton onClick={handleDelete} sx={{ float: 'right', marginRight: -1, marginTop: -1 }}>
<CloseIcon /> <CloseIcon />
</IconButton> </IconButton>
<Typography sx={{ fontSize: 14 }} color="text.secondary"> <Typography sx={{ fontSize: 14 }} color="text.secondary">
@ -67,6 +71,7 @@ const NotificationItem = (props) => {
} }
const NothingHereYet = (props) => { const NothingHereYet = (props) => {
const shortUrl = topicShortUrl(props.subscription.baseUrl, props.subscription.topic);
return ( return (
<VerticallyCenteredContainer maxWidth="xs"> <VerticallyCenteredContainer maxWidth="xs">
<Typography variant="h5" align="center" sx={{ paddingBottom: 1 }}> <Typography variant="h5" align="center" sx={{ paddingBottom: 1 }}>
@ -79,7 +84,7 @@ const NothingHereYet = (props) => {
<Paragraph> <Paragraph>
Example:<br/> Example:<br/>
<tt> <tt>
$ curl -d "Hi" {props.subscription.shortUrl()} $ curl -d "Hi" {shortUrl}
</tt> </tt>
</Paragraph> </Paragraph>
<Paragraph> <Paragraph>

View file

@ -15,7 +15,7 @@ import {
} from "@mui/material"; } from "@mui/material";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import Paper from "@mui/material/Paper"; import Paper from "@mui/material/Paper";
import repository from "../app/Repository"; import prefs from "../app/Prefs";
import {Paragraph} from "./styles"; import {Paragraph} from "./styles";
import EditIcon from '@mui/icons-material/Edit'; import EditIcon from '@mui/icons-material/Edit';
import CloseIcon from "@mui/icons-material/Close"; import CloseIcon from "@mui/icons-material/Close";
@ -60,9 +60,9 @@ const Notifications = () => {
}; };
const MinPriority = () => { const MinPriority = () => {
const minPriority = useLiveQuery(() => repository.getMinPriority()); const minPriority = useLiveQuery(() => prefs.minPriority());
const handleChange = async (ev) => { const handleChange = async (ev) => {
await repository.setMinPriority(ev.target.value); await prefs.setMinPriority(ev.target.value);
} }
if (!minPriority) { if (!minPriority) {
return null; // While loading return null; // While loading
@ -83,9 +83,9 @@ const MinPriority = () => {
}; };
const DeleteAfter = () => { const DeleteAfter = () => {
const deleteAfter = useLiveQuery(async () => repository.getDeleteAfter()); const deleteAfter = useLiveQuery(async () => prefs.deleteAfter());
const handleChange = async (ev) => { const handleChange = async (ev) => {
await repository.setDeleteAfter(ev.target.value); await prefs.setDeleteAfter(ev.target.value);
} }
if (!deleteAfter) { if (!deleteAfter) {
return null; // While loading return null; // While loading
@ -95,7 +95,7 @@ const DeleteAfter = () => {
<FormControl fullWidth variant="standard" sx={{ m: 1 }}> <FormControl fullWidth variant="standard" sx={{ m: 1 }}>
<Select value={deleteAfter} onChange={handleChange}> <Select value={deleteAfter} onChange={handleChange}>
<MenuItem value={0}>Never</MenuItem> <MenuItem value={0}>Never</MenuItem>
<MenuItem value={10800}>After three hour</MenuItem> <MenuItem value={10800}>After three hours</MenuItem>
<MenuItem value={86400}>After one day</MenuItem> <MenuItem value={86400}>After one day</MenuItem>
<MenuItem value={604800}>After one week</MenuItem> <MenuItem value={604800}>After one week</MenuItem>
<MenuItem value={2592000}>After one month</MenuItem> <MenuItem value={2592000}>After one month</MenuItem>

View file

@ -7,7 +7,6 @@ import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent'; import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText'; import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle'; import DialogTitle from '@mui/material/DialogTitle';
import Subscription from "../app/Subscription";
import {Autocomplete, Checkbox, FormControlLabel, useMediaQuery} from "@mui/material"; import {Autocomplete, Checkbox, FormControlLabel, useMediaQuery} from "@mui/material";
import theme from "./theme"; import theme from "./theme";
import api from "../app/Api"; import api from "../app/Api";
@ -25,7 +24,12 @@ const SubscribeDialog = (props) => {
const fullScreen = useMediaQuery(theme.breakpoints.down('sm')); const fullScreen = useMediaQuery(theme.breakpoints.down('sm'));
const handleSuccess = () => { const handleSuccess = () => {
const actualBaseUrl = (baseUrl) ? baseUrl : defaultBaseUrl; // FIXME const actualBaseUrl = (baseUrl) ? baseUrl : defaultBaseUrl; // FIXME
const subscription = new Subscription(actualBaseUrl, topic); const subscription = {
id: topicUrl(actualBaseUrl, topic),
baseUrl: actualBaseUrl,
topic: topic,
last: null
};
props.onSuccess(subscription); props.onSuccess(subscription);
} }
return ( return (
@ -54,8 +58,8 @@ const SubscribePage = (props) => {
const [anotherServerVisible, setAnotherServerVisible] = useState(false); const [anotherServerVisible, setAnotherServerVisible] = useState(false);
const baseUrl = (anotherServerVisible) ? props.baseUrl : defaultBaseUrl; const baseUrl = (anotherServerVisible) ? props.baseUrl : defaultBaseUrl;
const topic = props.topic; const topic = props.topic;
const existingTopicUrls = props.subscriptions.map((id, s) => s.url()); const existingTopicUrls = props.subscriptions.map(s => topicUrl(s.baseUrl, s.topic));
const existingBaseUrls = Array.from(new Set(["https://ntfy.sh", ...props.subscriptions.map((id, s) => s.baseUrl)])) const existingBaseUrls = Array.from(new Set(["https://ntfy.sh", ...props.subscriptions.map(s => s.baseUrl)]))
.filter(s => s !== defaultBaseUrl); .filter(s => s !== defaultBaseUrl);
const handleSubscribe = async () => { const handleSubscribe = async () => {
const success = await api.auth(baseUrl, topic, null); const success = await api.auth(baseUrl, topic, null);