From ac363ae0e28cec710cb8ac5e31d2314c06d4e8c5 Mon Sep 17 00:00:00 2001 From: Roland Date: Mon, 10 Apr 2023 13:15:34 -0600 Subject: [PATCH] Creating a share modal and button which allows a user to send a notification event to all users. --- app/src/Events.js | 16 ++++++++-- app/src/api.js | 13 +++++++- app/src/components/Nav.js | 2 ++ app/src/components/Share.js | 62 +++++++++++++++++++++++++++++++++++++ wrolpi/common.py | 13 +++++++- wrolpi/events.py | 7 ++++- wrolpi/root_api.py | 13 ++++++-- wrolpi/schema.py | 6 ++++ wrolpi/test/test_common.py | 15 +++++++++ 9 files changed, 139 insertions(+), 8 deletions(-) create mode 100644 app/src/components/Share.js diff --git a/app/src/Events.js b/app/src/Events.js index e801656c..f453ee94 100644 --- a/app/src/Events.js +++ b/app/src/Events.js @@ -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; } diff --git a/app/src/api.js b/app/src/api.js index 64a1103f..93d2dbbf 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -782,4 +782,15 @@ export async function fetchFile(path) { } else { console.error('Unable to fetch file dict! See client logs.'); } -} \ No newline at end of file +} + +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'); + } +} diff --git a/app/src/components/Nav.js b/app/src/components/Nav.js index 204e311e..fb0c20ab 100644 --- a/app/src/components/Nav.js +++ b/app/src/components/Nav.js @@ -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} ; const icons = + ; diff --git a/app/src/components/Share.js b/app/src/components/Share.js new file mode 100644 index 00000000..ca146eec --- /dev/null +++ b/app/src/components/Share.js @@ -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 + Share with everyone + +} + +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 <> + + Share this page + +
Another user can scan this QR code to view this page
+ +
+ + + Close + +
+ + + + + + +} \ No newline at end of file diff --git a/wrolpi/common.py b/wrolpi/common.py index 4a9fe0bf..55b3b463 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -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 '/' diff --git a/wrolpi/events.py b/wrolpi/events.py index e1faa3ee..c385ed2b 100644 --- a/wrolpi/events.py +++ b/wrolpi/events.py @@ -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) diff --git a/wrolpi/root_api.py b/wrolpi/root_api.py index abb801e4..bf731e95 100644 --- a/wrolpi/root_api.py +++ b/wrolpi/root_api.py @@ -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/') 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): diff --git a/wrolpi/schema.py b/wrolpi/schema.py index caa796f5..16d83751 100644 --- a/wrolpi/schema.py +++ b/wrolpi/schema.py @@ -76,3 +76,9 @@ class TagRequest: @dataclass class DeleteTagRequest: name: str + + +@dataclass +class NotifyRequest: + message: str + url: str = None diff --git a/wrolpi/test/test_common.py b/wrolpi/test/test_common.py index 9f748217..be4d666d 100644 --- a/wrolpi/test/test_common.py +++ b/wrolpi/test/test_common.py @@ -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