Changed to function format instead of method

This commit is contained in:
Frisk 2021-04-27 09:35:15 +02:00
parent 18aae9eabe
commit 0db3be3e76
No known key found for this signature in database
GPG key ID: 213F7C15068AF8AC
5 changed files with 125 additions and 86 deletions

View file

@ -44,19 +44,16 @@ _ = rc_formatters.gettext
logger = logging.getLogger("extensions.abusefilter") logger = logging.getLogger("extensions.abusefilter")
class abusefilter():
def __init__(self, api):
super().__init__(api)
@formatter.embed(event="abuselog/modify", mode="embed") @formatter.embed(event="abuselog/modify", mode="embed")
def embed_modify(self, ctx: Context, change: dict) -> DiscordMessage: def embed_modify(ctx: Context, change: dict) -> DiscordMessage:
embed = DiscordMessage(ctx.message_type, ctx.event, webhook_url=ctx.webhook_url) embed = DiscordMessage(ctx.message_type, ctx.event, webhook_url=ctx.webhook_url)
embed.set_link(create_article_path("Special:AbuseFilter/history/{number}/diff/prev/{historyid}".format(number=change["logparams"]['newId'], historyid=change["logparams"]["historyId"]))) embed.set_link(create_article_path("Special:AbuseFilter/history/{number}/diff/prev/{historyid}".format(number=change["logparams"]['newId'], historyid=change["logparams"]["historyId"])))
embed["title"] = _("Edited abuse filter number {number}").format(number=change["logparams"]['newId']) embed["title"] = _("Edited abuse filter number {number}").format(number=change["logparams"]['newId'])
return embed return embed
@formatter.compact(event="abuselog/modify") @formatter.compact(event="abuselog/modify")
def embed_modify(self, ctx: Context, change: dict) -> DiscordMessage: def embed_modify(ctx: Context, change: dict) -> DiscordMessage:
link = link_formatter(create_article_path("Special:AbuseFilter/history/{number}/diff/prev/{historyid}".format(number=change["logparams"]['newId'], historyid=change["logparams"]["historyId"]))) link = link_formatter(create_article_path("Special:AbuseFilter/history/{number}/diff/prev/{historyid}".format(number=change["logparams"]['newId'], historyid=change["logparams"]["historyId"])))
content = _("[{author}]({author_url}) edited abuse filter [number {number}]({filter_url})").format(author=author, author_url=author_url, number=change["logparams"]['newId'], filter_url=link) content = _("[{author}]({author_url}) edited abuse filter [number {number}]({filter_url})").format(author=author, author_url=author_url, number=change["logparams"]['newId'], filter_url=link)
return DiscordMessage return DiscordMessage

View file

@ -27,12 +27,8 @@ _ = rc_formatters.gettext
logger = logging.getLogger("extensions.base") logger = logging.getLogger("extensions.base")
class base():
def __init__(self, api):
super().__init__(api)
@formatter.embed(event="edit", mode="embed") @formatter.embed(event="edit", mode="embed")
def embed_edit(self, ctx: Context, change: dict) -> DiscordMessage: def embed_edit(ctx: Context, change: dict) -> DiscordMessage:
embed = DiscordMessage(ctx.message_type, ctx.event, ctx.webhook_url) embed = DiscordMessage(ctx.message_type, ctx.event, ctx.webhook_url)
action = ctx.event action = ctx.event
editsize = change["newlen"] - change["oldlen"] editsize = change["newlen"] - change["oldlen"]
@ -50,9 +46,9 @@ class base():
embed["color"] = 8750469 embed["color"] = 8750469
if change["title"].startswith("MediaWiki:Tag-"): # Refresh tag list when tag display name is edited if change["title"].startswith("MediaWiki:Tag-"): # Refresh tag list when tag display name is edited
ctx.client.refresh_internal_data() ctx.client.refresh_internal_data()
link = "{wiki}index.php?title={article}&curid={pageid}&diff={diff}&oldid={oldrev}".format( embed.set_link("{wiki}index.php?title={article}&curid={pageid}&diff={diff}&oldid={oldrev}".format(
wiki=ctx.client.WIKI_SCRIPT_PATH, pageid=change["pageid"], diff=change["revid"], oldrev=change["old_revid"], wiki=ctx.client.WIKI_SCRIPT_PATH, pageid=change["pageid"], diff=change["revid"], oldrev=change["old_revid"],
article=change["title"].replace(" ", "_").replace("%", "%25").replace("\\", "%5C").replace("&", "%26")) article=change["title"].replace(" ", "_").replace("%", "%25").replace("\\", "%5C").replace("&", "%26")))
embed["title"] = "{redirect}{article} ({new}{minor}{bot}{space}{editsize})".format( embed["title"] = "{redirect}{article} ({new}{minor}{bot}{space}{editsize})".format(
redirect="" if "redirect" in change else "", article=change["title"], editsize="+" + str( redirect="" if "redirect" in change else "", article=change["title"], editsize="+" + str(
editsize) if editsize > 0 else editsize, new=_("(N!) ") if action == "new" else "", editsize) if editsize > 0 else editsize, new=_("(N!) ") if action == "new" else "",
@ -70,7 +66,7 @@ class base():
"{wiki}?action=compare&format=json&fromrev={oldrev}&torev={diff}&topst=1&prop=diff".format( "{wiki}?action=compare&format=json&fromrev={oldrev}&torev={diff}&topst=1&prop=diff".format(
wiki=ctx.client.WIKI_API_PATH, diff=change["revid"], oldrev=change["old_revid"] wiki=ctx.client.WIKI_API_PATH, diff=change["revid"], oldrev=change["old_revid"]
), "compare", "*") ), "compare", "*")
except (ServerError): except ServerError:
changed_content = None changed_content = None
if changed_content: if changed_content:
EditDiff = ctx.client.content_parser() EditDiff = ctx.client.content_parser()
@ -95,5 +91,5 @@ class base():
return embed return embed
@formatter.compact(event="edit", mode="compact") @formatter.compact(event="edit", mode="compact")
def compact_edit(self, ctx: Context, change: dict): def compact_edit(ctx: Context, change: dict):
return DiscordMessage() return DiscordMessage()

View file

@ -24,3 +24,6 @@ class Context:
def set_categories(self, cats): def set_categories(self, cats):
self.categories = cats self.categories = cats
def set_parsedcomment(self, parsedcomment: str):
self.parsedcomment = parsedcomment

View file

@ -18,7 +18,9 @@ from typing import Optional, Callable
from src.discord.message import DiscordMessage from src.discord.message import DiscordMessage
from src.configloader import settings from src.configloader import settings
import src.misc import src.misc
import logging
logger = logging.getLogger("src.api.util")
def default_message(event: str, formatter_hooks: dict) -> Callable: def default_message(event: str, formatter_hooks: dict) -> Callable:
"""Returns a method of a formatter responsible for the event or None if such does not exist.""" """Returns a method of a formatter responsible for the event or None if such does not exist."""
@ -38,3 +40,44 @@ def escape_formatting(data: str) -> str:
def create_article_path(article: str) -> str: def create_article_path(article: str) -> str:
"""Takes the string and creates an URL with it as the article name""" """Takes the string and creates an URL with it as the article name"""
return src.misc.WIKI_ARTICLE_PATH.replace("$1", article) return src.misc.WIKI_ARTICLE_PATH.replace("$1", article)
def embed_helper(ctx, message: DiscordMessage, change: dict):
"""Helps in preparing common edit/log fields for events. Sets up:
author, author_url, icon"""
def format_user(change, recent_changes, action):
if "anon" in change:
author_url = create_article_path("Special:Contributions/{user}".format(
user=change["user"].replace(" ", "_"))) # Replace here needed in case of #75
logger.debug("current user: {} with cache of IPs: {}".format(change["user"], recent_changes.map_ips.keys()))
if change["user"] not in list(recent_changes.map_ips.keys()):
contibs = ctx.client.make_api_request(
"{wiki}?action=query&format=json&list=usercontribs&uclimit=max&ucuser={user}&ucstart={timestamp}&ucprop=".format(
wiki=ctx.client.WIKI_API_PATH, user=change["user"], timestamp=change["timestamp"]), "query",
"usercontribs")
if contibs is None:
logger.warning(
"WARNING: Something went wrong when checking amount of contributions for given IP address")
if settings.get("hide_ips", False):
change["user"] = _("Unregistered user")
change["user"] = change["user"] + "(?)"
else:
recent_changes.map_ips[change["user"]] = len(contibs)
logger.debug(
"Current params user {} and state of map_ips {}".format(change["user"], recent_changes.map_ips))
if settings.get("hide_ips", False):
change["user"] = _("Unregistered user")
change["user"] = "{author} ({contribs})".format(author=change["user"], contribs=len(contibs))
else:
logger.debug(
"Current params user {} and state of map_ips {}".format(change["user"], recent_changes.map_ips))
if action in ("edit", "new"):
recent_changes.map_ips[change["user"]] += 1
change["user"] = "{author} ({amount})".format(
author=change["user"] if settings.get("hide_ips", False) is False else _("Unregistered user"),
amount=recent_changes.map_ips[change["user"]])
else:
author_url = create_article_path("User:{}".format(change["user"].replace(" ", "_")))
message.set_author(change["user"], author_url)

View file

@ -245,6 +245,7 @@ def rc_processor(change, changed_categories):
parsed_comment = re.sub(r"(`|_|\*|~|{|}|\|\|)", "\\\\\\1", parsed_comment) parsed_comment = re.sub(r"(`|_|\*|~|{|}|\|\|)", "\\\\\\1", parsed_comment)
else: else:
parsed_comment = _("~~hidden~~") parsed_comment = _("~~hidden~~")
context.set_parsedcomment(parsed_comment)
if "userhidden" in change: if "userhidden" in change:
change["user"] = _("hidden") change["user"] = _("hidden")
if change.get("ns", -1) in settings.get("ignored_namespaces", ()): if change.get("ns", -1) in settings.get("ignored_namespaces", ()):
@ -268,6 +269,7 @@ def abuselog_processing(entry, recent_changes):
abuselog_appearance_mode(entry, recent_changes) abuselog_appearance_mode(entry, recent_changes)
load_extensions()
# Log in and download wiki information # Log in and download wiki information
wiki = Wiki(rc_processor, abuselog_processing) wiki = Wiki(rc_processor, abuselog_processing)
client = src.api.client.Client(formatter_hooks, wiki) client = src.api.client.Client(formatter_hooks, wiki)
@ -306,8 +308,6 @@ if 1 == 2: # additional translation strings in unreachable code
_("autoreview"), _("autopatrol"), _("wiki_guardian"), ngettext("second", "seconds", 1), ngettext("minute", "minutes", 1), ngettext("hour", "hours", 1), ngettext("day", "days", 1), ngettext("week", "weeks", 1), ngettext("month", "months",1), ngettext("year", "years", 1), ngettext("millennium", "millennia", 1), ngettext("decade", "decades", 1), ngettext("century", "centuries", 1)) _("autoreview"), _("autopatrol"), _("wiki_guardian"), ngettext("second", "seconds", 1), ngettext("minute", "minutes", 1), ngettext("hour", "hours", 1), ngettext("day", "days", 1), ngettext("week", "weeks", 1), ngettext("month", "months",1), ngettext("year", "years", 1), ngettext("millennium", "millennia", 1), ngettext("decade", "decades", 1), ngettext("century", "centuries", 1))
# noinspection PyUnreachableCode # noinspection PyUnreachableCode
load_extensions()
if TESTING: if TESTING:
logger.debug("DEBUGGING ") logger.debug("DEBUGGING ")