Refactor editor_global_userinfo
Refactoring editor_global_userinfo so that it also queries by wp_sub
when the query by username does not return user information
@@ -13,11 +13,42 @@ def editor_global_userinfo(
wp_username: str, wp_sub: typing.Optional[int], strict: bool
):
guiuser = urllib.parse.quote(wp_username)
- query = "{endpoint}?action=query&meta=globaluserinfo&guiuser={guiuser}&guiprop=editcount|merged&format=json&formatversion=2".format(
- endpoint=settings.TWLIGHT_API_PROVIDER_ENDPOINT, guiuser=guiuser
- )
- results = json.loads(urllib.request.urlopen(query).read())
+ # Trying to get global user info with the username
+ results = _get_user_info_request("guiuser", guiuser)
+
+ try:
+ global_userinfo = results["query"]["globaluserinfo"]
+ # If the user isn't found global_userinfo contains the empty key "missing"
+ if "missing" in global_userinfo:
+ # querying again, this time using wp_sub
+ results = _get_user_info_request("guiid", wp_sub)
+ global_userinfo = results["query"]["globaluserinfo"]
+ if strict:
+ # Verify that the numerical account ID matches, not just the user's handle.
+ assert isinstance(wp_sub, int)
+ assert wp_sub == global_userinfo["id"]
+ except (KeyError, AssertionError):
+ global_userinfo = None
+ logger.exception(f"Could not fetch global_userinfo for User {guiuser}")
+ return global_userinfo
+
+
+def _get_user_info_request(wp_param_name, wp_param):
"""
+ This function queries the mediawiki api to get users' Wikipedia information
+
+ Parameters
+ ----------
+ wp_param_name : str
+ The name of the parameter we want to query by. Can be guiuser or guiid
+ wp_param : str
+ The value of that parameter we want to query by wp_username or wp_sub.
+
+ Returns
+ -------
+ dict
+ A dictionary like the one below or a dictionary with a "missing" key
+
Expected data:
{
"batchcomplete": true,
@@ -47,19 +78,11 @@ def editor_global_userinfo(
}
}
"""
-
- try:
- global_userinfo = results["query"]["globaluserinfo"]
- # If the user isn't found global_userinfo contains the empty key "missing"
- assert "missing" not in global_userinfo
- if strict:
- # Verify that the numerical account ID matches, not just the user's handle.
- assert isinstance(wp_sub, int)
- assert wp_sub == global_userinfo["id"]
- except (KeyError, AssertionError):
- global_userinfo = None
- logger.exception(f"Could not fetch global_userinfo for User {guiuser}")
- return global_userinfo
+ endpoint = settings.TWLIGHT_API_PROVIDER_ENDPOINT
+ query = "{endpoint}?action=query&meta=globaluserinfo&{wp_param_name}={wp_param}&guiprop=editcount|merged&format=json&formatversion=2".format(
+ endpoint=endpoint, wp_param_name=wp_param_name, wp_param=wp_param
+ )
+ return json.loads(urllib.request.urlopen(query).read())
def editor_reg_date(identity, global_userinfo):
