From 481f368a4d48fda83d7323bcf4f01a10b1a8de9c Mon Sep 17 00:00:00 2001 From: MarkusRost <2701034-MarkusRost@users.noreply.gitlab.com> Date: Thu, 26 Sep 2024 04:57:45 +0200 Subject: [PATCH] Add custom data to context #264 --- docs/API spec.md | 3 +++ extensions/base/mediawiki.py | 2 ++ extensions/hooks/buttons.py | 12 +++++++++--- src/api/client.py | 4 ++-- src/api/context.py | 3 +++ src/api/util.py | 2 +- src/rcgcdw.py | 2 +- 7 files changed, 21 insertions(+), 7 deletions(-) diff --git a/docs/API spec.md b/docs/API spec.md index 4c12129..33a91b5 100644 --- a/docs/API spec.md +++ b/docs/API spec.md @@ -117,11 +117,14 @@ Context can consist of the following fields: - `event` - string - action called, should be the same as formatter event action - `categories` - {"new": set(), "removed": set()} - each set containing strings of added or removed categories for given page - `parsedcomment` - string - contains escaped and Markdown parsed summary (parsed_comment) of a log/edit action +- `changed_content` - dict/None - contains edit diff api response when show_edit_changes is enabled and the embed edit formatter was used +- `image_data` - dict/None - contains image data api response when the embed upload formatter was used - `comment_page` - dict - containing `fullUrl` and `article` with strings both to full article url and its name - `_` – gettext.gettext - function for singular translations - `ngettext` – gettext.ngettext – function for plural translations - `pgettext` – gettext.pgettext – function for translations differentiated by the context - `npgettext` – gettext.npgettext – function for plural translations differentiated by the context +- `custom_data` – dict – empty dict for hooks or formatters to store information, use at own risk ### Util **Path**: `src.api.util` diff --git a/extensions/base/mediawiki.py b/extensions/base/mediawiki.py index 7ce5c19..588b0ed 100644 --- a/extensions/base/mediawiki.py +++ b/extensions/base/mediawiki.py @@ -80,6 +80,7 @@ def embed_edit(ctx: Context, change: dict) -> DiscordMessage: except (ServerError, MediaWikiError): changed_content = None if changed_content: + ctx.changed_content = changed_content parse_mediawiki_changes(ctx, changed_content, embed) else: logger.warning("Unable to download data on the edit content!") @@ -159,6 +160,7 @@ def embed_upload_upload(ctx: Context, change: dict) -> DiscordMessage: # Make a request for file revisions so we can get direct URL to the image for embed if request_for_image_data is not None: try: + ctx.image_data = image_data urls = image_data["imageinfo"] for num, revision in enumerate(urls): if revision["timestamp"] == change["logparams"][ diff --git a/extensions/hooks/buttons.py b/extensions/hooks/buttons.py index f49bf18..1a293d0 100644 --- a/extensions/hooks/buttons.py +++ b/extensions/hooks/buttons.py @@ -62,9 +62,15 @@ def buttons_hook(message: DiscordMessage, metadata: DiscordMessageMetadata, cont if "delete" in action_buttons and context.event in ("new", "upload/upload"): add_button(message, BUTTON_PREFIX + " delete " + str(change["pageid"]), action_buttons["delete"], 4, {"id": None, "name": "🗑️"}) - # if "filerevert" in action_buttons and context.event in ("upload/overwrite", "upload/revert"): - # add_button(message, BUTTON_PREFIX + " file " + str(change["pageid"]) + " " + revision["archivename"].split("!")[0], - # action_buttons["filerevert"], 2, {"id": None, "name": "🔂"}) + if "filerevert" in action_buttons and context.event in ("upload/overwrite", "upload/revert") and context.image_data: + found_cur = False + for revision in context.image_data.get("imageinfo", []): + if found_cur: + add_button(message, BUTTON_PREFIX + " file " + str(change["pageid"]) + " " + revision["archivename"].split("!")[0], + action_buttons["filerevert"], 2, {"id": None, "name": "🔂"}) + break + if revision["timestamp"] == change["logparams"]["img_timestamp"]: # find the correct revision corresponding for this log entry + found_cur = True if "move" in action_buttons and context.event in ("move/move", "move/move_redir"): add_button(message, BUTTON_PREFIX + " move " + str(change["pageid"]) + " " + change["title"], action_buttons["move"], 2, {"id": None, "name": "🔂"}) diff --git a/src/api/client.py b/src/api/client.py index 66fd945..b0112e1 100644 --- a/src/api/client.py +++ b/src/api/client.py @@ -15,7 +15,7 @@ from __future__ import annotations -from datetime import datetime +from datetime import datetime, timezone import src.misc import sched from typing import Union, Callable, Any @@ -63,7 +63,7 @@ class Client: """Converts UTC time to amount of seconds from now, if amount of seconds given returns seconds as a float""" if isinstance(given_time, float) or isinstance(given_time, int): return float(given_time) - now = datetime.utcnow() + now = datetime.now(timezone.utc) then = datetime(now.year, now.month, now.day, *(map(int, given_time.split(':'))), 0, 0) return float((then - now).seconds) def wrap_reschedule(function, period: float, *args, **kwargs): diff --git a/src/api/context.py b/src/api/context.py index 55ab4c6..2a3acc4 100644 --- a/src/api/context.py +++ b/src/api/context.py @@ -31,6 +31,8 @@ class Context: self.feed_type = feed_type self.categories = None self.parsedcomment = None + self.changed_content = None + self.image_data = None self.event = None self.comment_page = None self._ = language.gettext # Singular translations (ex. ctx._("Large goat")) @@ -39,6 +41,7 @@ class Context: self.pgettext = language.pgettext # Translation with context (ex. ctx.pgettext("From mediawiki module", "Blocked {} user")) self.npgettext = language.npgettext # Plural translation with context (ex. ctx.npgettext("From mediawiki module", "Edited {} time", "Edited {} times", edit_amoint) self.settings = settings + self.custom_data = {} def set_categories(self, cats): self.categories = cats diff --git a/src/api/util.py b/src/api/util.py index 3982bab..802e43d 100644 --- a/src/api/util.py +++ b/src/api/util.py @@ -126,7 +126,7 @@ def embed_helper(ctx: Context, message: DiscordMessage, change: dict, set_user=T if settings.get("hide_ips", False): author = ctx._("Unregistered user") else: - author = change["user"] + "(?)" + author = change["user"] + " (?)" else: ip_mapper[change["user"]] = len(contibs) logger.debug("Current params user {} and state of map_ips {}".format(change["user"], ip_mapper)) diff --git a/src/rcgcdw.py b/src/rcgcdw.py index 4900b03..1debb77 100644 --- a/src/rcgcdw.py +++ b/src/rcgcdw.py @@ -83,7 +83,7 @@ formatter_hooks["no_formatter"] = no_formatter def day_overview_request() -> list: """Make requests for changes in last 24h""" logger.info("Fetching daily overview... This may take up to 30 seconds!") - timestamp = (datetime.datetime.utcnow() - datetime.timedelta(hours=24)).isoformat(timespec='milliseconds') + timestamp = (datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(hours=24)).isoformat(timespec='milliseconds') result = [] passes = 0 continuearg: Optional[str] = None