Skip to content

Commit

Permalink
Restore last played date
Browse files Browse the repository at this point in the history
  • Loading branch information
flabbamann committed Dec 15, 2021
1 parent a769b09 commit 8b05bd2
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 4 deletions.
18 changes: 15 additions & 3 deletions src/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
from galaxy.api.consts import Platform, LicenseType
from galaxy.api.errors import InvalidCredentials
from galaxy.api.plugin import Plugin, create_and_run_plugin
from galaxy.api.types import Authentication, Game, NextStep, SubscriptionGame, \
Subscription, LicenseInfo
from galaxy.api.types import (Authentication, Game, GameTime, NextStep, SubscriptionGame,
Subscription, LicenseInfo)

from http_client import HttpClient
from http_client import OAUTH_LOGIN_URL, OAUTH_LOGIN_REDIRECT_URL
from psn_client import PSNClient
from psn_client import PSNClient, parse_timestamp

from version import __version__

Expand Down Expand Up @@ -77,6 +77,18 @@ async def get_subscriptions(self) -> List[Subscription]:
async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[List[SubscriptionGame], None]:
yield await self._psn_client.get_subscription_games()

async def prepare_game_times_context(self, game_ids: List[str]) -> Any:
return {game['titleId']: game for game in await self._psn_client.async_get_played_games()}

async def get_game_time(self, game_id: str, context: Any) -> GameTime:
time_played, last_played_game = None, None
try:
game = context[game_id]
last_played_game = parse_timestamp(game['lastPlayedDateTime'])
except KeyError as e:
logger.debug(f'KeyError: {e}')
return GameTime(game_id, time_played, last_played_game)

async def get_owned_games(self):
def game_parser(title):
return Game(
Expand Down
9 changes: 8 additions & 1 deletion src/psn_client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import logging
from datetime import datetime, timezone
from functools import partial
from typing import List, NewType

Expand Down Expand Up @@ -34,6 +35,12 @@
UnixTimestamp = NewType("UnixTimestamp", int)


def parse_timestamp(earned_date) -> UnixTimestamp:
date_format = "%Y-%m-%dT%H:%M:%S.%fZ" if '.' in earned_date else "%Y-%m-%dT%H:%M:%SZ"
dt = datetime.strptime(earned_date, date_format)
dt = datetime.combine(dt.date(), dt.time(), timezone.utc)
return UnixTimestamp(int(dt.timestamp()))

class PSNClient:
def __init__(self, http_client):
self._http_client = http_client
Expand Down Expand Up @@ -125,7 +132,7 @@ def games_parser(response):
try:
games = response['data']['gameLibraryTitlesRetrieve']['games']
return [
{"titleId": title["titleId"], "name": title["name"]} for title in games
{"titleId": title["titleId"], "name": title["name"], "lastPlayedDateTime": title["lastPlayedDateTime"]} for title in games
] if games else []
except (KeyError, TypeError) as e:
raise UnknownBackendResponse(e)
Expand Down
62 changes: 62 additions & 0 deletions tests/test_game_time.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
from unittest.mock import Mock

import pytest
from galaxy.api.types import GameTime


@pytest.fixture()
def played_games_backend_response():
return {
"data": {
"gameLibraryTitlesRetrieve": {
"__typename": "GameList",
"games": [
{
"__typename": "GameLibraryTitle",
"lastPlayedDateTime": "2021-03-06T16:29:22.490Z",
"name": "Call of Duty®: Modern Warfare®",
"platform": "PS4",
"titleId": "GAME_ID_1",
},
{
"__typename": "GameLibraryTitle",
"lastPlayedDateTime": "1970-01-01T00:00:01.000Z",
"name": "Call of Duty®: Modern Warfare®",
"platform": "PS4",
"titleId": "GAME_ID_2",
},
],
}
}
}


@pytest.mark.asyncio
async def test_prepare_game_times_context(
http_get, authenticated_plugin, played_games_backend_response
):
http_get.return_value = played_games_backend_response

result = await authenticated_plugin.prepare_game_times_context(Mock(list))
for title in played_games_backend_response["data"]["gameLibraryTitlesRetrieve"]["games"]:
game = result[title["titleId"]]
assert game["name"] is not None
assert game["name"] == title["name"]
assert game["titleId"] is not None
assert game["titleId"] == title["titleId"]
assert game["lastPlayedDateTime"] is not None
assert game["lastPlayedDateTime"] == title["lastPlayedDateTime"]


@pytest.mark.asyncio
async def test_getting_game_time(
http_get, authenticated_plugin, played_games_backend_response
):
http_get.return_value = played_games_backend_response
ctx = await authenticated_plugin.prepare_game_times_context(Mock(list))
assert GameTime("GAME_ID_1", None, 1615048162) == await authenticated_plugin.get_game_time(
"GAME_ID_1", ctx
)
assert GameTime("GAME_ID_2", None, 1) == await authenticated_plugin.get_game_time(
"GAME_ID_2", ctx
)

1 comment on commit 8b05bd2

@PaulTheRNewb
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lack the technical ability to review the code, but I figured out how to manually cut/paste to replace two of the files, and add the third to the tests directory. Rebooted GOG and last played time is now accurately reflected for my Playstation games. Thank you VERY much for this.

Please sign in to comment.