Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions changedetectionio/blueprint/watchlist/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ def index():
# row push so a live-updated row can't drift from the server-rendered one.
row_ctx = watch_row_context(datastore,
active_tag_uuid=active_tag_uuid,
active_processor=active_processor,
queued_uuids=update_q.get_queued_uuids())

output = render_template(
Expand All @@ -142,7 +143,6 @@ def index():
extra_title=f" - {_('Group: %(name)s', name=active_tag.get('title', ''))}" if active_tag else '',
**row_ctx,
active_tag=active_tag,
active_processor=active_processor,
checking_now_size=len(worker_pool.get_running_uuids()),
app_rss_token=datastore.data['settings']['application'].get('rss_access_token'),
errored_count=errored_count,
Expand All @@ -167,7 +167,6 @@ def index():
now_time_server=round(time.time()),
pagination=pagination,
processor_badge_css=processors.get_processor_badge_css(),
processor_badge_texts=processors.get_processor_badge_texts(),
queue_size=update_q.qsize(),
# Active view filters (tag/processor/q/unread/...) so links (e.g. column sorting)
# can re-apply them and not drop the operator's current filtered view.
Expand Down
6 changes: 5 additions & 1 deletion changedetectionio/blueprint/watchlist/row_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@
from changedetectionio import processors


def watch_row_context(datastore, active_tag_uuid=None, queued_uuids=None):
def watch_row_context(datastore, active_tag_uuid=None, queued_uuids=None, active_processor=''):
"""Context for one (or many) watch list rows.

active_tag_uuid matters: the row's Edit/Recheck links carry the tag so the operator lands
back on the filtered view they came from. A pushed row must therefore be rendered with the
tag of the page that will receive it, not a global one.

active_processor: the processor the list is filtered by ('' for none), its badge in the row is shown active.

queued_uuids is accepted so a caller rendering many rows can fetch the queue once instead
of per row; omit it and the live queue is read for you.
"""
Expand All @@ -29,13 +31,15 @@ def watch_row_context(datastore, active_tag_uuid=None, queued_uuids=None):
queued_uuids = update_q.get_queued_uuids()

return {
'active_processor': active_processor or '',
'active_tag_uuid': active_tag_uuid,
# Also decides cols_required on the page, so page and row must agree or a pushed row
# ends up with a different <td> count than the table header — which is why it is
# computed here and not passed separately by the page.
'any_has_restock_price_processor': datastore.any_watches_have_processor_by_name("restock_diff"),
'datastore': datastore,
'has_proxies': datastore.proxy_list,
'processor_badge_texts': processors.get_processor_badge_texts(),
'processor_descriptions': processors.get_processor_descriptions(),
'queued_uuids': queued_uuids,
'system_default_fetcher': datastore.data['settings']['application'].get('fetch_backend'),
Expand Down
43 changes: 27 additions & 16 deletions changedetectionio/realtime/socket_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,17 @@ def watch_room(watch_uuid):
# The rendered row of a watch goes to the pages listing it. A list filtered by a group has that group in the row's
# links (Edit, Recheck, pause ... come back to the filtered list), and an app served under a sub-path
# (USE_X_SETTINGS with X-Forwarded-Prefix, e.g. example.com/changedetection/) has that path at the start of every
# address in the row. So there is one room per watch, group and sub-path: a page joins the one for the group it is
# filtered by ('' for none) and the sub-path it was reached under ('' for none), and is sent the row rendered for
# those. The row is rendered from a worker thread, outside any request, so nothing else says which sub-path the
# address in the row. A list filtered by a processor shows that processor's badge active. So there is one room per
# watch, group, processor and sub-path: a page joins the one for the group and processor it is filtered by ('' for
# none) and the sub-path it was reached under ('' for none), and is sent the row rendered for those. The row is rendered from a worker thread, outside any request, so nothing else says which sub-path the
# page's addresses need.
WATCH_ROW_ROOM_PREFIX = 'watch-row:'
# watch uuid -> the (group filter, sub-path) pairs of the pages that have asked for its row
# watch uuid -> the (group filter, sub-path, processor filter) of the pages that have asked for its row
_row_filters_shown = {}


def watch_row_room(watch_uuid, tag_uuid='', url_prefix=''):
return f"{WATCH_ROW_ROOM_PREFIX}{watch_uuid}:{tag_uuid or ''}:{url_prefix or ''}"
def watch_row_room(watch_uuid, tag_uuid='', url_prefix='', processor=''):
return f"{WATCH_ROW_ROOM_PREFIX}{watch_uuid}:{tag_uuid or ''}:{processor or ''}:{url_prefix or ''}"


def connection_url_prefix(page_says=None):
Expand Down Expand Up @@ -396,32 +396,35 @@ def has_connected_clients(socketio):
return True


def render_watch_list_row(watch, datastore, tag_uuid='', queued_uuids=None, url_prefix=''):
def render_watch_list_row(watch, datastore, tag_uuid='', queued_uuids=None, url_prefix='', processor=''):
"""The watch's row of the watch list, from the template the page itself is made with
(watch-overview-single-row.html with blueprint/watchlist/row_context.py), as the list filtered by `tag_uuid`
shows it. Mostly called from a worker thread at the end of a check, where there is no request to render in.
url_prefix: the sub-path the page is served under, so the row's addresses (links, images, form actions) start
with it as they do in the page."""
with it as they do in the page.
processor: the processor the list is filtered by, its badge is shown active."""
from flask import render_template
from changedetectionio.blueprint.watchlist.row_context import watch_row_context

def render():
return render_template('watch-overview-single-row.html', watch=watch,
**watch_row_context(datastore, active_tag_uuid=tag_uuid or None, queued_uuids=queued_uuids))
**watch_row_context(datastore, active_tag_uuid=tag_uuid or None, queued_uuids=queued_uuids,
active_processor=processor))

# The row reads the group from the request too (the Recheck button), so always in a request of that list
from changedetectionio.flask_app import app
with app.test_request_context(query_string={'tag': tag_uuid} if tag_uuid else None,
query = {k: v for k, v in (('tag', tag_uuid), ('processor', processor)) if v}
with app.test_request_context(query_string=query or None,
environ_overrides={'SCRIPT_NAME': url_prefix} if url_prefix else None):
return render()


def send_watch_list_row(socketio, watch, datastore, queued_uuids=None):
"""Send the watch's rendered row to the pages that list it, once for each group filter among them."""
"""Send the watch's rendered row to the pages that list it, once for each filter and sub-path among them."""
uuid = watch.get('uuid')
for shown in list(_row_filters_shown.get(uuid, ())):
tag_uuid, url_prefix = shown
room = watch_row_room(uuid, tag_uuid, url_prefix)
tag_uuid, url_prefix, processor = shown
room = watch_row_room(uuid, tag_uuid, url_prefix, processor)
try:
has_pages = next(iter(socketio.server.manager.get_participants('/', room)), None) is not None
except AttributeError:
Expand All @@ -433,7 +436,8 @@ def send_watch_list_row(socketio, watch, datastore, queued_uuids=None):
del _row_filters_shown[uuid]
continue
try:
html = render_watch_list_row(watch, datastore, tag_uuid=tag_uuid, queued_uuids=queued_uuids, url_prefix=url_prefix)
html = render_watch_list_row(watch, datastore, tag_uuid=tag_uuid, queued_uuids=queued_uuids,
url_prefix=url_prefix, processor=processor)
except Exception as e:
logger.error(f"Socket.IO: could not render the watch list row of {uuid}: {str(e)}")
continue
Expand Down Expand Up @@ -616,12 +620,19 @@ def event_watch_subscribe(data):
if rows_for is not None and not (isinstance(rows_for, str) and (rows_for == '' or rows_for in socketio.datastore.data['settings']['application']['tags'])):
rows_for = None
url_prefix = connection_url_prefix((data or {}).get('rows_url_prefix')) if rows_for is not None else ''
# And by which processor ('' for none, or one that is not a processor: the list then has no badge active)
rows_processor = (data or {}).get('rows_for_processor')
rows_processor = rows_processor.strip() if isinstance(rows_processor, str) else ''
if rows_processor:
from changedetectionio import processors
if rows_processor not in processors.get_processor_badge_texts():
rows_processor = ''
for uuid in uuids[:MAX_WATCH_SUBSCRIPTIONS]:
if isinstance(uuid, str) and uuid in watching:
join_room(watch_room(uuid))
if rows_for is not None:
join_room(watch_row_room(uuid, rows_for, url_prefix))
_row_filters_shown.setdefault(uuid, set()).add((rows_for, url_prefix))
join_room(watch_row_room(uuid, rows_for, url_prefix, rows_processor))
_row_filters_shown.setdefault(uuid, set()).add((rows_for, url_prefix, rows_processor))

@socketio.on('connect')
def handle_connect():
Expand Down
5 changes: 4 additions & 1 deletion changedetectionio/static/js/realtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,10 @@ $(document).ready(function () {
// A watch list also asks for the rows themselves, as the list filtered by its group shows them
const subscription = {uuids: watchUuidsOnThisPage()};
if (document.querySelector('.watch-table tr[data-watch-uuid]')) {
subscription.rows_for_tag = new URLSearchParams(window.location.search).get('tag') || '';
const pageParams = new URLSearchParams(window.location.search);
subscription.rows_for_tag = pageParams.get('tag') || '';
// And the processor it is filtered by, whose badge is shown active
subscription.rows_for_processor = (pageParams.get('processor') || '').trim();
// And under which sub-path this page is served (example.com/our-changedetection/), so the
// addresses in a row start as the ones in this page do. It is the start of this connection's path.
subscription.rows_url_prefix = socketio_url.replace(/\/socket\.io$/, '');
Expand Down
52 changes: 49 additions & 3 deletions changedetectionio/tests/test_basic_socketio.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,11 +166,22 @@ def _latest_row(socketio_client, uuid, seconds=5):
return latest


def _list_page(app, client, uuids, tag=''):
"""A browser with the watch list open, filtered by the group `tag` (or not)"""
def _processor_cell(html_text, uuid):
"""The watch-processor <td> of the watch's row in html_text (a pushed row or the whole list page)"""
row_start = html_text.index(f'data-watch-uuid="{uuid}"')
m = re.search(r'<td class="watch-processor">(.*?)</td>', html_text[row_start:], re.DOTALL)
assert m, "The row has its processor cell"
return m.group(1).strip()


def _list_page(app, client, uuids, tag='', processor=None):
"""A browser with the watch list open, filtered by the group `tag` (or not) and the `processor` (or not)"""
page = app.extensions['socketio'].test_client(app, flask_test_client=client)
assert page.is_connected()
page.emit('watch-subscribe', {'uuids': uuids, 'rows_for_tag': tag})
asks = {'uuids': uuids, 'rows_for_tag': tag}
if processor is not None:
asks['rows_for_processor'] = processor
page.emit('watch-subscribe', asks)
page.get_received()
return page

Expand Down Expand Up @@ -205,6 +216,11 @@ def test_watch_list_row_is_sent_with_stock_and_price(client, live_server, measur
# What was sent is what a reload of the list shows
res = client.get(url_for("watchlist.index"))
assert b'In stock' in res.data and b'10.00' in res.data and b'No information' not in res.data
# The processor badge too: the row is rendered without the page's own context, so what the row needs must
# come from row_context.py (an undefined name there is empty, not an error)
cell = _processor_cell(row, uuid)
assert 'processor-badge-restock_diff' in cell
assert cell == _processor_cell(res.data.decode(), uuid)

# A new price and out of stock arrive the same way
_set_restock_product(datastore_path, price='7.50', in_stock=False)
Expand Down Expand Up @@ -242,6 +258,9 @@ def test_watch_list_row_is_sent_with_groups_and_title(client, live_server, measu
tag_uuid = next(iter(tags))
assert 'Made after the page loaded' in row
assert url_for('watchlist.index', tag=tag_uuid) in row, "A link to the group's watches"
cell = _processor_cell(row, uuid)
assert 'processor-badge-text_json_diff' in cell, "The processor badge is in the row"
assert cell == _processor_cell(client.get(url_for("watchlist.index")).data.decode(), uuid)
# In the group's colours by itself: the page's own colour rules are from before the group existed
colours = tag_display_colours(tags[tag_uuid])
assert f"--tag-chip-bg: {colours['light']['bg']}" in row and f"--tag-chip-dark-bg: {colours['dark']['bg']}" in row
Expand Down Expand Up @@ -312,6 +331,33 @@ def test_watch_list_row_is_sent_as_the_filtered_list_shows_it(client, live_serve
delete_all_watches(client)


def test_watch_list_row_is_sent_as_the_processor_filtered_list_shows_it(client, live_server, measure_memory_usage, datastore_path):
"""A list filtered by a processor (?processor=) shows that processor's badge active, and so does a row sent to it"""
from changedetectionio.flask_app import app
datastore = client.application.config.get('DATASTORE')
uuid = datastore.add_watch(url=url_for('test_endpoint', _external=True), extras={'paused': True})

plain = _list_page(app, client, [uuid])
filtered = _list_page(app, client, [uuid], processor='text_json_diff')
made_up = _list_page(app, client, [uuid], processor='<b>no-such-processor')

client.post(url_for("ui.form_watch_list_checkbox_operations"), data={"op": "mute", "uuids": [uuid]}, follow_redirects=True)
plain_row, filtered_row, made_up_row = (_latest_row(p, uuid, seconds=2) for p in (plain, filtered, made_up))
assert plain_row and filtered_row and made_up_row

assert 'processor-badge-text_json_diff active' not in _processor_cell(plain_row, uuid)
assert 'processor-badge-text_json_diff active' in _processor_cell(filtered_row, uuid)
assert _processor_cell(made_up_row, uuid) == _processor_cell(plain_row, uuid), "Not a processor: no filter"
# As a reload of each list shows it
for row, args in ((plain_row, {}), (filtered_row, {'processor': 'text_json_diff'})):
res = client.get(url_for("watchlist.index", **args))
assert _processor_cell(row, uuid) == _processor_cell(res.data.decode(), uuid)

for p in (plain, filtered, made_up):
p.disconnect()
delete_all_watches(client)


def test_watch_list_row_is_sent_with_the_sub_path_of_the_page(client, live_server, measure_memory_usage, datastore_path, monkeypatch):
"""The app served under a sub-path (USE_X_SETTINGS and X-Forwarded-Prefix, example.com/our-changedetection/):
every address in a page starts with that path. A row is rendered from a worker thread, outside any request, so
Expand Down