Skip to content

Instantly share code, notes, and snippets.

@loathingKernel
Created April 4, 2023 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loathingKernel/ed280df692f3c1419495068fa55d6f53 to your computer and use it in GitHub Desktop.
Save loathingKernel/ed280df692f3c1419495068fa55d6f53 to your computer and use it in GitHub Desktop.
from datetime import datetime
from dataclasses import dataclass, field
from typing import List, Dict, Union, Any, Type, TypeVar
class _Unset:
def __bool__(self) -> bool:
return False
UNSET: _Unset = _Unset()
T = TypeVar("T")
Unset = Union[_Unset, T]
@dataclass
class ImageUrlModel:
type: Unset[str] = UNSET
url: Unset[str] = UNSET
def to_dict(self) -> Dict[str, Any]:
tmp: Dict[str, Any] = {}
tmp.update({})
if self.type is not UNSET:
tmp["type"] = self.type
if self.url is not UNSET:
tmp["url"] = self.url
return tmp
@classmethod
def from_dict(cls: Type["ImageUrlModel"], src: Dict[str, Any]) -> "ImageUrlModel":
d = src.copy()
type = d.pop("type", UNSET)
url = d.pop("url", UNSET)
tmp = cls(
type=type,
url=url,
)
return tmp
@dataclass
class KeyImagesModel:
key_images: Unset[List[ImageUrlModel]] = UNSET
def __getitem__(self, item):
return self.key_images[item]
def to_list(self) -> List[Dict[str, Any]]:
items: Unset[List[Dict[str, Any]]] = UNSET
if not isinstance(self.key_images, Unset):
items = []
for image_url in self.key_images:
item = image_url.to_dict()
items.append(item)
return items
@classmethod
def from_list(cls: Type["KeyImagesModel"], src: List[Dict]):
d = src.copy()
key_images = []
for item in d:
image_url = ImageUrlModel.from_dict(item)
key_images.append(image_url)
tmp = cls(key_images)
return tmp
def available_tall(self) -> List[ImageUrlModel]:
tall_types = ["DieselStoreFrontTall", "OfferImageTall", "Thumbnail", "ProductLogo"]
tall_images = filter(lambda img: img.type in tall_types, self.key_images)
tall_images = sorted(tall_images, key=lambda x: tall_types.index(x.type))
return tall_images
def available_wide(self) -> List[ImageUrlModel]:
wide_types = ["DieselStoreFrontWide", "OfferImageWide", "VaultClosed", "ProductLogo"]
wide_images = filter(lambda img: img.type in wide_types, self.key_images)
wide_images = sorted(wide_images, key=lambda x: wide_types.index(x.type))
return wide_images
def for_dimensions(self, w: int, h: int) -> ImageUrlModel:
if w > h:
return self.available_wide()[0]
else:
return self.available_tall()[0]
# lk: Unimplemented models are mapped to Dict
MappingsModel = Dict
CategoryModel = Dict
CustomAttributeModel = Dict
ItemModel = Dict
PriceModel = Dict
SellerModel = Dict
OfferMappingModel = Dict
TagModel = Dict
PromotionsModel = Dict
@dataclass
class GameModel:
catalog_ns: Unset[MappingsModel] = UNSET
categories: Unset[List[CategoryModel]] = UNSET
custom_attributes: Unset[List[CustomAttributeModel]] = UNSET
description: Unset[str] = UNSET
effective_date: Unset[datetime] = UNSET
expiry_date: Unset[datetime] = UNSET
id: Unset[str] = UNSET
is_code_redemption_only: Unset[bool] = UNSET
items: Unset[List[ItemModel]] = UNSET
key_images: Unset[KeyImagesModel] = UNSET
namespace: Unset[str] = UNSET
offer_mappings: Unset[List[OfferMappingModel]] = UNSET
offer_type: Unset[str] = UNSET
price: Unset[PriceModel] = UNSET
product_slug: Unset[str] = UNSET
promotions: Unset[PromotionsModel] = UNSET
seller: Unset[SellerModel] = UNSET
status: Unset[str] = UNSET
tags: Unset[List[TagModel]] = UNSET
title: Unset[str] = UNSET
url: Unset[str] = UNSET
url_slug: Unset[str] = UNSET
viewable_date: Unset[datetime] = UNSET
unmapped: Dict[str, Any] = field(default_factory=dict)
@classmethod
def from_dict(cls: Type["GameModel"], src: Dict[str, Any]) -> "GameModel":
if isinstance(api_data, list):
for product in api_data:
if product["_title"] == "home":
api_data = product
break
if "pages" in api_data.keys():
for page in api_data["pages"]:
if page["_slug"] == "home":
api_data = page
break
tmp = cls()
if search_data:
tmp.title = search_data.get("title", "Fail")
tmp.id = search_data.get("id")
tmp.key_images = KeyImagesModel.from_list(search_data["keyImages"])
if not tmp.developer:
for i in search_data["customAttributes"]:
if i["key"] == "developerName":
tmp.developer = i["value"]
tmp.price = search_data["price"]["totalPrice"]["fmtPrice"]["originalPrice"]
tmp.discount_price = search_data["price"]["totalPrice"]["fmtPrice"][
"discountPrice"
]
tmp.namespace = search_data["namespace"]
tmp.offer_id = search_data["id"]
if api_data:
links = api_data["data"]["socialLinks"]
tmp.links = []
for item in links:
if item.startswith("link"):
tmp.links.append(tuple((item.replace("link", ""), links[item])))
tmp.available_voice_langs = api_data["data"]["requirements"].get(
"languages", "Failed"
)
tmp.reqs = {}
for i, system in enumerate(api_data["data"]["requirements"].get("systems", [])):
try:
tmp.reqs[system["systemType"]] = {}
except KeyError:
continue
for req in system["details"]:
try:
tmp.reqs[system["systemType"]][req["title"]] = (
req["minimum"],
req["recommended"],
)
except KeyError:
pass
tmp.publisher = api_data["data"]["meta"].get("publisher", "")
tmp.developer = api_data["data"]["meta"].get("developer", "")
tmp.tags = [
i.replace("_", " ").capitalize()
for i in api_data["data"]["meta"].get("tags", [])
]
return tmp
@dataclass
class WishlistGameModel:
created: Unset[datetime] = UNSET
id: Unset[str] = UNSET
namespace: Unset[str] = UNSET
offer: Unset[Dict] = UNSET
offer_id: Unset[str] = UNSET
order: Unset[Any] = UNSET
updated: Unset[datetime] = UNSET
unmapped: Dict[str, Any] = field(default_factory=dict)
@classmethod
def from_dict(cls: Type["WishlistGameModel"], src: Dict[str, Any]) -> "WishlistGameModel":
d = src.copy()
created = datetime.fromisoformat(x[:-1]) if (x := d.pop("created", "")) else UNSET
id = x if (x := d.pop("id", "")) else UNSET
namespace = x if (x := d.pop("namespace", "")) else UNSET
offer = x if (x := d.pop("offer", {})) else UNSET
offer_id = x if (x := d.pop("offerId", "")) else UNSET
order = x if (x := d.pop("order", "")) else UNSET
updated = datetime.fromisoformat(x[:-1]) if (x := d.pop("updated", "")) else UNSET
tmp = cls(
created=created,
id=id,
namespace=namespace,
offer=offer,
offer_id=offer_id,
order=order,
updated=updated
)
tmp.unmapped = d
return tmp
@dataclass
class PagingModel:
count: Unset[int] = UNSET
total: Unset[int] = UNSET
unmapped: Dict[str, Any] = field(default_factory=dict)
@classmethod
def from_dict(cls: Type["PagingModel"], src: Dict[str, Any]) -> "PagingModel":
d = src.copy()
count = d.pop("count", UNSET)
total = d.pop("total", UNSET)
tmp = cls(
count=count,
total=total,
)
tmp.unmapped = d
return tmp
@dataclass
class SearchStoreModel:
elements: Unset[List[GameModel]] = UNSET
paging: Unset[PagingModel] = UNSET
unmapped: Dict[str, Any] = field(default_factory=dict)
@classmethod
def from_dict(cls: Type["SearchStoreModel"], src: Dict[str, Any]) -> "SearchStoreModel":
d = src.copy()
_elements = d.pop("elements", [])
elements = [] if _elements else UNSET
for item in _elements:
elem = GameModel.from_dict(item)
elements.append(elem)
paging = PagingModel.from_dict(x) if (x := d.pop("paging", {})) else UNSET
tmp = cls(
elements=elements,
paging=paging,
)
tmp.unmapped = d
return tmp
@dataclass
class CatalogModel:
search_store: Unset[SearchStoreModel] = UNSET
unmapped: Dict[str, Any] = field(default_factory=dict)
@classmethod
def from_dict(cls: Type["CatalogModel"], src: Dict[str, Any]) -> "CatalogModel":
d = src.copy()
search_store = SearchStoreModel.from_dict(x) if (x := d.pop("searchStore", {})) else UNSET
tmp = cls(
search_store=search_store,
)
tmp.unmapped = d
return tmp
@dataclass
class WishlistItemsModel:
elements: Unset[List[WishlistGameModel]] = UNSET
paging: Unset[PagingModel] = UNSET
unmapped: Dict[str, Any] = field(default_factory=dict)
@classmethod
def from_dict(cls: Type["WishlistItemsModel"], src: Dict[str, Any]) -> "WishlistItemsModel":
d = src.copy()
_elements = d.pop("elements", [])
elements = [] if _elements else UNSET
for item in _elements:
elem = WishlistGameModel.from_dict(item)
elements.append(elem)
_paging = d.pop("paging", {})
paging = PagingModel.from_dict(x) if (x := d.pop("paging", {})) else UNSET
tmp = cls(
elements=elements,
paging=paging,
)
tmp.unmapped = d
return tmp
@dataclass
class WishlistModel:
wishlist_items: Unset[WishlistItemsModel] = UNSET
unmapped: Dict[str, Any] = field(default_factory=dict)
@classmethod
def from_dict(cls: Type["WishlistModel"], src: Dict[str, Any]) -> "WishlistModel":
d = src.copy()
wishlist_items = WishlistItemsModel.from_dict(x) if (x := d.pop("wishlistItems", {})) else UNSET
tmp = cls(
wishlist_items=wishlist_items,
)
tmp.unmapped = d
return tmp
@dataclass
class DataModel:
catalog: Unset[CatalogModel] = UNSET
wishlist: Unset[WishlistModel] = UNSET
unmapped: Dict[str, Any] = field(default_factory=dict)
@classmethod
def from_dict(cls: Type["DataModel"], src: Dict[str, Any]) -> "DataModel":
d = src.copy()
catalog = CatalogModel.from_dict(x) if (x := d.pop("Catalog", {})) else UNSET
tmp = cls(
catalog=catalog,
)
tmp.unmapped = d
return tmp
@dataclass
class ErrorModel:
unmapped: Dict[str, Any] = field(default_factory=dict)
@classmethod
def from_dict(cls: Type["ErrorModel"], src: Dict[str, Any]) -> "ErrorModel":
d = src.copy()
tmp = cls()
tmp.unmapped = d
return tmp
@dataclass
class ExtensionsModel:
unmapped: Dict[str, Any] = field(default_factory=dict)
@classmethod
def from_dict(cls: Type["ExtensionsModel"], src: Dict[str, Any]) -> "ExtensionsModel":
d = src.copy()
tmp = cls()
tmp.unmapped = d
return tmp
@dataclass
class ResponseModel:
data: Unset[DataModel] = UNSET
errors: Unset[List[ErrorModel]] = UNSET
extensions: Unset[ExtensionsModel] = UNSET
unmapped: Dict[str, Any] = field(default_factory=dict)
@classmethod
def from_dict(cls: Type["ResponseModel"], src: Dict[str, Any]) -> "ResponseModel":
d = src.copy()
data = DataModel.from_dict(x) if (x := d.pop("data", {})) else UNSET
_errors = d.pop("errors", [])
errors = _errors if _errors else UNSET
for item in _errors:
error = ErrorModel.from_dict(item)
errors.append(error)
extensions = ExtensionsModel.from_dict(x) if (x := d.pop("extensions", {})) else UNSET
tmp = cls(
data=data,
errors=errors,
extensions=extensions
)
tmp.unmapped = d
return tmp
@dataclass
class BrowseModel:
category: str = "games/edition/base|bundles/games|editors|software/edition/base"
count: int = 30
language_code: str = "en"
country_code: str = "US"
keywords: str = ""
sortDir: str = "DESC"
start: int = 0
tag: str = ""
withMapping: bool = True
withPrice: bool = True
date: str = (
f"[,{datetime.strftime(datetime.now(), '%Y-%m-%dT%H:%M:%S')}.420Z]"
)
price: str = ""
onSale: bool = False
def __post_init__(self):
self.locale = f"{self.language_code}-{self.country_code}"
@property
def __dict__(self):
payload = {
"count": self.count,
"category": self.category,
"allowCountries": self.country_code,
"namespace": "",
"sortBy": "releaseDate",
"sortDir": self.sortDir,
"start": self.start,
"keywords": self.keywords,
"tag": self.tag,
"priceRange": self.price,
"releaseDate": self.date,
"withPrice": self.withPrice,
"locale": self.locale,
"country": self.country_code,
}
if self.price == "free":
payload["freeGame"] = True
payload.pop("priceRange")
elif self.price.startswith("<price>"):
payload["priceRange"] = self.price.replace("<price>", "")
if self.onSale:
payload["onSale"] = True
if self.price:
payload["effectiveDate"] = self.date
else:
payload.pop("priceRange")
return payload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment