Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve get_names #24

Merged
merged 3 commits into from
Jan 31, 2022
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ Improvements:
- [x] `get_uuid` returns the uuid
- [x] `get_uuids` returns a dict<str, str>
- [x] `get_status` returns a list of ServiceStatus
- [ ] `get_names` returns a list of tuple
- [x] `get_names` returns a sorted list of NameInfo

### Authentication (mojang.api.auth.*)

Expand Down
43 changes: 24 additions & 19 deletions mojang/api/base.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
import base64
import datetime as dt
import json
import typing
from typing import Dict, Iterable, List, Optional

import requests

from ..exceptions import InvalidName
from .structures.base import NameInfo, NameInfoList
from .structures.base import NameInfo, ServiceStatus
from .structures.profile import UnauthenticatedProfile
from .structures.session import Cape, Skin
from .utils import helpers, urls

ServiceStatus = typing.NamedTuple(
"ServiceStatus", [("name", str), ("status", str)]
)


def get_status() -> List[ServiceStatus]:
"""Get the status of Mojang's services
Expand Down Expand Up @@ -112,36 +107,46 @@ def get_uuids(usernames: Iterable[str]) -> Dict[str, Optional[str]]:
return ret


def get_names(uuid: str) -> Optional[NameInfoList]:
def get_names(uuid: str) -> List[NameInfo]:
"""Get the user's name history

:param str uuid: The user's uuid

:Example:

>>> import mojang
>>> mojang.get_names('65a8dd127668422e99c2383a07656f7a)
(
>>> mojang.get_names('65a8dd127668422e99c2383a07656f7a'')
[
NameInfo(name='piewdipie', changed_to_at=None),
NameInfo(name='KOtMotros', changed_to_at=datetime.datetime(2020, 3, 4, 17, 45, 26))
)
]
"""
response = requests.get(urls.api_name_history(uuid))
code, data = helpers.err_check(response, (400, ValueError))

if code == 204:
return None

_names = []
for item in data:
def _parse_item(item: dict):
changed_to_at = None
if "changedToAt" in item.keys():
changed_to_at = dt.datetime.fromtimestamp(
item["changedToAt"] / 1000
)
_names.append(NameInfo(name=item["name"], changed_to_at=changed_to_at))

return NameInfoList(_names)
return NameInfo(name=item["name"], changed_to_at=changed_to_at)

response = requests.get(urls.api_name_history(uuid))
code, data = helpers.err_check(response, (400, ValueError))

if code == 204:
return []

# Names are sorted newer to older
_names = [_parse_item(item) for item in data]
_tosort = [
_names.pop(_names.index(item))
for item in _names.copy()
if item.changed_to_at is not None
]
_tosort.sort(key=lambda i: i.changed_to_at, reverse=True)

return _tosort + _names


def get_profile(uuid: str) -> Optional[UnauthenticatedProfile]:
Expand Down
7 changes: 4 additions & 3 deletions mojang/api/ext/_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

from .. import session
from ..auth import microsoft, security, yggdrasil
from ..structures.profile import Cape, NameInfoList, Skin
from ..structures.profile import Cape, Skin
from ..structures.base import NameInfo
from ..structures.auth import ChallengeInfo


Expand Down Expand Up @@ -35,7 +36,7 @@ def __init__(self, access_token: str, refresh_token: str) -> None:
self.__uuid = None
self.__is_legacy = False
self.__is_demo = False
self.__names = None
self.__names: List[NameInfo] = []
self.__skins = None
self.__capes = None

Expand Down Expand Up @@ -72,7 +73,7 @@ def is_demo(self) -> bool:
return self.__is_demo

@property
def names(self) -> Optional[NameInfoList]:
def names(self) -> List[NameInfo]:
return self.__names

@property
Expand Down
41 changes: 8 additions & 33 deletions mojang/api/structures/base.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,12 @@
import typing
import datetime as dt
from typing import NamedTuple, Optional, Tuple, Union


# UUID and Name
class NameInfo(NamedTuple):
"""
:var str name: The player name
:var datetime.datetime changed_to_at: When it's was changed to
"""
ServiceStatus = typing.NamedTuple(
"ServiceStatus", [("name", str), ("status", str)]
)

name: str
changed_to_at: Optional[dt.datetime]


class NameInfoList(Tuple[NameInfo, ...]):
@property
def current(self) -> NameInfo:
"""Returns the most recent name"""
if len(self) == 1:
return self[0]

_max = self[0]
for n in self[1:]:
if (n.changed_to_at is not None) and (
_max.changed_to_at is None
or n.changed_to_at > _max.changed_to_at
):
_max = n

return _max

@property
def first(self) -> NameInfo:
"""Returns the first name"""
first = list(filter(lambda n: n.changed_to_at is None, self))
return first[0]
NameInfo = typing.NamedTuple(
"NameInfo",
[("name", str), ("changed_to_at", typing.Optional[dt.datetime])],
)
16 changes: 8 additions & 8 deletions mojang/api/structures/profile.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from typing import List, Optional
from .base import NameInfoList
from .base import NameInfo
from .session import Skin, Cape


Expand All @@ -18,7 +18,7 @@ def __init__(
uuid: str,
is_legacy: bool,
is_demo: bool,
names: Optional[NameInfoList],
names: List[NameInfo],
) -> None:
self.__name = name
self.__uuid = uuid
Expand All @@ -33,7 +33,7 @@ def __hash__(self) -> int:
self.__uuid,
self.__is_legacy,
self.__is_demo,
self.__names,
tuple(self.__names),
)
)

Expand All @@ -60,7 +60,7 @@ def is_demo(self) -> bool:
return self.__is_demo

@property
def names(self) -> Optional[NameInfoList]:
def names(self) -> List[NameInfo]:
return self.__names


Expand All @@ -76,7 +76,7 @@ def __init__(
uuid: str,
is_legacy: bool,
is_demo: bool,
names: Optional[NameInfoList],
names: List[NameInfo],
skin: Optional[Skin],
cape: Optional[Cape],
) -> None:
Expand All @@ -91,7 +91,7 @@ def __hash__(self) -> int:
self.uuid,
self.is_legacy,
self.is_demo,
self.names,
tuple(self.names),
self.__skin,
self.__cape,
)
Expand Down Expand Up @@ -121,7 +121,7 @@ def __init__(
uuid: str,
is_legacy: bool,
is_demo: bool,
names: Optional[NameInfoList],
names: List[NameInfo],
skins: List[Skin],
capes: List[Cape],
) -> None:
Expand All @@ -136,7 +136,7 @@ def __hash__(self) -> int:
self.uuid,
self.is_legacy,
self.is_demo,
self.names,
tuple(self.names),
self.__skins,
self.__capes,
)
Expand Down
8 changes: 4 additions & 4 deletions tests/test_mojang_names.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import unittest

import mojang
from mojang.api.structures.base import NameInfo, NameInfoList
from mojang.api.structures.base import NameInfo
from mojang.exceptions import InvalidName


Expand All @@ -13,11 +13,11 @@ def setUp(self) -> None:
self.unkown = mojang.get_names("069a79f444e94726a5befca90e38aaf6")

def test_existent_names(self):
self.assertEqual(self.notch, NameInfoList([NameInfo("Notch", None)]))
self.assertEqual(self.jeb_, NameInfoList([NameInfo("jeb_", None)]))
self.assertEqual(self.notch, [NameInfo("Notch", None)])
self.assertEqual(self.jeb_, [NameInfo("jeb_", None)])

def test_unexistent_names(self):
self.assertEqual(self.unkown, None)
self.assertEqual(self.unkown, [])

def test_invalid_names(self):
self.assertRaises(ValueError, mojang.get_names, "thisisnotauuid")
6 changes: 3 additions & 3 deletions tests/test_mojang_user.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import unittest

import mojang
from mojang.api.structures.base import NameInfo, NameInfoList
from mojang.api.base import NameInfo
from mojang.api.structures.profile import UnauthenticatedProfile
from mojang.api.structures.session import Cape, Skin
from mojang.exceptions import InvalidName
Expand All @@ -21,7 +21,7 @@ def test_existent_user(self):
"069a79f444e94726a5befca90e38aaf5",
False,
False,
NameInfoList([NameInfo("Notch", None)]),
[NameInfo("Notch", None)],
Skin(
"http://textures.minecraft.net/texture/292009a4925b58f02c77dadc3ecef07ea4c7472f64e0fdc32ce5522489362680",
"classic",
Expand All @@ -37,7 +37,7 @@ def test_existent_user(self):
"853c80ef3c3749fdaa49938b674adae6",
False,
False,
NameInfoList([NameInfo("jeb_", None)]),
[NameInfo("jeb_", None)],
Skin(
"http://textures.minecraft.net/texture/7fd9ba42a7c81eeea22f1524271ae85a8e045ce0af5a6ae16c6406ae917e68b5",
"classic",
Expand Down