mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-19 22:46:20 -05:00
Creating a share modal and button which allows a user to send a notification event to all users.
This commit is contained in:
parent
4e85e2f3d7
commit
ac363ae0e2
9 changed files with 139 additions and 8 deletions
|
|
@ -5,15 +5,15 @@ import {toast} from "react-semantic-toasts-2";
|
|||
|
||||
const apiEventName = 'apiEvent';
|
||||
|
||||
function eventToast(title, description, type = 'success', time = 5000) {
|
||||
toast({type: type, title: title, description: description, time: time});
|
||||
function eventToast(title, description, type = 'success', time = 5000, onClick = null) {
|
||||
toast({type: type, title: title, description: description, time: time, onClick: onClick});
|
||||
}
|
||||
|
||||
function handleEvents(events) {
|
||||
const newestEvents = {};
|
||||
|
||||
events.forEach(e => {
|
||||
const {event, message, subject, dt} = e;
|
||||
const {event, message, subject, dt, url} = e;
|
||||
document.dispatchEvent(new CustomEvent(apiEventName, {detail: e}));
|
||||
|
||||
if (subject && newestEvents[subject] && newestEvents[subject] > dt) {
|
||||
|
|
@ -27,6 +27,16 @@ function handleEvents(events) {
|
|||
eventToast('Downloads Disabled', message, 'info');
|
||||
}
|
||||
|
||||
if (event === 'user_notify_message') {
|
||||
console.log(message, url);
|
||||
eventToast(
|
||||
message,
|
||||
'Click here to view the shared page',
|
||||
'info',
|
||||
10_000,
|
||||
() => window.open(url, '_self'));
|
||||
}
|
||||
|
||||
if (subject) {
|
||||
newestEvents[subject] = dt;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -782,4 +782,15 @@ export async function fetchFile(path) {
|
|||
} else {
|
||||
console.error('Unable to fetch file dict! See client logs.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function sendNotification(message, url) {
|
||||
const body = {message, url};
|
||||
const response = await apiPost(`${API_URI}/notify`, body);
|
||||
if (response.status === 201) {
|
||||
toast({type: 'success', title: 'Shared', description: 'Your share was sent', time: 2000});
|
||||
} else {
|
||||
toast({type: 'error', title: 'Error', description: 'Your share failed to send!', time: 5000});
|
||||
console.error('Failed to share');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import {Dropdown, Menu} from "semantic-ui-react";
|
|||
import {Media, StatusContext, ThemeContext} from "../contexts/contexts";
|
||||
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
|
||||
import {DarkModeToggle, HotspotStatusIcon, NAME} from "./Common";
|
||||
import {ShareButton} from "./Share";
|
||||
|
||||
const links = [
|
||||
{text: 'Videos', to: '/videos', key: 'videos'},
|
||||
|
|
@ -64,6 +65,7 @@ export function NavBar() {
|
|||
{topNavText}
|
||||
</NavLink>;
|
||||
const icons = <React.Fragment>
|
||||
<NavIcon><ShareButton/></NavIcon>
|
||||
<NavIcon><HotspotStatusIcon/></NavIcon>
|
||||
<NavIcon><DarkModeToggle/></NavIcon>
|
||||
</React.Fragment>;
|
||||
|
|
|
|||
62
app/src/components/Share.js
Normal file
62
app/src/components/Share.js
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import React from "react";
|
||||
import {Icon} from "./Theme";
|
||||
import {Button as SButton, Header, IconGroup, Modal} from "semantic-ui-react";
|
||||
import QRCode from "react-qr-code";
|
||||
import {sendNotification} from "../api";
|
||||
|
||||
export const ShareEveryoneButton = ({url, size, onClick}) => {
|
||||
const handleShare = async () => {
|
||||
await sendNotification('Look at this page', url);
|
||||
if (onClick) {
|
||||
await onClick();
|
||||
}
|
||||
}
|
||||
|
||||
return <SButton
|
||||
color='violet'
|
||||
size={size}
|
||||
onClick={handleShare}
|
||||
>
|
||||
Share with everyone
|
||||
</SButton>
|
||||
}
|
||||
|
||||
export const ShareButton = () => {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
|
||||
const handleOpen = (e) => {
|
||||
if (e) {
|
||||
e.preventDefault();
|
||||
}
|
||||
setOpen(true);
|
||||
}
|
||||
|
||||
const handleClose = (e) => {
|
||||
if (e) {
|
||||
e.preventDefault();
|
||||
}
|
||||
setOpen(false);
|
||||
}
|
||||
|
||||
return <>
|
||||
<Modal closeIcon
|
||||
open={open}
|
||||
onClose={handleClose}
|
||||
>
|
||||
<Modal.Header>Share this page</Modal.Header>
|
||||
<Modal.Content>
|
||||
<Header as='h4'>Another user can scan this QR code to view this page</Header>
|
||||
<QRCode value={window.location.href}/>
|
||||
</Modal.Content>
|
||||
<Modal.Actions>
|
||||
<ShareEveryoneButton url={window.location.href} onClick={handleClose}/>
|
||||
<SButton onClick={handleClose}>Close</SButton>
|
||||
</Modal.Actions>
|
||||
</Modal>
|
||||
<a href='#' onClick={handleOpen}>
|
||||
<IconGroup size='large'>
|
||||
<Icon name='share'/>
|
||||
</IconGroup>
|
||||
</a>
|
||||
</>
|
||||
}
|
||||
|
|
@ -20,7 +20,7 @@ from multiprocessing import Lock, Manager
|
|||
from pathlib import Path
|
||||
from types import GeneratorType
|
||||
from typing import Union, Callable, Tuple, Dict, List, Iterable, Optional, Generator, Any, Set
|
||||
from urllib.parse import urlparse
|
||||
from urllib.parse import urlparse, urlunsplit
|
||||
|
||||
import aiohttp
|
||||
import yaml
|
||||
|
|
@ -1166,3 +1166,14 @@ def resolve_generators(obj: Union[Dict, List]) -> Any:
|
|||
elif isinstance(obj, GeneratorType) or isinstance(obj, Iterable):
|
||||
return [resolve_generators(i) for i in obj]
|
||||
return obj
|
||||
|
||||
|
||||
def url_strip_host(url: str) -> str:
|
||||
"""Return a relative URL without the host or scheme.
|
||||
|
||||
>>> url_strip_host('https://example.com/foo')
|
||||
'/foo'
|
||||
"""
|
||||
url = urlparse(url)
|
||||
url = urlunsplit(('', '', url.path, url.query, url.fragment))
|
||||
return url or '/'
|
||||
|
|
|
|||
|
|
@ -49,6 +49,10 @@ class Events:
|
|||
def send_downloads_disabled(message: str = None):
|
||||
send_event('downloads_disabled', message, subject='downloads')
|
||||
|
||||
@staticmethod
|
||||
def send_user_notify(message: str, url: str = None):
|
||||
send_event('user_notify_message', message, subject='user_notify', url=url)
|
||||
|
||||
|
||||
def log_event(event: str, message: str = None, action: str = None, subject: str = None):
|
||||
log = f'{event=}'
|
||||
|
|
@ -61,7 +65,7 @@ def log_event(event: str, message: str = None, action: str = None, subject: str
|
|||
logger.debug(log)
|
||||
|
||||
|
||||
def send_event(event: str, message: str = None, action: str = None, subject: str = None):
|
||||
def send_event(event: str, message: str = None, action: str = None, subject: str = None, url: str = None):
|
||||
EVENTS_LOCK.acquire()
|
||||
try:
|
||||
# All events will be in time order, they should never be at the exact same time.
|
||||
|
|
@ -73,6 +77,7 @@ def send_event(event: str, message: str = None, action: str = None, subject: str
|
|||
event=event,
|
||||
message=message,
|
||||
subject=subject,
|
||||
url=url,
|
||||
)
|
||||
EVENTS_HISTORY.append(e)
|
||||
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ from wrolpi import admin, status, flags, schema
|
|||
from wrolpi import tags
|
||||
from wrolpi.admin import HotspotStatus
|
||||
from wrolpi.common import logger, get_config, wrol_mode_enabled, Base, get_media_directory, \
|
||||
wrol_mode_check, native_only, disable_wrol_mode, enable_wrol_mode, get_global_statistics
|
||||
wrol_mode_check, native_only, disable_wrol_mode, enable_wrol_mode, get_global_statistics, url_strip_host
|
||||
from wrolpi.dates import now, strptime
|
||||
from wrolpi.downloader import download_manager
|
||||
from wrolpi.errors import WROLModeEnabled, API_ERRORS, APIError, ValidationError, HotspotError, InvalidDownload
|
||||
|
|
@ -408,7 +408,16 @@ async def post_new_tag(_: Request, body: schema.TagRequest, tag_id: int = None):
|
|||
@api_bp.delete('/tag/<tag_id:int>')
|
||||
async def delete_tag_request(_: Request, tag_id: int):
|
||||
tags.delete_tag(tag_id)
|
||||
return response.empty(HTTPStatus.NO_CONTENT)
|
||||
return response.empty()
|
||||
|
||||
|
||||
@api_bp.post('/notify')
|
||||
@validate(schema.NotifyRequest)
|
||||
async def post_notify(_: Request, body: schema.NotifyRequest):
|
||||
"""Sends a notify Event"""
|
||||
url = url_strip_host(body.url)
|
||||
Events.send_user_notify(body.message, url)
|
||||
return response.empty(HTTPStatus.CREATED)
|
||||
|
||||
|
||||
class CustomJSONEncoder(json.JSONEncoder):
|
||||
|
|
|
|||
|
|
@ -76,3 +76,9 @@ class TagRequest:
|
|||
@dataclass
|
||||
class DeleteTagRequest:
|
||||
name: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class NotifyRequest:
|
||||
message: str
|
||||
url: str = None
|
||||
|
|
|
|||
|
|
@ -638,3 +638,18 @@ def test_resolve_generators2():
|
|||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'url,expected', [
|
||||
('https://example.com', '/'),
|
||||
('https://example.com/foo', '/foo'),
|
||||
('https://example.com/foo?question=answer', '/foo?question=answer'),
|
||||
('https://example.com/foo?question=answer#fragment', '/foo?question=answer#fragment'),
|
||||
('https://exmaple.com/files?folders=test+%23+example%2F', '/files?folders=test+%23+example%2F'),
|
||||
('https://exmaple.com/files?folders=test+%23+example%2F&folders=map%2F',
|
||||
'/files?folders=test+%23+example%2F&folders=map%2F'),
|
||||
]
|
||||
)
|
||||
def test_url_strip_host(url, expected):
|
||||
assert common.url_strip_host(url) == expected
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue