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

feat: add check_product_voucher function #29

Merged
merged 7 commits into from
Feb 12, 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 @@ -70,7 +70,7 @@ Improvements:
### Session API (mojang.api.session)

New features:
- [ ] `check_giftcode` : Check if redeem code is valid
- [x] `check_product_voucher` : Check if a product voucher is valid
- [ ] `redeem` : Redeem a gift code
- [ ] `check_username` : Check if a username is available

Expand Down
29 changes: 29 additions & 0 deletions mojang/api/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,35 @@
from .structures.session import Cape, NameChange, Skin


def check_product_voucher(access_token: str, voucher: str) -> bool:
"""Check if a voucher is available.

:param str access_token: The session access token
:param str voucher: The code you want to check

:raises Unauthorized: if the access token is invalid
:raises ValueError: if the voucher is not a real code

:Example:

>>> from mojang.api import session
>>> session.check_product_voucher('ACCESS_TOKEN', 'JHRD2-HWGTY-WP3MW-QR4MC-CGGHZ')
True
"""
headers = helpers.get_headers(bearer=access_token)
response = requests.get(
urls.api_session_product_voucher(voucher), headers=headers
)
code, data = helpers.err_check(
response, (401, Unauthorized), use_defaults=False
)

if code == 404 and "errorMessage" not in data:
raise ValueError("Invalid voucher")

return code == 200


def get_user_name_change(access_token: str) -> NameChange:
"""Return if user can change name and when it was created

Expand Down
3 changes: 3 additions & 0 deletions mojang/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
)

# URLs for Authenticated users
api_session_product_voucher = (
lambda voucher: f"https://api.minecraftservices.com/productvoucher/{voucher}"
)
api_session_name_change = (
"https://api.minecraftservices.com/minecraft/profile/namechange"
)
Expand Down
47 changes: 47 additions & 0 deletions tests/session/mock_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,14 @@ def __init__(
access_token: str,
unavailable_names: list = [],
valid_cape_ids=[],
valid_vouchers=[],
used_vouchers=[],
) -> None:
self._access_token = access_token
self._unavailable_names = unavailable_names
self._valid_cape_ids = valid_cape_ids
self._valid_vouchers = valid_vouchers
self._used_vouchers = used_vouchers

def _is_token_valid(self, headers: dict):
authorization = headers.get("authorization", None)
Expand All @@ -23,6 +27,49 @@ def _is_token_valid(self, headers: dict):
token = str(authorization).split(" ")[1]
return token == self._access_token

def product_voucher(self, url, **kwargs):
voucher = urlparse(url).path.split("/")[-1]
response = Response()
if not self._is_token_valid(kwargs.get("headers", {})):
response.status_code = 401
elif voucher not in self._valid_vouchers:
response.status_code = 404
response._content = json.dumps(
{
"path": "/productvoucher/:voucher",
"errorType": "NOT_FOUND",
"error": "NOT_FOUND",
}
).encode("utf-8")
response.encoding = "utf-8"
elif voucher in self._used_vouchers:
response.status_code = 404
response._content = json.dumps(
{
"path": "/productvoucher/:voucher",
"errorType": "NOT_FOUND",
"error": "NOT_FOUND",
"errorMessage": "The server has not found anything matching the request URI",
"developerMessage": "The server has not found anything matching the request URI",
}
).encode("utf-8")
response.encoding = "utf-8"
else:
response.status_code = 200
response._content = json.dumps(
{
"voucherInfo": {
"code": "00000-00000-00000-00000-00000",
"productVariant": "minecraft",
"status": "ACTIVE",
},
"productRedeemable": True,
}
).encode("utf-8")
response.encoding = "utf-8"

return response

def user_name_change(self, *args, **kwargs):
response = Response()
if not self._is_token_valid(kwargs.get("headers", {})):
Expand Down
49 changes: 49 additions & 0 deletions tests/session/test_mojang_product_voucher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import datetime as dt
import unittest
from unittest import mock

from mojang.api import session
from mojang.exceptions import Unauthorized

from .mock_server import MockSessionServer

VALID_ACCESS_TOKEN = "MY_ACCESS_TOKEN"
INVALID_ACCESS_TOKEN = "NOT_MY_ACCESS_TOKEN"

mock_server = MockSessionServer(
VALID_ACCESS_TOKEN,
valid_vouchers=["8901854197", "JHRD2-HWGTY-WP3MW-QR4MC-CGGHZ"],
used_vouchers=["JHRD2-HWGTY-WP3MW-QR4MC-CGGHZ"],
)


class TestMojangProductVoucher(unittest.TestCase):
@mock.patch("requests.get", side_effect=mock_server.product_voucher)
def test_invalid_voucher(self, mock_get: mock.MagicMock):
self.assertRaises(
ValueError,
session.check_product_voucher,
VALID_ACCESS_TOKEN,
"12345",
)

@mock.patch("requests.get", side_effect=mock_server.product_voucher)
def test_used_voucher(self, mock_get: mock.MagicMock):
res = session.check_product_voucher(
VALID_ACCESS_TOKEN, "JHRD2-HWGTY-WP3MW-QR4MC-CGGHZ"
)
self.assertEqual(res, False)

@mock.patch("requests.get", side_effect=mock_server.product_voucher)
def test_unused_voucher(self, mock_get: mock.MagicMock):
res = session.check_product_voucher(VALID_ACCESS_TOKEN, "8901854197")
self.assertEqual(res, True)

@mock.patch("requests.get", side_effect=mock_server.product_voucher)
def test_invalid_token(self, mock_get: mock.MagicMock):
self.assertRaises(
Unauthorized,
session.check_product_voucher,
INVALID_ACCESS_TOKEN,
"8901854197",
)