1
0
Fork 0
mirror of synced 2024-06-02 18:54:41 +12:00

Some fixes in shop: Images, try/except

This commit is contained in:
Dummerle 2021-09-12 21:19:51 +02:00
parent 96266cc6bd
commit 152c1a326d
6 changed files with 78 additions and 56 deletions

View file

@ -160,9 +160,12 @@ def start(args):
if args.debug:
logging.basicConfig(format='[%(name)s] %(levelname)s: %(message)s', level=logging.DEBUG)
logging.getLogger().setLevel(level=logging.DEBUG)
# keep requests quiet
# keep requests, asyncio and pillow quiet
logging.getLogger('requests').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.WARNING)
logging.getLogger("PIL.TiffImagePlugin").setLevel(logging.WARNING)
logging.getLogger("asyncio").setLevel(logging.WARNING)
logging.getLogger("PIL.PngImagePlugin").setLevel(logging.WARNING)
else:
logging.basicConfig(
format='[%(name)s] %(levelname)s: %(message)s',
@ -175,6 +178,6 @@ def start(args):
exit_code = app.exec_()
# if not restart
# restart app
del app
app.deleteLater()
if exit_code != -133742:
break

View file

@ -1,6 +1,7 @@
import logging
import webbrowser
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QFont
from PyQt5.QtWidgets import QWidget, QLabel, QPushButton, QHBoxLayout
from qtawesome import icon
@ -27,6 +28,9 @@ class ShopGameInfo(QWidget, Ui_shop_info):
self.image = ImageLabel()
self.image_stack.addWidget(self.image)
self.image_stack.addWidget(WaitingSpinner())
warn_label = QLabel()
warn_label.setPixmap(icon("fa.warning").pixmap(160, 160).scaled(240, 320, Qt.IgnoreAspectRatio))
self.image_stack.addWidget(warn_label)
self.locale = get_lang()
self.wishlist_button.clicked.connect(self.add_to_wishlist)
@ -51,6 +55,14 @@ class ShopGameInfo(QWidget, Ui_shop_info):
for i in reversed(range(self.req_group_box.layout().count())):
self.req_group_box.layout().itemAt(i).widget().setParent(None)
slug = data["productSlug"]
if not slug:
for mapping in data["offerMappings"]:
if mapping["pageType"] == "productHome":
slug = mapping["pageSlug"]
break
else:
logger.error("Could not get page information")
slug = ""
if "/home" in slug:
slug = slug.replace("/home", "")
self.slug = slug
@ -73,7 +85,8 @@ class ShopGameInfo(QWidget, Ui_shop_info):
is_bundle = True
# init API request
self.api_core.get_game(slug, is_bundle, self.data_received)
if slug:
self.api_core.get_game(slug, is_bundle, self.data_received)
def add_to_wishlist(self):
if not self.in_wishlist:
@ -87,7 +100,23 @@ class ShopGameInfo(QWidget, Ui_shop_info):
if success else self.wishlist_button.setText("Something goes wrong"))
def data_received(self, game):
self.game = ShopGame.from_json(game, self.data)
try:
self.game = ShopGame.from_json(game, self.data)
except Exception as e:
logger.error(str(e))
self.price.setText("Error")
self.req_group_box.setVisible(False)
for img in self.data.get("keyImages"):
if img["type"] in ["DieselStoreFrontWide", "OfferImageWide", "VaultClosed", "ProductLogo"]:
self.image.update_image(img["url"], size=(240, 320))
self.image_stack.setCurrentIndex(0)
break
else:
self.image_stack.setCurrentIndex(2)
self.price.setText("")
self.social_link_gb.setVisible(False)
self.tags.setText("")
return
self.title.setText(self.game.title)
self.price.setFont(QFont())
if self.game.price == "0" or self.game.price == 0:
@ -126,13 +155,14 @@ class ShopGameInfo(QWidget, Ui_shop_info):
self.req_group_box.layout().addWidget(QLabel(self.tr("Could not get requirements")))
if self.game.image_urls.front_tall:
img = self.game.image_urls.front_tall
img_url = self.game.image_urls.front_tall
elif self.game.image_urls.offer_image_tall:
img = self.game.image_urls.offer_image_tall
img_url = self.game.image_urls.offer_image_tall
elif self.game.image_urls.product_logo:
img_url = self.game.image_urls.product_logo
else:
img = ""
self.image.update_image(img, self.game.title, (240, 320))
img_url = ""
self.image.update_image(img_url, self.game.title, (240, 320))
self.image_stack.setCurrentIndex(0)
try:

View file

@ -57,7 +57,7 @@ class GameWidget(QWidget):
self.title = json_info["title"]
for img in json_info["keyImages"]:
if img["type"] in ["DieselStoreFrontWide", "OfferImageWide", "VaultClosed"]:
if img["type"] in ["DieselStoreFrontWide", "OfferImageWide", "VaultClosed", "ProductLogo"]:
if img["type"] == "VaultClosed" and self.title != "Mystery Game":
continue
self.image.update_image(img["url"], json_info["title"], (self.width, int(self.width * 9 / 16)))

View file

@ -7,12 +7,14 @@ from rare.utils.utils import get_lang
class ImageUrlModel:
def __init__(self, front_tall: str = "", offer_image_tall: str = "",
thumbnail: str = "", front_wide: str = "", offer_image_wide: str = ""):
thumbnail: str = "", front_wide: str = "", offer_image_wide: str = "",
product_logo: str = ""):
self.front_tall = front_tall
self.offer_image_tall = offer_image_tall
self.thumbnail = thumbnail
self.front_wide = front_wide
self.offer_image_wide = offer_image_wide
self.product_logo = product_logo
@classmethod
def from_json(cls, json_data: list):
@ -28,6 +30,8 @@ class ImageUrlModel:
tmp.offer_image_tall = item["url"]
elif item["type"] == "OfferImageWide":
tmp.offer_image_wide = item["url"]
elif item["type"] == "ProductLogo":
tmp.product_logo = item["url"]
return tmp

View file

@ -73,6 +73,7 @@ class ShopWidget(QScrollArea, Ui_ShopWidget):
self.api_core.get_free_games(self.add_free_games)
# load wishlist
self.api_core.get_wishlist(self.add_wishlist_items)
# load browse games
self.prepare_request()
def update_wishlist(self):
@ -86,11 +87,15 @@ class ShopWidget(QScrollArea, Ui_ShopWidget):
for game in wishlist:
if not game:
continue
if game["offer"]["price"]["totalPrice"]["discount"] > 0:
w = GameWidget(self.path, game["offer"])
w.show_info.connect(self.show_game.emit)
self.discount_widget.layout().addWidget(w)
discounts += 1
try:
if game["offer"]["price"]["totalPrice"]["discount"] > 0:
w = GameWidget(self.path, game["offer"])
w.show_info.connect(self.show_game.emit)
self.discount_widget.layout().addWidget(w)
discounts += 1
except Exception as e:
logger.warning(str(game) + str(e))
continue
self.discounts_gb.setVisible(discounts > 0)
self.discount_stack.setCurrentIndex(0)
@ -99,22 +104,19 @@ class ShopWidget(QScrollArea, Ui_ShopWidget):
free_games_now = []
coming_free_games = []
for game in free_games:
if game["title"] == "Mystery Game":
coming_free_games.append(game)
continue
try:
if game['price']['totalPrice']['fmtPrice']['discountPrice'] == "0" and game['price']['totalPrice']['fmtPrice']['originalPrice'] != game['price']['totalPrice']['fmtPrice']['discountPrice']:
free_games_now.append(game)
continue
if game["title"] == "Mystery Game":
coming_free_games.append(game)
continue
except KeyError as e:
logger.warning(str(e))
try:
# parse datetime to check if game is next week or now
try:
end_date = datetime.datetime.strptime(
game["promotions"]["upcomingPromotionalOffers"][0]["promotionalOffers"][0]["endDate"],
'%Y-%m-%dT%H:%M:%S.%fZ')
except Exception:
try:
end_date = datetime.datetime.strptime(
game["promotions"]["promotionalOffers"][0]["promotionalOffers"][0]["endDate"],
'%Y-%m-%dT%H:%M:%S.%fZ')
except Exception:
continue
try:
start_date = datetime.datetime.strptime(
game["promotions"]["upcomingPromotionalOffers"][0]["promotionalOffers"][0]["startDate"],
@ -125,16 +127,14 @@ class ShopWidget(QScrollArea, Ui_ShopWidget):
game["promotions"]["promotionalOffers"][0]["promotionalOffers"][0]["startDate"],
'%Y-%m-%dT%H:%M:%S.%fZ')
except Exception as e:
print(e)
logger.warning(str(e))
continue
except TypeError:
print("type error")
continue
if start_date < date < end_date:
free_games_now.append(game)
elif start_date > date:
if start_date > date:
coming_free_games.append(game)
# free games now
for free_game in free_games_now:
@ -143,8 +143,6 @@ class ShopWidget(QScrollArea, Ui_ShopWidget):
self.free_games_now.layout().addWidget(w)
self.free_game_widgets.append(w)
# self.free_games_now.layout().addStretch(1)
# free games next week
for free_game in coming_free_games:
w = GameWidget(self.path, free_game)
@ -222,11 +220,10 @@ class ShopWidget(QScrollArea, Ui_ShopWidget):
if len(self.discounts_gb.layout().children()) > 0:
self.discounts_gb.setVisible(True)
locale = get_lang()
self.game_stack.setCurrentIndex(1)
date = f"[,{datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%dT%X')}.{str(random.randint(0, 999)).zfill(3)}Z]"
browse_model = BrowseModel(locale=locale, date=date, count=20, price=self.price,
browse_model = BrowseModel(locale=self.locale, date=date, count=20, price=self.price,
onSale=self.on_discount.isChecked())
browse_model.tag = "|".join(self.tags)
@ -240,13 +237,7 @@ class ShopWidget(QScrollArea, Ui_ShopWidget):
self.game_widget.setLayout(FlowLayout())
for game in data:
price = game['price']['totalPrice']['fmtPrice']['originalPrice']
discount_price = game['price']['totalPrice']['fmtPrice']['discountPrice']
if price != discount_price:
w = GameWidget(self.path, game, 275)
else:
w = GameWidget(self.path, game, 275)
w = GameWidget(self.path, game, 275)
self.game_widget.layout().addWidget(w)
w.show_info.connect(self.show_game.emit)

View file

@ -264,7 +264,7 @@ class ImageLabel(QLabel):
self.path = cache_dir
self.manager = QtRequestManager("bytes")
def update_image(self, url, name, size: tuple = (240, 320)):
def update_image(self, url, name="", size: tuple = (240, 320)):
self.setFixedSize(*size)
self.img_size = size
self.name = name
@ -282,25 +282,19 @@ class ImageLabel(QLabel):
self.show_image()
def image_ready(self, data):
try:
self.setPixmap(QPixmap())
except RuntimeError:
return
self.setPixmap(QPixmap())
try:
image: Image.Image = Image.open(io.BytesIO(data))
except PIL.UnidentifiedImageError:
print(self.name)
return
image = image.resize((self.img_size[0], self.img_size[1]))
if QSettings().value("cache_images", False, bool):
image.save(os.path.join(self.path, self.name), format="png")
image = image.resize((self.img_size[:2]))
byte_array = io.BytesIO()
image.save(byte_array, format="PNG")
# pixmap = QPixmap.fromImage(ImageQt(image))
pixmap = QPixmap()
pixmap.loadFromData(byte_array.getvalue())
# pixmap = QPixmap.fromImage(ImageQt.ImageQt(image))
pixmap = pixmap.scaled(*self.img_size[:2], Qt.KeepAspectRatioByExpanding)
self.setPixmap(pixmap)
def show_image(self):