Merge branch 'customdata' into 'testing'

Add custom data to context

See merge request chicken-riders/RcGcDw!128
This commit is contained in:
Frisk 2024-09-27 08:54:05 +00:00
commit 0d10f928b4
7 changed files with 21 additions and 7 deletions

View file

@ -117,11 +117,14 @@ Context can consist of the following fields:
- `event` - string - action called, should be the same as formatter event action - `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 - `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 - `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 - `comment_page` - dict - containing `fullUrl` and `article` with strings both to full article url and its name
- `_` gettext.gettext - function for singular translations - `_` gettext.gettext - function for singular translations
- `ngettext` gettext.ngettext function for plural translations - `ngettext` gettext.ngettext function for plural translations
- `pgettext` gettext.pgettext function for translations differentiated by the context - `pgettext` gettext.pgettext function for translations differentiated by the context
- `npgettext` gettext.npgettext function for plural 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 ### Util
**Path**: `src.api.util` **Path**: `src.api.util`

View file

@ -80,6 +80,7 @@ def embed_edit(ctx: Context, change: dict) -> DiscordMessage:
except (ServerError, MediaWikiError): except (ServerError, MediaWikiError):
changed_content = None changed_content = None
if changed_content: if changed_content:
ctx.changed_content = changed_content
parse_mediawiki_changes(ctx, changed_content, embed) parse_mediawiki_changes(ctx, changed_content, embed)
else: else:
logger.warning("Unable to download data on the edit content!") 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 # 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: if request_for_image_data is not None:
try: try:
ctx.image_data = image_data
urls = image_data["imageinfo"] urls = image_data["imageinfo"]
for num, revision in enumerate(urls): for num, revision in enumerate(urls):
if revision["timestamp"] == change["logparams"][ if revision["timestamp"] == change["logparams"][

View file

@ -62,9 +62,15 @@ def buttons_hook(message: DiscordMessage, metadata: DiscordMessageMetadata, cont
if "delete" in action_buttons and context.event in ("new", "upload/upload"): if "delete" in action_buttons and context.event in ("new", "upload/upload"):
add_button(message, BUTTON_PREFIX + " delete " + str(change["pageid"]), add_button(message, BUTTON_PREFIX + " delete " + str(change["pageid"]),
action_buttons["delete"], 4, {"id": None, "name": "🗑️"}) action_buttons["delete"], 4, {"id": None, "name": "🗑️"})
# if "filerevert" in action_buttons and context.event in ("upload/overwrite", "upload/revert"): if "filerevert" in action_buttons and context.event in ("upload/overwrite", "upload/revert") and context.image_data:
# add_button(message, BUTTON_PREFIX + " file " + str(change["pageid"]) + " " + revision["archivename"].split("!")[0], found_cur = False
# action_buttons["filerevert"], 2, {"id": None, "name": "🔂"}) 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"): 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"], add_button(message, BUTTON_PREFIX + " move " + str(change["pageid"]) + " " + change["title"],
action_buttons["move"], 2, {"id": None, "name": "🔂"}) action_buttons["move"], 2, {"id": None, "name": "🔂"})

View file

@ -15,7 +15,7 @@
from __future__ import annotations from __future__ import annotations
from datetime import datetime from datetime import datetime, timezone
import src.misc import src.misc
import sched import sched
from typing import Union, Callable, Any 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""" """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): if isinstance(given_time, float) or isinstance(given_time, int):
return float(given_time) 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) then = datetime(now.year, now.month, now.day, *(map(int, given_time.split(':'))), 0, 0)
return float((then - now).seconds) return float((then - now).seconds)
def wrap_reschedule(function, period: float, *args, **kwargs): def wrap_reschedule(function, period: float, *args, **kwargs):

View file

@ -31,6 +31,8 @@ class Context:
self.feed_type = feed_type self.feed_type = feed_type
self.categories = None self.categories = None
self.parsedcomment = None self.parsedcomment = None
self.changed_content = None
self.image_data = None
self.event = None self.event = None
self.comment_page = None self.comment_page = None
self._ = language.gettext # Singular translations (ex. ctx._("Large goat")) 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.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.npgettext = language.npgettext # Plural translation with context (ex. ctx.npgettext("From mediawiki module", "Edited {} time", "Edited {} times", edit_amoint)
self.settings = settings self.settings = settings
self.custom_data = {}
def set_categories(self, cats): def set_categories(self, cats):
self.categories = cats self.categories = cats

View file

@ -127,7 +127,7 @@ def embed_helper(ctx: Context, message: DiscordMessage, change: dict, set_user=T
if settings.get("hide_ips", False): if settings.get("hide_ips", False):
author = ctx._("Unregistered user") author = ctx._("Unregistered user")
else: else:
author = change["user"] + "(?)" author = change["user"] + " (?)"
else: else:
ip_mapper[change["user"]] = len(contibs) ip_mapper[change["user"]] = len(contibs)
logger.debug("Current params user {} and state of map_ips {}".format(change["user"], ip_mapper)) logger.debug("Current params user {} and state of map_ips {}".format(change["user"], ip_mapper))

View file

@ -83,7 +83,7 @@ formatter_hooks["no_formatter"] = no_formatter
def day_overview_request() -> list: def day_overview_request() -> list:
"""Make requests for changes in last 24h""" """Make requests for changes in last 24h"""
logger.info("Fetching daily overview... This may take up to 30 seconds!") 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 = [] result = []
passes = 0 passes = 0
continuearg: Optional[str] = None continuearg: Optional[str] = None