diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f41865d --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +bin +obj +*.suo +*.user \ No newline at end of file diff --git a/README.md b/README.md index 521846c..3998e2f 100644 --- a/README.md +++ b/README.md @@ -1,45 +1,67 @@ -# galaxy-integration-n64-RetroArch- -N64 RetroArch integration for GOG Galaxy 2.0 +# Retro GOG +RetroArch integrations for GOG Galaxy 2.0 -# [If you want the integration to work, please read the tutorial!](https://github.com/Riku55/galaxy-integration-n64-RetroArch-#tutorial) +## About +The goal of this project is to integrate all retro platforms that are supported by both [GOG Galaxy 2.0](https://www.gog.com/galaxy) and [RetroArch](https://retroarch.com/) so that games can easily be launched from GOG with minimal user configuration. GOG Galaxy will track user's play time as well as achievement status from [RetroAchievements.org](https://retroachievements.org). These integrations are designed for and have only been tested with Windows. -This integration is still work in progress, but it's core features are working and the worst bugs are removed, so try it out if you'd like to. -Thanks to AHCoder for using his PS2 integration as base for this one. Also thanks to several people on the GOG Discord for helping me out with some problems. +This project is currently a work in progress. Bugs may be present. Created with the Galaxy API: https://github.com/gogcom/galaxy-integrations-python-api +Forked from Riku55's N64 Integration Plugin: https://github.com/Riku55/galaxy-integration-n64-RetroArch- + #### Working Features: -- Add N64 Roms into the galaxy 2.0 library -- Launch N64 Roms with RetroArch via Galaxy 2.0 +- Add and launch retro games to your GOG Galaxy 2.0 library - Import RetroArch Playtime -- Use Mupen64Plus_Next or ParaLLEl core, change it in user_config.py +- Configuration wizard for easy installation #### Future Features: -- MacOS Support (help from MacOS Users would be appreciated) -- Add GUI (cef) for better usability -- Add retroachievements via API -- More launch options -- Support for various emulators (might be another repository then) -- Add more platforms supported by RetroArch (if Galaxy should support more than one platform per integration in the future. Currently working on PSX support in other repository, not quite usable right now though) +- Add achievements to GOG via web API + +## Currently Supported Platforms +- 3DO Interactive +- Atari 2600 +- Atari Jaguar +- Nintendo Entertainment System +- Super Nintendo Entertainment System +- Nintendo 64 (Riku55) +- Nintendo GameCube +- Nintendo Wii +- Nintendo Game Boy +- Nintendo Game Boy Color +- Nintendo Game Boy Advance +- Nintendo DS +- Nintendo 3DS +- SEGA Master System +- SEGA Genesis / Mega Drive +- SEGA CD +- SEGA Saturn +- SEGA Dreamcast +- PC Engine / Turobgrafx 16 +- PlayStation +- PlayStation 2 +- PlayStation Portable + +![screenshot](https://imgur.com/A1Zk5Zt.png "Screenshot") ## Tutorial -### Setting up [RetroArch](https://retroarch.com/?page=platforms) (version 1.7.6 or higher required) - You need to repeat step 3 after adding new Roms to the path. +#### Setting up [RetroArch](https://retroarch.com/?page=platforms) 1. Open RetroArch. -2. Navigate to the left until you're at *Main Menu*, click on *Load Core* -> *Download a Core* and select *Nintendo - Nintendo 64 (Mupen64Plus-Next)*. +2. Navigate to the left until you're at *Main Menu*, click on *Load Core* -> *Download a Core* and download the core of your choice for the platform you want to integrate. 3. Navigate to the right until you're at *Import Content*, click on *Scan Directory*, navigate to the folder where your Roms are and click on *Scan this Directory*. 4. Navigate to *Settings*, click on *Saving*, go to the last option there *Save runtime log (aggregate)* and turn it on. -### Setting up the Integration: -1. Download the integration (use clone or download or download the *Source Code.zip* file in releases or just [click here](https://github.com/Riku55/galaxy-integration-n64-RetroArch-/archive/0.2.zip)). +#### Setting up RetroGOG: +1. Download [RetroGOG configuration wizard](https://github.com/jshackles/RetroGOG/raw/master/RetroGOG.exe) +2. Run the application and follow the on-screen instructions. +3. (Re)start Galaxy 2.0 and connect the integration. + +#### Manual setup instructions: +1. Download the integration (use clone or download). 2. Extract the ZIP file. -3. Put it into your Galaxy plugin folder (standard is: *C:\Users\USERNAME\AppData\Local\GOG.com\Galaxy\plugins\installed*) -4. Open the file *user_config.py* with an editor. -5. Add your emulator and roms path as described in the file. -6. (Re)start Galaxy 2.0 and connect the integration. -_______________________________________________________________________________________________________________________________________ - -## If the integration doesn't work and you made sure that you set up everything correctly, here are some things that might fix it: -1. In RetroArch, go to Settings -> Playlist and make sure that *Save Playlist using old format* is NOT active. -2. More to be added +3. Copy the contents of the plugins folders to your Galaxy plugin folder (standard is: *C:\Users\USERNAME\AppData\Local\GOG.com\Galaxy\plugins\installed*) +4. For each integration, open the file *user_config.py* with an editor. +5. Add your emulator path, along with your preferred core as described in the file. +6. (Re)start Galaxy 2.0 and connect the integration. \ No newline at end of file diff --git a/RetroGOG.exe b/RetroGOG.exe new file mode 100644 index 0000000..b0e7115 Binary files /dev/null and b/RetroGOG.exe differ diff --git a/corrections.py b/corrections.py deleted file mode 100644 index e1c5093..0000000 --- a/corrections.py +++ /dev/null @@ -1,12 +0,0 @@ -correction_list = {} - -correction_list["Legend of Zelda, The - Majora's Mask"] = "The Legend of Zelda - Majora's Mask" -correction_list["Legend of Zelda, The - Ocarina of Time"] = "The Legend of Zelda - Ocarina of Time" -correction_list["Doubutsu no Mori"] = "Animal Forest" -correction_list["Bomberman 64 - The Second Attack!"] = "Bomberman 64: The Second Attack" -correction_list["Tarzan"] = "Disney's Tarzan" -correction_list["RR64 - Ridge Racer 64"] = "Ridge Racer 64" - -correction_list2 = {} - -correction_list2["Pokemon Stadium (Japan)"] = "Pocket Monsters Stadium" diff --git a/galaxy/api/types.py b/galaxy/api/types.py deleted file mode 100644 index 37d55a3..0000000 --- a/galaxy/api/types.py +++ /dev/null @@ -1,153 +0,0 @@ -from dataclasses import dataclass -from typing import List, Dict, Optional - -from galaxy.api.consts import LicenseType, LocalGameState - -@dataclass -class Authentication(): - """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` - to inform the client that authentication has successfully finished. - - :param user_id: id of the authenticated user - :param user_name: username of the authenticated user - """ - user_id: str - user_name: str - -@dataclass -class Cookie(): - """Cookie - - :param name: name of the cookie - :param value: value of the cookie - :param domain: optional domain of the cookie - :param path: optional path of the cookie - """ - name: str - value: str - domain: Optional[str] = None - path: Optional[str] = None - -@dataclass -class NextStep(): - """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. - For example: - - .. code-block:: python - :linenos: - - PARAMS = { - "window_title": "Login to platform", - "window_width": 800, - "window_height": 600, - "start_uri": URL, - "end_uri_regex": r"^https://platform_website\.com/.*" - } - - JS = {r"^https://platform_website\.com/.*": [ - r''' - location.reload(); - ''' - ]} - - COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), - Cookie("Cookie2", "ok", ".platform.com") - ] - - async def authenticate(self, stored_credentials=None): - if not stored_credentials: - return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) - - :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} - :param cookies: browser initial set of cookies - :param js: a map of the url regex patterns into the list of *js* scripts that should be executed on every document at given step of internal browser authentication. - """ - next_step: str - auth_params: Dict[str, str] - cookies: Optional[List[Cookie]] = None - js: Optional[Dict[str, List[str]]] = None - -@dataclass -class LicenseInfo(): - """Information about the license of related product. - - :param license_type: type of license - :param owner: optional owner of the related product, defaults to currently authenticated user - """ - license_type: LicenseType - owner: Optional[str] = None - -@dataclass -class Dlc(): - """Downloadable content object. - - :param dlc_id: id of the dlc - :param dlc_title: title of the dlc - :param license_info: information about the license attached to the dlc - """ - dlc_id: str - dlc_title: str - license_info: LicenseInfo - -@dataclass -class Game(): - """Game object. - - :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game - :param game_title: title of the game - :param dlcs: list of dlcs available for the game - :param license_info: information about the license attached to the game - """ - game_id: str - game_title: str - dlcs: Optional[List[Dlc]] - license_info: LicenseInfo - -@dataclass -class Achievement(): - """Achievement, has to be initialized with either id or name. - - :param unlock_time: unlock time of the achievement - :param achievement_id: optional id of the achievement - :param achievement_name: optional name of the achievement - """ - unlock_time: int - achievement_id: Optional[str] = None - achievement_name: Optional[str] = None - - def __post_init__(self): - assert self.achievement_id or self.achievement_name, \ - "One of achievement_id or achievement_name is required" - -@dataclass -class LocalGame(): - """Game locally present on the authenticated user's computer. - - :param game_id: id of the game - :param local_game_state: state of the game - """ - game_id: str - local_game_state: LocalGameState - -@dataclass -class FriendInfo(): - """Information about a friend of the currently authenticated user. - - :param user_id: id of the user - :param user_name: username of the user - """ - user_id: str - user_name: str - -@dataclass -class GameTime(): - """Game time of a game, defines the total time spent in the game - and the last time the game was played. - - :param game_id: id of the related game - :param time_played: the total time spent in the game in **minutes** - :param last_time_played: last time the game was played (**unix timestamp**) - """ - game_id: str - time_played: Optional[int] - last_played_time: Optional[int] diff --git a/galaxy_api.zip b/galaxy_api.zip new file mode 100644 index 0000000..0c512dc Binary files /dev/null and b/galaxy_api.zip differ diff --git a/galaxy/__init__.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/__init__.py similarity index 75% rename from galaxy/__init__.py rename to plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/__init__.py index 97b69ed..1453276 100644 --- a/galaxy/__init__.py +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/__init__.py @@ -1 +1 @@ -__path__: str = __import__('pkgutil').extend_path(__path__, __name__) +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/__init__.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/galaxy/api/consts.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/consts.py similarity index 75% rename from galaxy/api/consts.py rename to plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/consts.py index d636613..e29eb98 100644 --- a/galaxy/api/consts.py +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/consts.py @@ -90,6 +90,7 @@ class Platform(Enum): Playfire = "playfire" Oculus = "oculus" Test = "test" + Rockstar = "rockstar" class Feature(Enum): @@ -110,6 +111,12 @@ class Feature(Enum): ImportFriends = "ImportFriends" ShutdownPlatformClient = "ShutdownPlatformClient" LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" class LicenseType(Enum): @@ -128,3 +135,30 @@ class LocalGameState(Flag): None_ = 0 Installed = 1 Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/galaxy/api/errors.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/errors.py similarity index 97% rename from galaxy/api/errors.py rename to plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/errors.py index f53479f..d5424bc 100644 --- a/galaxy/api/errors.py +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/errors.py @@ -20,7 +20,7 @@ def __init__(self, data=None): class UnknownBackendResponse(ApplicationError): def __init__(self, data=None): - super().__init__(4, "Backend responded in uknown way", data) + super().__init__(4, "Backend responded in unknown way", data) class TooManyRequests(ApplicationError): def __init__(self, data=None): diff --git a/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/importer.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/galaxy/api/jsonrpc.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/jsonrpc.py similarity index 61% rename from galaxy/api/jsonrpc.py rename to plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/jsonrpc.py index bd5ab64..51ecad3 100644 --- a/galaxy/api/jsonrpc.py +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/jsonrpc.py @@ -8,6 +8,10 @@ from galaxy.reader import StreamLineReader from galaxy.task_manager import TaskManager + +logger = logging.getLogger(__name__) + + class JsonRpcError(Exception): def __init__(self, code, message, data=None): self.code = code @@ -25,7 +29,7 @@ def json(self): } if self.data is not None: - obj["error"]["data"] = self.data + obj["data"] = self.data return obj @@ -64,6 +68,7 @@ def __init__(self, data=None): super().__init__(0, "Unknown error", data) Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) @@ -79,7 +84,7 @@ def anonymise_sensitive_params(params, sensitive_params): return params -class Server(): +class Connection(): def __init__(self, reader, writer, encoder=json.JSONEncoder()): self._active = True self._reader = StreamLineReader(reader) @@ -88,6 +93,8 @@ def __init__(self, reader, writer, encoder=json.JSONEncoder()): self._methods = {} self._notifications = {} self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} def register_method(self, name, callback, immediate, sensitive_params=False): """ @@ -113,6 +120,47 @@ def register_notification(self, name, callback, immediate, sensitive_params=Fals """ self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + async def run(self): while self._active: try: @@ -124,37 +172,63 @@ async def run(self): self._eof() continue data = data.strip() - logging.debug("Received %d bytes of data", len(data)) + logger.debug("Received %d bytes of data", len(data)) self._handle_input(data) await asyncio.sleep(0) # To not starve task queue def close(self): - logging.info("Closing JSON-RPC server - not more messages will be read") - self._active = False + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False async def wait_closed(self): await self._task_manager.wait() def _eof(self): - logging.info("Received EOF") + logger.info("Received EOF") self.close() def _handle_input(self, data): try: - request = self._parse_request(data) + message = self._parse_message(data) except JsonRpcError as error: self._send_error(None, error) return - if request.id is not None: - self._handle_request(request) - else: - self._handle_notification(request) + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) def _handle_notification(self, request): method = self._notifications.get(request.method) if not method: - logging.error("Received unknown notification: %s", request.method) + logger.error("Received unknown notification: %s", request.method) return callback, signature, immediate, sensitive_params = method @@ -171,12 +245,12 @@ def _handle_notification(self, request): try: self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) except Exception: - logging.exception("Unexpected exception raised in notification handler") + logger.exception("Unexpected exception raised in notification handler") def _handle_request(self, request): method = self._methods.get(request.method) if not method: - logging.error("Received unknown request: %s", request.method) + logger.error("Received unknown request: %s", request.method) self._send_error(request.id, MethodNotFound()) return @@ -203,33 +277,39 @@ async def handle(): except asyncio.CancelledError: self._send_error(request.id, Aborted()) except Exception as e: #pylint: disable=broad-except - logging.exception("Unexpected exception raised in plugin handler") + logger.exception("Unexpected exception raised in plugin handler") self._send_error(request.id, UnknownError(str(e))) self._task_manager.create_task(handle(), request.method) @staticmethod - def _parse_request(data): + def _parse_message(data): try: - jsonrpc_request = json.loads(data, encoding="utf-8") - if jsonrpc_request.get("jsonrpc") != "2.0": + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": raise InvalidRequest() - del jsonrpc_request["jsonrpc"] - return Request(**jsonrpc_request) + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + except json.JSONDecodeError: raise ParseError() except TypeError: raise InvalidRequest() - def _send(self, data): + def _send(self, data, sensitive=True): try: line = self._encoder.encode(data) - logging.debug("Sending data: %s", line) data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) self._writer.write(data) - self._task_manager.create_task(self._writer.drain(), "drain") except TypeError as error: - logging.error(str(error)) + logger.error(str(error)) def _send_response(self, request_id, result): response = { @@ -237,7 +317,7 @@ def _send_response(self, request_id, result): "id": request_id, "result": result } - self._send(response) + self._send(response, sensitive=False) def _send_error(self, request_id, error): response = { @@ -246,54 +326,42 @@ def _send_error(self, request_id, error): "error": error.json() } - self._send(response) + self._send(response, sensitive=False) - @staticmethod - def _log_request(request, sensitive_params): - params = anonymise_sensitive_params(request.params, sensitive_params) - if request.id is not None: - logging.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) - else: - logging.info("Handling notification: method=%s, params=%s", request.method, params) - -class NotificationClient(): - def __init__(self, writer, encoder=json.JSONEncoder()): - self._writer = writer - self._encoder = encoder - self._methods = {} - self._task_manager = TaskManager("notification client") - - def notify(self, method, params, sensitive_params=False): - """ - Send notification + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) - :param method: - :param params: - :param sensitive_params: list of parameters that are anonymized before logging; \ - if False - no params are considered sensitive, if True - all params are considered sensitive - """ + def _send_notification(self, method, params): notification = { "jsonrpc": "2.0", "method": method, "params": params } - self._log(method, params, sensitive_params) - self._send(notification) + self._send(notification, sensitive=True) - async def close(self): - await self._task_manager.wait() + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) - def _send(self, data): - try: - line = self._encoder.encode(data) - data = (line + "\n").encode("utf-8") - logging.debug("Sending %d byte of data", len(data)) - self._writer.write(data) - self._task_manager.create_task(self._writer.drain(), "drain") - except TypeError as error: - logging.error("Failed to parse outgoing message: %s", str(error)) + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) @staticmethod - def _log(method, params, sensitive_params): - params = anonymise_sensitive_params(params, sensitive_params) - logging.info("Sending notification: method=%s, params=%s", method, params) + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/galaxy/api/plugin.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/plugin.py similarity index 53% rename from galaxy/api/plugin.py rename to plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/plugin.py index e2330bb..9a746d2 100644 --- a/galaxy/api/plugin.py +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/plugin.py @@ -2,16 +2,22 @@ import dataclasses import json import logging -import logging.handlers import sys from enum import Enum -from typing import Any, Dict, List, Optional, Set, Union - -from galaxy.api.consts import Feature -from galaxy.api.errors import ImportInProgress, UnknownError -from galaxy.api.jsonrpc import ApplicationError, NotificationClient, Server -from galaxy.api.types import Achievement, Authentication, FriendInfo, Game, GameTime, LocalGame, NextStep +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + class JSONEncoder(json.JSONEncoder): def default(self, o): # pylint: disable=method-hidden @@ -30,7 +36,7 @@ class Plugin: """Use and override methods of this class to create a new platform integration.""" def __init__(self, platform, version, reader, writer, handshake_token): - logging.info("Creating plugin for platform %s, version %s", platform.value, version) + logger.info("Creating plugin for platform %s, version %s", platform.value, version) self._platform = platform self._version = version @@ -41,17 +47,85 @@ def __init__(self, platform, version, reader, writer, handshake_token): self._handshake_token = handshake_token encoder = JSONEncoder() - self._server = Server(self._reader, self._writer, encoder) - self._notification_client = NotificationClient(self._writer, encoder) - - self._achievements_import_in_progress = False - self._game_times_import_in_progress = False + self._connection = Connection(self._reader, self._writer, encoder) self._persistent_cache = dict() self._internal_task_manager = TaskManager("plugin internal") self._external_task_manager = TaskManager("plugin external") + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + # internal self._register_method("shutdown", self._shutdown, internal=True) self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) @@ -109,6 +183,24 @@ def __init__(self, platform, version, reader, writer, handshake_token): self._register_method("start_game_times_import", self._start_game_times_import) self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + async def __aenter__(self): return self @@ -136,7 +228,8 @@ def _detect_feature(self, feature: Feature, methods: List[str]): if self._implements(methods): self._features.add(feature) - def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, sensitive_params=False): + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): def wrap_result(result): if result_name: result = { @@ -149,7 +242,7 @@ def method(*args, **kwargs): result = handler(*args, **kwargs) return wrap_result(result) - self._server.register_method(name, method, True, sensitive_params) + self._connection.register_method(name, method, True, sensitive_params) else: async def method(*args, **kwargs): if not internal: @@ -159,37 +252,47 @@ async def method(*args, **kwargs): result = await handler_(*args, **kwargs) return wrap_result(result) - self._server.register_method(name, method, False, sensitive_params) + self._connection.register_method(name, method, False, sensitive_params) def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): if not internal and not immediate: handler = self._wrap_external_method(handler, name) - self._server.register_notification(name, handler, immediate, sensitive_params) + self._connection.register_notification(name, handler, immediate, sensitive_params) def _wrap_external_method(self, handler, name: str): async def wrapper(*args, **kwargs): return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + return wrapper async def run(self): """Plugin's main coroutine.""" - await self._server.run() + await self._connection.run() + logger.debug("Plugin run loop finished") def close(self) -> None: if not self._active: return - logging.info("Closing plugin") - self._server.close() + logger.info("Closing plugin") + self._connection.close() self._external_task_manager.cancel() - self._internal_task_manager.create_task(self.shutdown(), "shutdown") + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") self._active = False async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") await self._external_task_manager.wait() await self._internal_task_manager.wait() - await self._server.wait_closed() - await self._notification_client.close() + await self._connection.wait_closed() + logger.debug("Plugin closed") def create_task(self, coro, description): """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" @@ -200,11 +303,11 @@ async def _pass_control(self): try: self.tick() except Exception: - logging.exception("Unexpected exception raised in plugin tick") + logger.exception("Unexpected exception raised in plugin tick") await asyncio.sleep(1) async def _shutdown(self): - logging.info("Shutting down") + logger.info("Shutting down") self.close() await self._external_task_manager.wait() await self._internal_task_manager.wait() @@ -221,7 +324,7 @@ def _initialize_cache(self, data: Dict): try: self.handshake_complete() except Exception: - logging.exception("Unhandled exception during `handshake_complete` step") + logger.exception("Unhandled exception during `handshake_complete` step") self._internal_task_manager.create_task(self._pass_control(), "tick") @staticmethod @@ -252,9 +355,9 @@ async def pass_login_credentials(self, step, credentials, cookies): """ # temporary solution for persistent_cache vs credentials issue - self.persistent_cache['credentials'] = credentials # type: ignore + self.persistent_cache["credentials"] = credentials # type: ignore - self._notification_client.notify("store_credentials", credentials, sensitive_params=True) + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) def add_game(self, game: Game) -> None: """Notify the client to add game to the list of owned games @@ -276,7 +379,7 @@ async def check_for_new_games(self): """ params = {"owned_game": game} - self._notification_client.notify("owned_game_added", params) + self._connection.send_notification("owned_game_added", params) def remove_game(self, game_id: str) -> None: """Notify the client to remove game from the list of owned games @@ -298,7 +401,7 @@ async def check_for_removed_games(self): """ params = {"game_id": game_id} - self._notification_client.notify("owned_game_removed", params) + self._connection.send_notification("owned_game_removed", params) def update_game(self, game: Game) -> None: """Notify the client to update the status of a game @@ -307,7 +410,7 @@ def update_game(self, game: Game) -> None: :param game: Game to update """ params = {"owned_game": game} - self._notification_client.notify("owned_game_updated", params) + self._connection.send_notification("owned_game_updated", params) def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: """Notify the client to unlock an achievement for a specific game. @@ -319,24 +422,24 @@ def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: "game_id": game_id, "achievement": achievement } - self._notification_client.notify("achievement_unlocked", params) + self._connection.send_notification("achievement_unlocked", params) def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: params = { "game_id": game_id, "unlocked_achievements": achievements } - self._notification_client.notify("game_achievements_import_success", params) + self._connection.send_notification("game_achievements_import_success", params) def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: params = { "game_id": game_id, "error": error.json() } - self._notification_client.notify("game_achievements_import_failure", params) + self._connection.send_notification("game_achievements_import_failure", params) def _achievements_import_finished(self) -> None: - self._notification_client.notify("achievements_import_finished", None) + self._connection.send_notification("achievements_import_finished", None) def update_local_game_status(self, local_game: LocalGame) -> None: """Notify the client to update the status of a local game. @@ -362,15 +465,15 @@ def tick(self): self._check_statuses_task = asyncio.create_task(self._check_statuses()) """ params = {"local_game": local_game} - self._notification_client.notify("local_game_status_changed", params) + self._connection.send_notification("local_game_status_changed", params) - def add_friend(self, user: FriendInfo) -> None: + def add_friend(self, user: UserInfo) -> None: """Notify the client to add a user to friends list of the currently authenticated user. - :param user: FriendInfo of a user that the client will add to friends list + :param user: UserInfo of a user that the client will add to friends list """ params = {"friend_info": user} - self._notification_client.notify("friend_added", params) + self._connection.send_notification("friend_added", params) def remove_friend(self, user_id: str) -> None: """Notify the client to remove a user from friends list of the currently authenticated user. @@ -378,7 +481,14 @@ def remove_friend(self, user_id: str) -> None: :param user_id: id of the user to remove from friends list """ params = {"user_id": user_id} - self._notification_client.notify("friend_removed", params) + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) def update_game_time(self, game_time: GameTime) -> None: """Notify the client to update game time for a game. @@ -386,37 +496,161 @@ def update_game_time(self, game_time: GameTime) -> None: :param game_time: game time to update """ params = {"game_time": game_time} - self._notification_client.notify("game_time_updated", params) + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) - def _game_time_import_success(self, game_time: GameTime) -> None: + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: params = {"game_time": game_time} - self._notification_client.notify("game_time_import_success", params) + self._connection.send_notification("game_time_import_success", params) def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: params = { "game_id": game_id, "error": error.json() } - self._notification_client.notify("game_time_import_failure", params) + self._connection.send_notification("game_time_import_failure", params) def _game_times_import_finished(self) -> None: - self._notification_client.notify("game_times_import_finished", None) + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) def lost_authentication(self) -> None: """Notify the client that integration has lost authentication for the current user and is unable to perform actions which would require it. """ - self._notification_client.notify("authentication_lost", None) + self._connection.send_notification("authentication_lost", None) def push_cache(self) -> None: """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. """ - self._notification_client.notify( + self._connection.send_notification( "push_cache", params={"data": self._persistent_cache}, sensitive_params="data" ) + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + # handlers def handshake_complete(self) -> None: """This method is called right after the handshake with the GOG Galaxy Client is complete and @@ -458,7 +692,7 @@ async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union This method is called by the GOG Galaxy Client. :param stored_credentials: If the client received any credentials to store locally - in the previous session they will be passed here as a parameter. + in the previous session they will be passed here as a parameter. Example of possible override of the method: @@ -480,11 +714,12 @@ async def authenticate(self, stored_credentials=None): raise NotImplementedError() async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ - -> Union[NextStep, Authentication]: - """This method is called if we return galaxy.api.types.NextStep from authenticate or from pass_login_credentials. + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. - This method should either return galaxy.api.types.Authentication if the authentication is finished - or galaxy.api.types.NextStep if it requires going to another cef url. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. This method is called by the GOG Galaxy Client. :param step: deprecated. @@ -529,36 +764,7 @@ async def get_owned_games(self): raise NotImplementedError() async def _start_achievements_import(self, game_ids: List[str]) -> None: - if self._achievements_import_in_progress: - raise ImportInProgress() - - context = await self.prepare_achievements_context(game_ids) - - async def import_game_achievements(game_id, context_): - try: - achievements = await self.get_unlocked_achievements(game_id, context_) - self._game_achievements_import_success(game_id, achievements) - except ApplicationError as error: - self._game_achievements_import_failure(game_id, error) - except Exception: - logging.exception("Unexpected exception raised in import_game_achievements") - self._game_achievements_import_failure(game_id, UnknownError()) - - async def import_games_achievements(game_ids_, context_): - try: - imports = [import_game_achievements(game_id, context_) for game_id in game_ids_] - await asyncio.gather(*imports) - finally: - self._achievements_import_finished() - self._achievements_import_in_progress = False - self.achievements_import_complete() - - self._external_task_manager.create_task( - import_games_achievements(game_ids, context), - "unlocked achievements import", - handle_exceptions=False - ) - self._achievements_import_in_progress = True + await self._achievements_importer.start(game_ids) async def prepare_achievements_context(self, game_ids: List[str]) -> Any: """Override this method to prepare context for get_unlocked_achievements. @@ -672,7 +878,7 @@ async def launch_platform_client(self) -> None: This method is called by the GOG Galaxy Client.""" raise NotImplementedError() - async def get_friends(self) -> List[FriendInfo]: + async def get_friends(self) -> List[UserInfo]: """Override this method to return the friends list of the currently authenticated user. This method is called by the GOG Galaxy Client. @@ -693,36 +899,7 @@ async def get_friends(self): raise NotImplementedError() async def _start_game_times_import(self, game_ids: List[str]) -> None: - if self._game_times_import_in_progress: - raise ImportInProgress() - - context = await self.prepare_game_times_context(game_ids) - - async def import_game_time(game_id, context_): - try: - game_time = await self.get_game_time(game_id, context_) - self._game_time_import_success(game_time) - except ApplicationError as error: - self._game_time_import_failure(game_id, error) - except Exception: - logging.exception("Unexpected exception raised in import_game_time") - self._game_time_import_failure(game_id, UnknownError()) - - async def import_game_times(game_ids_, context_): - try: - imports = [import_game_time(game_id, context_) for game_id in game_ids_] - await asyncio.gather(*imports) - finally: - self._game_times_import_finished() - self._game_times_import_in_progress = False - self.game_times_import_complete() - - self._external_task_manager.create_task( - import_game_times(game_ids, context), - "game times import", - handle_exceptions=False - ) - self._game_times_import_in_progress = True + await self._game_time_importer.start(game_ids) async def prepare_game_times_context(self, game_ids: List[str]) -> Any: """Override this method to prepare context for get_game_time. @@ -750,6 +927,162 @@ def game_times_import_complete(self) -> None: (like updating cache). """ + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + def create_and_run_plugin(plugin_class, argv): """Call this method as an entry point for the implemented integration. @@ -769,7 +1102,7 @@ def main(): main() """ if len(argv) < 3: - logging.critical("Not enough parameters, required: token, port") + logger.critical("Not enough parameters, required: token, port") sys.exit(1) token = argv[1] @@ -777,23 +1110,27 @@ def main(): try: port = int(argv[2]) except ValueError: - logging.critical("Failed to parse port value: %s", argv[2]) + logger.critical("Failed to parse port value: %s", argv[2]) sys.exit(2) if not (1 <= port <= 65535): - logging.critical("Port value out of range (1, 65535)") + logger.critical("Port value out of range (1, 65535)") sys.exit(3) if not issubclass(plugin_class, Plugin): - logging.critical("plugin_class must be subclass of Plugin") + logger.critical("plugin_class must be subclass of Plugin") sys.exit(4) async def coroutine(): reader, writer = await asyncio.open_connection("127.0.0.1", port) - extra_info = writer.get_extra_info("sockname") - logging.info("Using local address: %s:%u", *extra_info) - async with plugin_class(reader, writer, token) as plugin: - await plugin.run() + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() try: if sys.platform == "win32": @@ -801,5 +1138,5 @@ async def coroutine(): asyncio.run(coroutine()) except Exception: - logging.exception("Error while running plugin") + logger.exception("Error while running plugin") sys.exit(5) diff --git a/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/types.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/galaxy/http.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/http.py similarity index 81% rename from galaxy/http.py rename to plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/http.py index 615daa0..a5bc76a 100644 --- a/galaxy/http.py +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/http.py @@ -1,12 +1,11 @@ """ -This module standarize http traffic and the error handling for further communication with the GOG Galaxy 2.0. +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. -Examplary simple web service could looks like: +Exemplary simple web service could looks like: .. code-block:: python - import logging from galaxy.http import create_client_session, handle_exception class BackendClient: @@ -44,6 +43,8 @@ async def _authorized_request(self, method, url, *args, **kwargs): ) +logger = logging.getLogger(__name__) + #: Default limit of the simultaneous connections for ssl connector. DEFAULT_LIMIT = 20 #: Default timeout in seconds used for client session. @@ -70,7 +71,7 @@ async def request(self, method, url, *args, **kwargs): def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: """ - Creates TCP connector with resonable defaults. + Creates TCP connector with reasonable defaults. For details about available parameters refer to `aiohttp.TCPConnector `_ """ @@ -78,16 +79,17 @@ def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: ssl_context.load_verify_locations(certifi.where()) kwargs.setdefault("ssl", ssl_context) kwargs.setdefault("limit", DEFAULT_LIMIT) - return aiohttp.TCPConnector(*args, **kwargs) # type: ignore due to https://github.com/python/mypy/issues/4001 + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: """ - Creates client session with resonable defaults. + Creates client session with reasonable defaults. For details about available parameters refer to `aiohttp.ClientSession `_ - Examplary customization: + Exemplary customization: .. code-block:: python @@ -103,7 +105,8 @@ def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: kwargs.setdefault("connector", create_tcp_connector()) kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) kwargs.setdefault("raise_for_status", True) - return aiohttp.ClientSession(*args, **kwargs) # type: ignore due to https://github.com/python/mypy/issues/4001 + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore @contextmanager @@ -120,25 +123,25 @@ def handle_exception(): raise BackendNotAvailable() except aiohttp.ClientConnectionError: raise NetworkError() - except aiohttp.ContentTypeError: - raise UnknownBackendResponse() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) except aiohttp.ClientResponseError as error: if error.status == HTTPStatus.UNAUTHORIZED: - raise AuthenticationRequired() + raise AuthenticationRequired(error.message) if error.status == HTTPStatus.FORBIDDEN: - raise AccessDenied() + raise AccessDenied(error.message) if error.status == HTTPStatus.SERVICE_UNAVAILABLE: - raise BackendNotAvailable() + raise BackendNotAvailable(error.message) if error.status == HTTPStatus.TOO_MANY_REQUESTS: - raise TooManyRequests() + raise TooManyRequests(error.message) if error.status >= 500: - raise BackendError() + raise BackendError(error.message) if error.status >= 400: - logging.warning( + logger.warning( "Got status %d while performing %s request for %s", error.status, error.request_info.method, str(error.request_info.url) ) - raise UnknownError() - except aiohttp.ClientError: - logging.exception("Caught exception while performing request") - raise UnknownError() + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/galaxy/proc_tools.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/proc_tools.py similarity index 99% rename from galaxy/proc_tools.py rename to plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/proc_tools.py index b0de0bc..4c2df33 100644 --- a/galaxy/proc_tools.py +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/proc_tools.py @@ -3,7 +3,6 @@ from typing import Iterable, NewType, Optional, List, cast - ProcessId = NewType("ProcessId", int) diff --git a/galaxy/reader.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/reader.py similarity index 93% rename from galaxy/reader.py rename to plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/reader.py index 551f803..732e658 100644 --- a/galaxy/reader.py +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/reader.py @@ -12,7 +12,7 @@ async def readline(self): while True: # check if there is no unprocessed data in the buffer if not self._buffer or self._processed_buffer_it != 0: - chunk = await self._reader.read(1024) + chunk = await self._reader.read(1024*1024) if not chunk: return bytes() # EOF self._buffer += chunk diff --git a/galaxy/registry_monitor.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/registry_monitor.py similarity index 94% rename from galaxy/registry_monitor.py rename to plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/registry_monitor.py index 02b1a5a..1396535 100644 --- a/galaxy/registry_monitor.py +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/registry_monitor.py @@ -1,5 +1,7 @@ -import platform -if platform.system().lower() == "windows": +import sys + + +if sys.platform == "win32": import logging import ctypes from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID @@ -76,11 +78,10 @@ def is_updated(self): if self._key is None: self._open_key() - if self._key is None: - return False + if self._key is not None: + self._set_key_update_notification() - self._set_key_update_notification() - return True + return False def _set_key_update_notification(self): filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET diff --git a/galaxy/task_manager.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/task_manager.py similarity index 73% rename from galaxy/task_manager.py rename to plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/task_manager.py index 1ff20e2..e7bb517 100644 --- a/galaxy/task_manager.py +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/task_manager.py @@ -3,6 +3,10 @@ from collections import OrderedDict from itertools import count + +logger = logging.getLogger(__name__) + + class TaskManager: def __init__(self, name): self._name = name @@ -15,23 +19,23 @@ def create_task(self, coro, description, handle_exceptions=True): async def task_wrapper(task_id): try: result = await coro - logging.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) return result except asyncio.CancelledError: if handle_exceptions: - logging.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) else: raise except Exception: if handle_exceptions: - logging.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) else: raise finally: del self._tasks[task_id] task_id = next(self._task_counter) - logging.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) task = asyncio.create_task(task_wrapper(task_id)) self._tasks[task_id] = task return task @@ -47,6 +51,3 @@ async def wait(self): if not tasks: return await asyncio.gather(*tasks, return_exceptions=True) - - - diff --git a/galaxy/tools.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/tools.py similarity index 100% rename from galaxy/tools.py rename to plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/tools.py diff --git a/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/unittest/__init__.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/galaxy/unittest/mock.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/unittest/mock.py similarity index 77% rename from galaxy/unittest/mock.py rename to plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/unittest/mock.py index b439671..da2e033 100644 --- a/galaxy/unittest/mock.py +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/galaxy/unittest/mock.py @@ -21,11 +21,19 @@ def coroutine_mock(): corofunc.coro = coro return corofunc + async def skip_loop(iterations=1): for _ in range(iterations): await asyncio.sleep(0) async def async_return_value(return_value, loop_iterations_delay=0): - await skip_loop(loop_iterations_delay) + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/manifest.json b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/manifest.json new file mode 100644 index 0000000..2d95c9b --- /dev/null +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy 3DO RetroArch plugin", + "platform": "3do", + "guid": "9d81c0ec-5646-4b1a-b809-e7e61e1d3577", + "version": "0.4", + "description": "Galaxy Plugin to add 3DO games and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/plugin.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/plugin.py new file mode 100644 index 0000000..ef55352 --- /dev/null +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform._3Do, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/The 3DO Company - 3DO.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/user_config.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/user_config.py new file mode 100644 index 0000000..65e1a51 --- /dev/null +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "opera_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/version.py b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/__init__.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/__init__.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/consts.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/errors.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/importer.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/jsonrpc.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/plugin.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/types.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/http.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/proc_tools.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/reader.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/registry_monitor.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/task_manager.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/tools.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/unittest/__init__.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/unittest/mock.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/manifest.json b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/manifest.json new file mode 100644 index 0000000..ca58ddd --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy Nintendo 3DS RetroArch plugin", + "platform": "3ds", + "guid": "f6acd3ed-2c31-47d6-bae4-07b6714c1e55", + "version": "0.4", + "description": "Galaxy Plugin to add Nintendo 3DS roms and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/plugin.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/plugin.py new file mode 100644 index 0000000..03cb4a9 --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.Nintendo3Ds, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Nintendo - Nintendo 3DS.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/user_config.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/user_config.py new file mode 100644 index 0000000..3df833b --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "citra_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/version.py b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/__init__.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/__init__.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/consts.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/errors.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/importer.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/jsonrpc.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/plugin.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/types.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/http.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/proc_tools.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/reader.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/registry_monitor.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/task_manager.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/tools.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/unittest/__init__.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/unittest/mock.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/manifest.json b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/manifest.json new file mode 100644 index 0000000..3329195 --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy Atari 2600 RetroArch plugin", + "platform": "atari", + "guid": "830528d9-e621-48e9-8ed4-e03a4853843e", + "version": "0.4", + "description": "Galaxy Plugin to add Atari 2600 roms and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/plugin.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/plugin.py new file mode 100644 index 0000000..4eb5237 --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.Atari, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Atari - 2600.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/user_config.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/user_config.py new file mode 100644 index 0000000..5d06aff --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "stella_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/version.py b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/atari_830528d9-e621-48e9-8ed4-e03a4853843e/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/__init__.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/__init__.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/consts.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/errors.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/importer.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/jsonrpc.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/plugin.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/types.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/http.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/proc_tools.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/reader.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/registry_monitor.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/task_manager.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/tools.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/unittest/__init__.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/unittest/mock.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/manifest.json b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/manifest.json new file mode 100644 index 0000000..b302e80 --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy Sega Dreamcast RetroArch plugin", + "platform": "dc", + "guid": "5d181ffd-48dc-4330-aa58-6f646e76a5c8", + "version": "0.4", + "description": "Galaxy Plugin to add Sega Dreamcast isos and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/plugin.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/plugin.py new file mode 100644 index 0000000..adec4ec --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.SegaDreamcast, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Sega - Dreamcast.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/user_config.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/user_config.py new file mode 100644 index 0000000..3d14f0e --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "flycast_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/version.py b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/__init__.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/__init__.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/consts.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/errors.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/importer.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/jsonrpc.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/plugin.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/types.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/http.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/proc_tools.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/reader.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/registry_monitor.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/task_manager.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/tools.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/unittest/__init__.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/unittest/mock.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/manifest.json b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/manifest.json new file mode 100644 index 0000000..d352acb --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy Nintendo Gameboy RetroArch plugin", + "platform": "ngameboy", + "guid": "4345afe1-a2c3-4c58-93d3-373c53a90a92", + "version": "0.4", + "description": "Galaxy Plugin to add Nintendo GameBoy roms and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/plugin.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/plugin.py new file mode 100644 index 0000000..a28ac32 --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.NintendoGameBoy, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Nintendo - Game Boy.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/user_config.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/user_config.py new file mode 100644 index 0000000..98bea83 --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "mgba_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/version.py b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/gb_4345afe1-a2c3-4c58-93d3-373c53a90a92/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/__init__.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/__init__.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/consts.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/errors.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/importer.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/jsonrpc.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/plugin.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/types.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/http.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/proc_tools.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/reader.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/registry_monitor.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/task_manager.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/tools.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/unittest/__init__.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/unittest/mock.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/manifest.json b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/manifest.json new file mode 100644 index 0000000..9df536b --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy Nintendo Gameboy Advance RetroArch plugin", + "platform": "ngameboy", + "guid": "16a78ef5-fba6-4629-b83c-ef47adab5aab", + "version": "0.4", + "description": "Galaxy Plugin to add Nintendo GameBoy Advance roms and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/plugin.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/plugin.py new file mode 100644 index 0000000..5338d02 --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.NintendoGameBoy, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Nintendo - Game Boy Advance.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/user_config.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/user_config.py new file mode 100644 index 0000000..98bea83 --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "mgba_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/version.py b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/gba_16a78ef5-fba6-4629-b83c-ef47adab5aab/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/__init__.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/__init__.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/consts.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/errors.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/importer.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/jsonrpc.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/plugin.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/types.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/http.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/proc_tools.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/reader.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/registry_monitor.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/task_manager.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/tools.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/unittest/__init__.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/unittest/mock.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/manifest.json b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/manifest.json new file mode 100644 index 0000000..cb62617 --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy Nintendo Gameboy Color RetroArch plugin", + "platform": "ngameboy", + "guid": "9b53fc85-af7c-4ce2-af31-0d95234d783a", + "version": "0.4", + "description": "Galaxy Plugin to add Nintendo GameBoy Color roms and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/plugin.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/plugin.py new file mode 100644 index 0000000..cbeacd4 --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.NintendoGameBoy, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Nintendo - Game Boy Color.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/user_config.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/user_config.py new file mode 100644 index 0000000..98bea83 --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "mgba_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/version.py b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/__init__.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/__init__.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/consts.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/errors.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/importer.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/jsonrpc.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/plugin.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/types.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/http.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/proc_tools.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/reader.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/registry_monitor.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/task_manager.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/tools.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/unittest/__init__.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/unittest/mock.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/manifest.json b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/manifest.json new file mode 100644 index 0000000..fd934b6 --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy Atari Jaguar RetroArch plugin", + "platform": "jaguar", + "guid": "b9773549-9c20-4729-b23d-f683762ce73a", + "version": "0.4", + "description": "Galaxy Plugin to add Atari Jaguar roms and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/plugin.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/plugin.py new file mode 100644 index 0000000..981cb3d --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.AtariJaguar, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Atari - Jaguar.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/user_config.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/user_config.py new file mode 100644 index 0000000..b7092fc --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "virtualjaguar_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/version.py b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/jaguar_b9773549-9c20-4729-b23d-f683762ce73a/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/__init__.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/__init__.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/consts.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/errors.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/importer.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/jsonrpc.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/plugin.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/types.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/http.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/proc_tools.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/reader.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/registry_monitor.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/task_manager.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/tools.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/unittest/__init__.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/unittest/mock.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/manifest.json b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/manifest.json similarity index 93% rename from manifest.json rename to plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/manifest.json index b3cbdf7..516e46b 100644 --- a/manifest.json +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/manifest.json @@ -2,7 +2,7 @@ "name": "Galaxy n64 RetroArch plugin", "platform": "n64", "guid": "a3824d31-c2d3-4a1a-b321-7d0764da5513", - "version": "0.2", + "version": "0.4", "description": "Galaxy Plugin to add n64 roms and start them with RetroArch emulator", "author": "riku55", "email": "", diff --git a/plugin.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/plugin.py similarity index 63% rename from plugin.py rename to plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/plugin.py index 846a6c2..54b9fbb 100644 --- a/plugin.py +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/plugin.py @@ -2,16 +2,22 @@ import subprocess import sys import json, urllib.request, os, os.path -import user_config, corrections +import user_config import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional from galaxy.api.consts import LicenseType, LocalGameState, Platform from galaxy.api.plugin import Plugin, create_and_run_plugin -from galaxy.api.types import Authentication, Game, LicenseInfo, LocalGame, GameTime +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime -class RetroarchN64Plugin(Plugin): +from version import __version__ as version + +class Retroarch(Plugin): def __init__(self, reader, writer, token): - super().__init__(Platform.Nintendo64, "0.2", reader, writer, token) + super().__init__(Platform.Nintendo64, version, reader, writer, token) self.game_cache = [] self.playlist_path = user_config.emu_path + "playlists/Nintendo - Nintendo 64.lpl" self.proc = None @@ -23,57 +29,56 @@ async def authenticate(self, stored_credentials=None): creds["user"] = "RAUser" self.store_credentials(creds) return Authentication("RAUser", "Retroarch") - + async def pass_login_credentials(self, step, credentials, cookies): creds = {} creds["user"] = "RAUser" self.store_credentials(creds) - return Authentication("RAUser", "Retroarch") - + return Authentication("RAUser", "Retroarch") + async def get_owned_games(self): - self.update_game_cache() - - return self.game_cache - + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache - def update_game_cache(self): + def update_game_cache(self): game_list = [] - + if os.path.isfile(self.playlist_path): with open(self.playlist_path) as playlist_json: playlist_dict = json.load(playlist_json) for entry in playlist_dict["items"]: - if os.path.abspath(user_config.rom_path) in os.path.abspath(entry["path"]) and os.path.isfile(entry["path"]): - if entry["label"].split(" (")[0] in corrections.correction_list: - correct_name = corrections.correction_list[entry["label"].split(" (")[0]] - else: - if entry["label"] in corrections.correction_list2: - correct_name = corrections.correction_list2[entry["label"]] - else: - correct_name = entry["label"].split(" (")[0] + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) game_list.append( - Game( - entry["crc32"].split("|")[0], - correct_name, + Game( + provided_name, + provided_name, None, LicenseInfo(LicenseType.SinglePurchase, None) ) - ) - + ) + #adds games when added while running for entry in game_list: if entry not in self.game_cache: self.game_cache.append(entry) self.add_game(entry) - + #removes games when removed while running for entry in self.game_cache: if entry not in game_list: - self.game_cache.remove(entry) + self.game_cache.remove(entry) self.remove_game(entry.game_id) - #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed async def get_local_games(self): if not self.game_cache: @@ -82,36 +87,31 @@ async def get_local_games(self): for game_entry in self.game_cache: local_game_list.append(LocalGame(game_entry.game_id, 1)) return local_game_list - + # Only as placeholders so the launch game feature is recognized async def install_game(self, game_id): pass async def uninstall_game(self, game_id): pass - + def shutdown(self): pass - - #potentially give user more customization possibilities like starting in fullscreen etc - async def launch_game(self, game_id): - + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): if os.path.isfile(self.playlist_path): with open(self.playlist_path) as playlist_json: playlist_dict = json.load(playlist_json) for entry in playlist_dict["items"]: - if game_id == entry["crc32"].split("|")[0]: + if game_id == self.format_game(entry["label"]): self.update_local_game_status(LocalGame(game_id, 2)) - self.game_run = entry["crc32"].split("|")[0] - if user_config.core == 1: - self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/mupen64plus_next_libretro.dll\" \"" + entry["path"])) - if user_config.core == 2: - self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/parallel_n64_libretro.dll\" \"" + entry["path"])) - break - - #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings - async def get_game_time(self, game_id: str, context:any): + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): file_path = "" time = 0 last_played = None @@ -120,8 +120,8 @@ async def get_game_time(self, game_id: str, context:any): with open(self.playlist_path) as playlist_json: playlist_dict = json.load(playlist_json) for rom in playlist_dict["items"]: - if game_id == rom["crc32"].split("|")[0]: - file_path = user_config.emu_path + "/playlists/logs/" + os.path.abspath(rom["path"]).split(os.path.abspath(user_config.rom_path) + "\\")[1][:-4] + ".lrtl" + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" if os.path.isfile(file_path): with open(file_path) as json_data: time_data = json.load(json_data) @@ -129,8 +129,8 @@ async def get_game_time(self, game_id: str, context:any): min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') time = min_data.hour*60 + min_data.minute return GameTime(game_id, time, last_played) - - #checks if game is (still) running, adjusts game_cache and game_time + + #checks if game is (still) running, adjusts game_cache and game_time def tick(self): try: if self.proc.poll() is not None: @@ -139,14 +139,13 @@ def tick(self): self.proc = None except AttributeError: pass - - self.update_game_cache() + + self.update_game_cache() self.get_local_games() - + def main(): - create_and_run_plugin(RetroarchN64Plugin, sys.argv) - + create_and_run_plugin(Retroarch, sys.argv) + if __name__ == "__main__": - main() - + main() diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/user_config.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/user_config.py new file mode 100644 index 0000000..db4e995 --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your roms and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "mupen64plus_next_libretro.dll" + +core = "" diff --git a/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/version.py b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/n64_a3824d31-c2d3-4a1a-b321-7d0764da5513/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/__init__.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/__init__.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/consts.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/errors.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/importer.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/jsonrpc.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/plugin.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/types.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/http.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/proc_tools.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/reader.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/registry_monitor.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/task_manager.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/tools.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/unittest/__init__.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/unittest/mock.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/manifest.json b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/manifest.json new file mode 100644 index 0000000..0eebe52 --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy Nintendo Gamecube RetroArch plugin", + "platform": "ncube", + "guid": "602422b9-ced5-476e-911a-7fa0adf0f7f7", + "version": "0.4", + "description": "Galaxy Plugin to add Nintendo Gamecube isos and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/plugin.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/plugin.py new file mode 100644 index 0000000..cbeb22a --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.NintendoGameCube, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Nintendo - GameCube.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/user_config.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/user_config.py new file mode 100644 index 0000000..8706617 --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "dolphin_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/version.py b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/__init__.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/__init__.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/consts.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/errors.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/importer.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/jsonrpc.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/plugin.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/types.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/http.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/proc_tools.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/reader.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/registry_monitor.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/task_manager.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/tools.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/unittest/__init__.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/unittest/mock.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/manifest.json b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/manifest.json new file mode 100644 index 0000000..f875447 --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy Nintendo DS RetroArch plugin", + "platform": "nds", + "guid": "4704ed29-f516-4fd8-8477-ddbcdb7cedfc", + "version": "0.4", + "description": "Galaxy Plugin to add Nintendo DS roms and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/plugin.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/plugin.py new file mode 100644 index 0000000..b59370a --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.NintendoDs, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Nintendo - Nintendo DS.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/user_config.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/user_config.py new file mode 100644 index 0000000..539eb5a --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "desmume_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/version.py b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/__init__.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/__init__.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/consts.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/errors.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/importer.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/jsonrpc.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/plugin.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/types.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/http.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/proc_tools.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/reader.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/registry_monitor.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/task_manager.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/tools.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/unittest/__init__.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/unittest/mock.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/manifest.json b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/manifest.json new file mode 100644 index 0000000..2029a8a --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy NES RetroArch plugin", + "platform": "nes", + "guid": "e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad", + "version": "0.4", + "description": "Galaxy Plugin to add NES roms and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/plugin.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/plugin.py new file mode 100644 index 0000000..b01a6d2 --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.NintendoEntertainmentSystem, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Nintendo - Nintendo Entertainment System.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/user_config.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/user_config.py new file mode 100644 index 0000000..8faf7e2 --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your roms and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "mesen_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/version.py b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/__init__.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/__init__.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/consts.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/errors.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/importer.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/jsonrpc.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/plugin.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/types.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/http.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/proc_tools.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/reader.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/registry_monitor.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/task_manager.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/tools.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/unittest/__init__.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/unittest/mock.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/manifest.json b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/manifest.json new file mode 100644 index 0000000..ddc1cf5 --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy Nintendo Wii RetroArch plugin", + "platform": "nwii", + "guid": "2d0e97ac-0406-4e5f-a85b-ab5b1a042cba", + "version": "0.4", + "description": "Galaxy Plugin to add Nintendo Wii isos and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/plugin.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/plugin.py new file mode 100644 index 0000000..221d464 --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.NintendoWii, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Nintendo - Wii.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/user_config.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/user_config.py new file mode 100644 index 0000000..8706617 --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "dolphin_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/version.py b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/__init__.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/__init__.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/consts.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/errors.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/importer.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/jsonrpc.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/plugin.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/types.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/http.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/proc_tools.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/reader.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/registry_monitor.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/task_manager.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/tools.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/unittest/__init__.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/unittest/mock.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/manifest.json b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/manifest.json new file mode 100644 index 0000000..03f6735 --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy PC Engine RetroArch plugin", + "platform": "pce", + "guid": "c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a", + "version": "0.4", + "description": "Galaxy Plugin to add PC Engine games and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/plugin.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/plugin.py new file mode 100644 index 0000000..078f6d2 --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.PcEngine, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/NEC - PC Engine - TurboGrafx 16.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/user_config.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/user_config.py new file mode 100644 index 0000000..26b21db --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "mednafen_pce_fast_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/version.py b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/__init__.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/__init__.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/consts.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/errors.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/importer.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/jsonrpc.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/plugin.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/types.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/http.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/proc_tools.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/reader.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/registry_monitor.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/task_manager.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/tools.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/unittest/__init__.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/unittest/mock.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/manifest.json b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/manifest.json new file mode 100644 index 0000000..6e081d7 --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy PS1 RetroArch plugin", + "platform": "psx", + "guid": "ff02c67d-5962-4e79-a3a3-928814edb270", + "version": "0.4", + "description": "Galaxy Plugin to add PS1 isos and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/plugin.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/plugin.py new file mode 100644 index 0000000..6816265 --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.PlayStation, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Sony - PlayStation.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/user_config.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/user_config.py new file mode 100644 index 0000000..b3dd8e2 --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "pcsx_rearmed_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/version.py b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/ps1_ff02c67d-5962-4e79-a3a3-928814edb270/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/__init__.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/__init__.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/consts.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/errors.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/importer.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/jsonrpc.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/plugin.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/types.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/http.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/proc_tools.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/reader.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/registry_monitor.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/task_manager.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/tools.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/unittest/__init__.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/unittest/mock.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/manifest.json b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/manifest.json new file mode 100644 index 0000000..88289f5 --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy PS2 RetroArch plugin", + "platform": "ps2", + "guid": "50ad79eb-393c-4f95-98ce-59f095ae47ea", + "version": "0.4", + "description": "Galaxy Plugin to add PS2 isos and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/plugin.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/plugin.py new file mode 100644 index 0000000..c544aa3 --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.PlayStation2, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Sony - PlayStation 2.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/user_config.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/user_config.py new file mode 100644 index 0000000..98bd88f --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "play_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/version.py b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/__init__.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/__init__.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/consts.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/errors.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/importer.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/jsonrpc.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/plugin.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/types.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/http.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/proc_tools.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/reader.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/registry_monitor.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/task_manager.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/tools.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/unittest/__init__.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/unittest/mock.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/manifest.json b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/manifest.json new file mode 100644 index 0000000..788fb6c --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy PSP RetroArch plugin", + "platform": "psp", + "guid": "05487532-ba29-411b-b799-784262d275bd", + "version": "0.4", + "description": "Galaxy Plugin to add PSP isos and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/plugin.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/plugin.py new file mode 100644 index 0000000..921fee2 --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.PlayStationPortable, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Sony - PlayStation Portable.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/user_config.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/user_config.py new file mode 100644 index 0000000..e58403b --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "ppsspp_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/psp_05487532-ba29-411b-b799-784262d275bd/version.py b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/psp_05487532-ba29-411b-b799-784262d275bd/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/__init__.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/__init__.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/consts.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/errors.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/importer.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/jsonrpc.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/plugin.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/types.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/http.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/proc_tools.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/reader.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/registry_monitor.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/task_manager.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/tools.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/unittest/__init__.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/unittest/mock.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/manifest.json b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/manifest.json new file mode 100644 index 0000000..3014d4e --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy Sega Saturn RetroArch plugin", + "platform": "saturn", + "guid": "bd6ec091-8ee0-440a-9e26-71bbf21c05af", + "version": "0.4", + "description": "Galaxy Plugin to add Sega Saturn isos and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/plugin.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/plugin.py new file mode 100644 index 0000000..84f5f8a --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.SegaSaturn, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Sega - Saturn.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/user_config.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/user_config.py new file mode 100644 index 0000000..75c87bb --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "mednafen_saturn_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/version.py b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/__init__.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/__init__.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/consts.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/errors.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/importer.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/jsonrpc.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/plugin.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/types.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/http.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/proc_tools.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/reader.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/registry_monitor.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/task_manager.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/tools.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/unittest/__init__.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/unittest/mock.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/manifest.json b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/manifest.json new file mode 100644 index 0000000..51ee4ff --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy Sega CD RetroArch plugin", + "platform": "segacd", + "guid": "ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2", + "version": "0.4", + "description": "Galaxy Plugin to add Sega CD isos and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/plugin.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/plugin.py new file mode 100644 index 0000000..3dc60e7 --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.SegaCd, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Sega - Mega-CD - Sega CD.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/user_config.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/user_config.py new file mode 100644 index 0000000..8abbed4 --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "genesis_plus_gx_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/version.py b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/__init__.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/__init__.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/consts.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/errors.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/importer.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/jsonrpc.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/plugin.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/types.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/http.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/proc_tools.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/reader.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/registry_monitor.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/task_manager.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/tools.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/unittest/__init__.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/unittest/mock.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/manifest.json b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/manifest.json new file mode 100644 index 0000000..765050a --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy Sega Genesis RetroArch plugin", + "platform": "segag", + "guid": "e3ac94e7-945e-459d-bc1e-676cff8173f9", + "version": "0.4", + "description": "Galaxy Plugin to add Sega Genesis roms and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/plugin.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/plugin.py new file mode 100644 index 0000000..4deeda6 --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.SegaGenesis, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Sega - Mega Drive - Genesis.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/user_config.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/user_config.py new file mode 100644 index 0000000..8abbed4 --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "genesis_plus_gx_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/version.py b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/segag_e3ac94e7-945e-459d-bc1e-676cff8173f9/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/__init__.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/__init__.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/consts.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/errors.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/importer.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/jsonrpc.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/plugin.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/types.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/http.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/proc_tools.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/reader.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/registry_monitor.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/task_manager.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/tools.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/unittest/__init__.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/unittest/mock.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/manifest.json b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/manifest.json new file mode 100644 index 0000000..ff8ab1b --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy Sega Master System RetroArch plugin", + "platform": "sms", + "guid": "c6689bfb-7ba4-4d24-98e3-bd2dc339926b", + "version": "0.4", + "description": "Galaxy Plugin to add Sega Master System roms and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/plugin.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/plugin.py new file mode 100644 index 0000000..c2ebc7e --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.SegaMasterSystem, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Sega - Master System - Mark III.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/user_config.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/user_config.py new file mode 100644 index 0000000..8abbed4 --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your isos and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "genesis_plus_gx_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/version.py b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/__init__.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/__init__.py new file mode 100644 index 0000000..1453276 --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/__init__.py @@ -0,0 +1 @@ +__path__: str = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/__init__.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/consts.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/consts.py new file mode 100644 index 0000000..e29eb98 --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/consts.py @@ -0,0 +1,164 @@ +from enum import Enum, Flag + + +class Platform(Enum): + """Supported gaming platforms""" + Unknown = "unknown" + Gog = "gog" + Steam = "steam" + Psn = "psn" + XBoxOne = "xboxone" + Generic = "generic" + Origin = "origin" + Uplay = "uplay" + Battlenet = "battlenet" + Epic = "epic" + Bethesda = "bethesda" + ParadoxPlaza = "paradox" + HumbleBundle = "humble" + Kartridge = "kartridge" + ItchIo = "itch" + NintendoSwitch = "nswitch" + NintendoWiiU = "nwiiu" + NintendoWii = "nwii" + NintendoGameCube = "ncube" + RiotGames = "riot" + Wargaming = "wargaming" + NintendoGameBoy = "ngameboy" + Atari = "atari" + Amiga = "amiga" + SuperNintendoEntertainmentSystem = "snes" + Beamdog = "beamdog" + Direct2Drive = "d2d" + Discord = "discord" + DotEmu = "dotemu" + GameHouse = "gamehouse" + GreenManGaming = "gmg" + WePlay = "weplay" + ZxSpectrum = "zx" + ColecoVision = "vision" + NintendoEntertainmentSystem = "nes" + SegaMasterSystem = "sms" + Commodore64 = "c64" + PcEngine = "pce" + SegaGenesis = "segag" + NeoGeo = "neo" + Sega32X = "sega32" + SegaCd = "segacd" + _3Do = "3do" + SegaSaturn = "saturn" + PlayStation = "psx" + PlayStation2 = "ps2" + Nintendo64 = "n64" + AtariJaguar = "jaguar" + SegaDreamcast = "dc" + Xbox = "xboxog" + Amazon = "amazon" + GamersGate = "gg" + Newegg = "egg" + BestBuy = "bb" + GameUk = "gameuk" + Fanatical = "fanatical" + PlayAsia = "playasia" + Stadia = "stadia" + Arc = "arc" + ElderScrollsOnline = "eso" + Glyph = "glyph" + AionLegionsOfWar = "aionl" + Aion = "aion" + BladeAndSoul = "blade" + GuildWars = "gw" + GuildWars2 = "gw2" + Lineage2 = "lin2" + FinalFantasy11 = "ffxi" + FinalFantasy14 = "ffxiv" + TotalWar = "totalwar" + WindowsStore = "winstore" + EliteDangerous = "elites" + StarCitizen = "star" + PlayStationPortable = "psp" + PlayStationVita = "psvita" + NintendoDs = "nds" + Nintendo3Ds = "3ds" + PathOfExile = "pathofexile" + Twitch = "twitch" + Minecraft = "minecraft" + GameSessions = "gamesessions" + Nuuvem = "nuuvem" + FXStore = "fxstore" + IndieGala = "indiegala" + Playfire = "playfire" + Oculus = "oculus" + Test = "test" + Rockstar = "rockstar" + + +class Feature(Enum): + """Possible features that can be implemented by an integration. + It does not have to support all or any specific features from the list. + """ + Unknown = "Unknown" + ImportInstalledGames = "ImportInstalledGames" + ImportOwnedGames = "ImportOwnedGames" + LaunchGame = "LaunchGame" + InstallGame = "InstallGame" + UninstallGame = "UninstallGame" + ImportAchievements = "ImportAchievements" + ImportGameTime = "ImportGameTime" + Chat = "Chat" + ImportUsers = "ImportUsers" + VerifyGame = "VerifyGame" + ImportFriends = "ImportFriends" + ShutdownPlatformClient = "ShutdownPlatformClient" + LaunchPlatformClient = "LaunchPlatformClient" + ImportGameLibrarySettings = "ImportGameLibrarySettings" + ImportOSCompatibility = "ImportOSCompatibility" + ImportUserPresence = "ImportUserPresence" + ImportLocalSize = "ImportLocalSize" + ImportSubscriptions = "ImportSubscriptions" + ImportSubscriptionGames = "ImportSubscriptionGames" + + +class LicenseType(Enum): + """Possible game license types, understandable for the GOG Galaxy client.""" + Unknown = "Unknown" + SinglePurchase = "SinglePurchase" + FreeToPlay = "FreeToPlay" + OtherUserLicense = "OtherUserLicense" + + +class LocalGameState(Flag): + """Possible states that a local game can be in. + For example a game which is both installed and currently running should have its state set as a "bitwise or" of Running and Installed flags: + ``local_game_state=`` + """ + None_ = 0 + Installed = 1 + Running = 2 + + +class OSCompatibility(Flag): + """Possible game OS compatibility. + Use "bitwise or" to express multiple OSs compatibility, e.g. ``os=OSCompatibility.Windows|OSCompatibility.MacOS`` + """ + Windows = 0b001 + MacOS = 0b010 + Linux = 0b100 + + +class PresenceState(Enum): + """"Possible states of a user.""" + Unknown = "unknown" + Online = "online" + Offline = "offline" + Away = "away" + + +class SubscriptionDiscovery(Flag): + """Possible capabilities which inform what methods of subscriptions ownership detection are supported. + + :param AUTOMATIC: integration can retrieve the proper status of subscription ownership. + :param USER_ENABLED: integration can handle override of ~class::`Subscription.owned` value to True + """ + AUTOMATIC = 1 + USER_ENABLED = 2 diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/errors.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/errors.py new file mode 100644 index 0000000..d5424bc --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/errors.py @@ -0,0 +1,75 @@ +from galaxy.api.jsonrpc import ApplicationError, UnknownError + +assert UnknownError + +class AuthenticationRequired(ApplicationError): + def __init__(self, data=None): + super().__init__(1, "Authentication required", data) + +class BackendNotAvailable(ApplicationError): + def __init__(self, data=None): + super().__init__(2, "Backend not available", data) + +class BackendTimeout(ApplicationError): + def __init__(self, data=None): + super().__init__(3, "Backend timed out", data) + +class BackendError(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend error", data) + +class UnknownBackendResponse(ApplicationError): + def __init__(self, data=None): + super().__init__(4, "Backend responded in unknown way", data) + +class TooManyRequests(ApplicationError): + def __init__(self, data=None): + super().__init__(5, "Too many requests. Try again later", data) + +class InvalidCredentials(ApplicationError): + def __init__(self, data=None): + super().__init__(100, "Invalid credentials", data) + +class NetworkError(ApplicationError): + def __init__(self, data=None): + super().__init__(101, "Network error", data) + +class LoggedInElsewhere(ApplicationError): + def __init__(self, data=None): + super().__init__(102, "Logged in elsewhere", data) + +class ProtocolError(ApplicationError): + def __init__(self, data=None): + super().__init__(103, "Protocol error", data) + +class TemporaryBlocked(ApplicationError): + def __init__(self, data=None): + super().__init__(104, "Temporary blocked", data) + +class Banned(ApplicationError): + def __init__(self, data=None): + super().__init__(105, "Banned", data) + +class AccessDenied(ApplicationError): + def __init__(self, data=None): + super().__init__(106, "Access denied", data) + +class FailedParsingManifest(ApplicationError): + def __init__(self, data=None): + super().__init__(200, "Failed parsing manifest", data) + +class TooManyMessagesSent(ApplicationError): + def __init__(self, data=None): + super().__init__(300, "Too many messages sent", data) + +class IncoherentLastMessage(ApplicationError): + def __init__(self, data=None): + super().__init__(400, "Different last message id on backend", data) + +class MessageNotFound(ApplicationError): + def __init__(self, data=None): + super().__init__(500, "Message not found", data) + +class ImportInProgress(ApplicationError): + def __init__(self, data=None): + super().__init__(600, "Import already in progress", data) diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/importer.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/importer.py new file mode 100644 index 0000000..f958f32 --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/importer.py @@ -0,0 +1,102 @@ +import asyncio +import logging +from galaxy.api.jsonrpc import ApplicationError +from galaxy.api.errors import ImportInProgress, UnknownError + +logger = logging.getLogger(__name__) + + +class Importer: + def __init__( + self, + task_manger, + name, + get, + prepare_context, + notification_success, + notification_failure, + notification_finished, + complete, + ): + self._task_manager = task_manger + self._name = name + self._get = get + self._prepare_context = prepare_context + self._notification_success = notification_success + self._notification_failure = notification_failure + self._notification_finished = notification_finished + self._complete = complete + + self._import_in_progress = False + + async def _import_element(self, id_, context_): + try: + element = await self._get(id_, context_) + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + + async def _import_elements(self, ids_, context_): + try: + imports = [self._import_element(id_, context_) for id_ in ids_] + await asyncio.gather(*imports) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False + + async def start(self, ids): + if self._import_in_progress: + raise ImportInProgress() + + self._import_in_progress = True + try: + context = await self._prepare_context(ids) + self._task_manager.create_task( + self._import_elements(ids, context), + "{} import".format(self._name), + handle_exceptions=False + ) + except: + self._import_in_progress = False + raise + + +class CollectionImporter(Importer): + def __init__(self, notification_partially_finished, *args): + super().__init__(*args) + self._notification_partially_finished = notification_partially_finished + + async def _import_element(self, id_, context_): + try: + async for element in self._get(id_, context_): + self._notification_success(id_, element) + except ApplicationError as error: + self._notification_failure(id_, error) + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Unexpected exception raised in %s importer", self._name) + self._notification_failure(id_, UnknownError()) + finally: + self._notification_partially_finished(id_) + + +class SynchroneousImporter(Importer): + async def _import_elements(self, ids_, context_): + try: + for id_ in ids_: + await self._import_element(id_, context_) + self._notification_finished() + self._complete() + except asyncio.CancelledError: + logger.debug("Importing %s cancelled", self._name) + finally: + self._import_in_progress = False diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/jsonrpc.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/jsonrpc.py new file mode 100644 index 0000000..51ecad3 --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/jsonrpc.py @@ -0,0 +1,367 @@ +import asyncio +from collections import namedtuple +from collections.abc import Iterable +import logging +import inspect +import json + +from galaxy.reader import StreamLineReader +from galaxy.task_manager import TaskManager + + +logger = logging.getLogger(__name__) + + +class JsonRpcError(Exception): + def __init__(self, code, message, data=None): + self.code = code + self.message = message + self.data = data + super().__init__() + + def __eq__(self, other): + return self.code == other.code and self.message == other.message and self.data == other.data + + def json(self): + obj = { + "code": self.code, + "message": self.message + } + + if self.data is not None: + obj["data"] = self.data + + return obj + +class ParseError(JsonRpcError): + def __init__(self): + super().__init__(-32700, "Parse error") + +class InvalidRequest(JsonRpcError): + def __init__(self): + super().__init__(-32600, "Invalid Request") + +class MethodNotFound(JsonRpcError): + def __init__(self): + super().__init__(-32601, "Method not found") + +class InvalidParams(JsonRpcError): + def __init__(self): + super().__init__(-32602, "Invalid params") + +class Timeout(JsonRpcError): + def __init__(self): + super().__init__(-32000, "Method timed out") + +class Aborted(JsonRpcError): + def __init__(self): + super().__init__(-32001, "Method aborted") + +class ApplicationError(JsonRpcError): + def __init__(self, code, message, data): + if code >= -32768 and code <= -32000: + raise ValueError("The error code in reserved range") + super().__init__(code, message, data) + +class UnknownError(ApplicationError): + def __init__(self, data=None): + super().__init__(0, "Unknown error", data) + +Request = namedtuple("Request", ["method", "params", "id"], defaults=[{}, None]) +Response = namedtuple("Response", ["id", "result", "error"], defaults=[None, {}, {}]) +Method = namedtuple("Method", ["callback", "signature", "immediate", "sensitive_params"]) + + +def anonymise_sensitive_params(params, sensitive_params): + anomized_data = "****" + + if isinstance(sensitive_params, bool): + if sensitive_params: + return {k:anomized_data for k,v in params.items()} + + if isinstance(sensitive_params, Iterable): + return {k: anomized_data if k in sensitive_params else v for k, v in params.items()} + + return params + +class Connection(): + def __init__(self, reader, writer, encoder=json.JSONEncoder()): + self._active = True + self._reader = StreamLineReader(reader) + self._writer = writer + self._encoder = encoder + self._methods = {} + self._notifications = {} + self._task_manager = TaskManager("jsonrpc server") + self._last_request_id = 0 + self._requests_futures = {} + + def register_method(self, name, callback, immediate, sensitive_params=False): + """ + Register method + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._methods[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + def register_notification(self, name, callback, immediate, sensitive_params=False): + """ + Register notification + + :param name: + :param callback: + :param internal: if True the callback will be processed immediately (synchronously) + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._notifications[name] = Method(callback, inspect.signature(callback), immediate, sensitive_params) + + async def send_request(self, method, params, sensitive_params): + """ + Send request + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + self._last_request_id += 1 + request_id = str(self._last_request_id) + + loop = asyncio.get_running_loop() + future = loop.create_future() + self._requests_futures[self._last_request_id] = (future, sensitive_params) + + logger.info( + "Sending request: id=%s, method=%s, params=%s", + request_id, method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_request(request_id, method, params) + return await future + + def send_notification(self, method, params, sensitive_params=False): + """ + Send notification + + :param method: + :param params: + :param sensitive_params: list of parameters that are anonymized before logging; \ + if False - no params are considered sensitive, if True - all params are considered sensitive + """ + + logger.info( + "Sending notification: method=%s, params=%s", + method, anonymise_sensitive_params(params, sensitive_params) + ) + + self._send_notification(method, params) + + async def run(self): + while self._active: + try: + data = await self._reader.readline() + if not data: + self._eof() + continue + except: + self._eof() + continue + data = data.strip() + logger.debug("Received %d bytes of data", len(data)) + self._handle_input(data) + await asyncio.sleep(0) # To not starve task queue + + def close(self): + if self._active: + logger.info("Closing JSON-RPC server - not more messages will be read") + self._active = False + + async def wait_closed(self): + await self._task_manager.wait() + + def _eof(self): + logger.info("Received EOF") + self.close() + + def _handle_input(self, data): + try: + message = self._parse_message(data) + except JsonRpcError as error: + self._send_error(None, error) + return + + if isinstance(message, Request): + if message.id is not None: + self._handle_request(message) + else: + self._handle_notification(message) + elif isinstance(message, Response): + self._handle_response(message) + + def _handle_response(self, response): + request_future = self._requests_futures.get(int(response.id)) + if request_future is None: + response_type = "response" if response.result is not None else "error" + logger.warning("Received %s for unknown request: %s", response_type, response.id) + return + + future, sensitive_params = request_future + + if response.error: + error = JsonRpcError( + response.error.setdefault("code", 0), + response.error.setdefault("message", ""), + response.error.setdefault("data", None) + ) + self._log_error(response, error, sensitive_params) + future.set_exception(error) + return + + self._log_response(response, sensitive_params) + future.set_result(response.result) + + def _handle_notification(self, request): + method = self._notifications.get(request.method) + if not method: + logger.error("Received unknown notification: %s", request.method) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + callback(*bound_args.args, **bound_args.kwargs) + else: + try: + self._task_manager.create_task(callback(*bound_args.args, **bound_args.kwargs), request.method) + except Exception: + logger.exception("Unexpected exception raised in notification handler") + + def _handle_request(self, request): + method = self._methods.get(request.method) + if not method: + logger.error("Received unknown request: %s", request.method) + self._send_error(request.id, MethodNotFound()) + return + + callback, signature, immediate, sensitive_params = method + self._log_request(request, sensitive_params) + + try: + bound_args = signature.bind(**request.params) + except TypeError: + self._send_error(request.id, InvalidParams()) + + if immediate: + response = callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, response) + else: + async def handle(): + try: + result = await callback(*bound_args.args, **bound_args.kwargs) + self._send_response(request.id, result) + except NotImplementedError: + self._send_error(request.id, MethodNotFound()) + except JsonRpcError as error: + self._send_error(request.id, error) + except asyncio.CancelledError: + self._send_error(request.id, Aborted()) + except Exception as e: #pylint: disable=broad-except + logger.exception("Unexpected exception raised in plugin handler") + self._send_error(request.id, UnknownError(str(e))) + + self._task_manager.create_task(handle(), request.method) + + @staticmethod + def _parse_message(data): + try: + jsonrpc_message = json.loads(data, encoding="utf-8") + if jsonrpc_message.get("jsonrpc") != "2.0": + raise InvalidRequest() + del jsonrpc_message["jsonrpc"] + if "result" in jsonrpc_message.keys() or "error" in jsonrpc_message.keys(): + return Response(**jsonrpc_message) + else: + return Request(**jsonrpc_message) + + except json.JSONDecodeError: + raise ParseError() + except TypeError: + raise InvalidRequest() + + def _send(self, data, sensitive=True): + try: + line = self._encoder.encode(data) + data = (line + "\n").encode("utf-8") + if sensitive: + logger.debug("Sending %d bytes of data", len(data)) + else: + logging.debug("Sending data: %s", line) + self._writer.write(data) + except TypeError as error: + logger.error(str(error)) + + def _send_response(self, request_id, result): + response = { + "jsonrpc": "2.0", + "id": request_id, + "result": result + } + self._send(response, sensitive=False) + + def _send_error(self, request_id, error): + response = { + "jsonrpc": "2.0", + "id": request_id, + "error": error.json() + } + + self._send(response, sensitive=False) + + def _send_request(self, request_id, method, params): + request = { + "jsonrpc": "2.0", + "method": method, + "id": request_id, + "params": params + } + self._send(request, sensitive=True) + + def _send_notification(self, method, params): + notification = { + "jsonrpc": "2.0", + "method": method, + "params": params + } + self._send(notification, sensitive=True) + + @staticmethod + def _log_request(request, sensitive_params): + params = anonymise_sensitive_params(request.params, sensitive_params) + if request.id is not None: + logger.info("Handling request: id=%s, method=%s, params=%s", request.id, request.method, params) + else: + logger.info("Handling notification: method=%s, params=%s", request.method, params) + + @staticmethod + def _log_response(response, sensitive_params): + result = anonymise_sensitive_params(response.result, sensitive_params) + logger.info("Handling response: id=%s, result=%s", response.id, result) + + @staticmethod + def _log_error(response, error, sensitive_params): + params = error.data if error.data is not None else {} + data = anonymise_sensitive_params(params, sensitive_params) + logger.info("Handling error: id=%s, code=%s, description=%s, data=%s", + response.id, error.code, error.message, data + ) diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/plugin.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/plugin.py new file mode 100644 index 0000000..9a746d2 --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/plugin.py @@ -0,0 +1,1142 @@ +import asyncio +import dataclasses +import json +import logging +import sys +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union, AsyncGenerator + +from galaxy.api.consts import Feature, OSCompatibility +from galaxy.api.jsonrpc import ApplicationError, Connection +from galaxy.api.types import ( + Achievement, Authentication, Game, GameLibrarySettings, GameTime, LocalGame, NextStep, UserInfo, UserPresence, + Subscription, SubscriptionGame +) +from galaxy.task_manager import TaskManager +from galaxy.api.importer import Importer, CollectionImporter, SynchroneousImporter + + +logger = logging.getLogger(__name__) + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): # pylint: disable=method-hidden + if dataclasses.is_dataclass(o): + # filter None values + def dict_factory(elements): + return {k: v for k, v in elements if v is not None} + + return dataclasses.asdict(o, dict_factory=dict_factory) + if isinstance(o, Enum): + return o.value + return super().default(o) + + +class Plugin: + """Use and override methods of this class to create a new platform integration.""" + + def __init__(self, platform, version, reader, writer, handshake_token): + logger.info("Creating plugin for platform %s, version %s", platform.value, version) + self._platform = platform + self._version = version + + self._features: Set[Feature] = set() + self._active = True + + self._reader, self._writer = reader, writer + self._handshake_token = handshake_token + + encoder = JSONEncoder() + self._connection = Connection(self._reader, self._writer, encoder) + + self._persistent_cache = dict() + + self._internal_task_manager = TaskManager("plugin internal") + self._external_task_manager = TaskManager("plugin external") + + self._achievements_importer = Importer( + self._external_task_manager, + "achievements", + self.get_unlocked_achievements, + self.prepare_achievements_context, + self._game_achievements_import_success, + self._game_achievements_import_failure, + self._achievements_import_finished, + self.achievements_import_complete + ) + self._game_time_importer = Importer( + self._external_task_manager, + "game times", + self.get_game_time, + self.prepare_game_times_context, + self._game_time_import_success, + self._game_time_import_failure, + self._game_times_import_finished, + self.game_times_import_complete + ) + self._game_library_settings_importer = Importer( + self._external_task_manager, + "game library settings", + self.get_game_library_settings, + self.prepare_game_library_settings_context, + self._game_library_settings_import_success, + self._game_library_settings_import_failure, + self._game_library_settings_import_finished, + self.game_library_settings_import_complete + ) + self._os_compatibility_importer = Importer( + self._external_task_manager, + "os compatibility", + self.get_os_compatibility, + self.prepare_os_compatibility_context, + self._os_compatibility_import_success, + self._os_compatibility_import_failure, + self._os_compatibility_import_finished, + self.os_compatibility_import_complete + ) + self._user_presence_importer = Importer( + self._external_task_manager, + "users presence", + self.get_user_presence, + self.prepare_user_presence_context, + self._user_presence_import_success, + self._user_presence_import_failure, + self._user_presence_import_finished, + self.user_presence_import_complete + ) + self._local_size_importer = SynchroneousImporter( + self._external_task_manager, + "local size", + self.get_local_size, + self.prepare_local_size_context, + self._local_size_import_success, + self._local_size_import_failure, + self._local_size_import_finished, + self.local_size_import_complete + ) + self._subscription_games_importer = CollectionImporter( + self._subscriptions_games_partial_import_finished, + self._external_task_manager, + "subscription games", + self.get_subscription_games, + self.prepare_subscription_games_context, + self._subscription_games_import_success, + self._subscription_games_import_failure, + self._subscription_games_import_finished, + self.subscription_games_import_complete + ) + + # internal + self._register_method("shutdown", self._shutdown, internal=True) + self._register_method("get_capabilities", self._get_capabilities, internal=True, immediate=True) + self._register_method( + "initialize_cache", + self._initialize_cache, + internal=True, + immediate=True, + sensitive_params="data" + ) + self._register_method("ping", self._ping, internal=True, immediate=True) + + # implemented by developer + self._register_method( + "init_authentication", + self.authenticate, + sensitive_params=["stored_credentials"] + ) + self._register_method( + "pass_login_credentials", + self.pass_login_credentials, + sensitive_params=["cookies", "credentials"] + ) + self._register_method( + "import_owned_games", + self.get_owned_games, + result_name="owned_games" + ) + self._detect_feature(Feature.ImportOwnedGames, ["get_owned_games"]) + + self._register_method("start_achievements_import", self._start_achievements_import) + self._detect_feature(Feature.ImportAchievements, ["get_unlocked_achievements"]) + + self._register_method("import_local_games", self.get_local_games, result_name="local_games") + self._detect_feature(Feature.ImportInstalledGames, ["get_local_games"]) + + self._register_notification("launch_game", self.launch_game) + self._detect_feature(Feature.LaunchGame, ["launch_game"]) + + self._register_notification("install_game", self.install_game) + self._detect_feature(Feature.InstallGame, ["install_game"]) + + self._register_notification("uninstall_game", self.uninstall_game) + self._detect_feature(Feature.UninstallGame, ["uninstall_game"]) + + self._register_notification("shutdown_platform_client", self.shutdown_platform_client) + self._detect_feature(Feature.ShutdownPlatformClient, ["shutdown_platform_client"]) + + self._register_notification("launch_platform_client", self.launch_platform_client) + self._detect_feature(Feature.LaunchPlatformClient, ["launch_platform_client"]) + + self._register_method("import_friends", self.get_friends, result_name="friend_info_list") + self._detect_feature(Feature.ImportFriends, ["get_friends"]) + + self._register_method("start_game_times_import", self._start_game_times_import) + self._detect_feature(Feature.ImportGameTime, ["get_game_time"]) + + self._register_method("start_game_library_settings_import", self._start_game_library_settings_import) + self._detect_feature(Feature.ImportGameLibrarySettings, ["get_game_library_settings"]) + + self._register_method("start_os_compatibility_import", self._start_os_compatibility_import) + self._detect_feature(Feature.ImportOSCompatibility, ["get_os_compatibility"]) + + self._register_method("start_user_presence_import", self._start_user_presence_import) + self._detect_feature(Feature.ImportUserPresence, ["get_user_presence"]) + + self._register_method("start_local_size_import", self._start_local_size_import) + self._detect_feature(Feature.ImportLocalSize, ["get_local_size"]) + + self._register_method("import_subscriptions", self.get_subscriptions, result_name="subscriptions") + self._detect_feature(Feature.ImportSubscriptions, ["get_subscriptions"]) + + self._register_method("start_subscription_games_import", self._start_subscription_games_import) + self._detect_feature(Feature.ImportSubscriptionGames, ["get_subscription_games"]) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + self.close() + await self.wait_closed() + + @property + def features(self) -> List[Feature]: + return list(self._features) + + @property + def persistent_cache(self) -> Dict[str, str]: + """The cache is only available after the :meth:`~.handshake_complete()` is called. + """ + return self._persistent_cache + + def _implements(self, methods: List[str]) -> bool: + for method in methods: + if method not in self.__class__.__dict__: + return False + return True + + def _detect_feature(self, feature: Feature, methods: List[str]): + if self._implements(methods): + self._features.add(feature) + + def _register_method(self, name, handler, result_name=None, internal=False, immediate=False, + sensitive_params=False): + def wrap_result(result): + if result_name: + result = { + result_name: result + } + return result + + if immediate: + def method(*args, **kwargs): + result = handler(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, True, sensitive_params) + else: + async def method(*args, **kwargs): + if not internal: + handler_ = self._wrap_external_method(handler, name) + else: + handler_ = handler + result = await handler_(*args, **kwargs) + return wrap_result(result) + + self._connection.register_method(name, method, False, sensitive_params) + + def _register_notification(self, name, handler, internal=False, immediate=False, sensitive_params=False): + if not internal and not immediate: + handler = self._wrap_external_method(handler, name) + self._connection.register_notification(name, handler, immediate, sensitive_params) + + def _wrap_external_method(self, handler, name: str): + async def wrapper(*args, **kwargs): + return await self._external_task_manager.create_task(handler(*args, **kwargs), name, False) + + return wrapper + + async def run(self): + """Plugin's main coroutine.""" + await self._connection.run() + logger.debug("Plugin run loop finished") + + def close(self) -> None: + if not self._active: + return + + logger.info("Closing plugin") + self._connection.close() + self._external_task_manager.cancel() + + async def shutdown(): + try: + await asyncio.wait_for(self.shutdown(), 30) + except asyncio.TimeoutError: + logging.warning("Plugin shutdown timed out") + + self._internal_task_manager.create_task(shutdown(), "shutdown") + self._active = False + + async def wait_closed(self) -> None: + logger.debug("Waiting for plugin to close") + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + await self._connection.wait_closed() + logger.debug("Plugin closed") + + def create_task(self, coro, description): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + return self._external_task_manager.create_task(coro, description) + + async def _pass_control(self): + while self._active: + try: + self.tick() + except Exception: + logger.exception("Unexpected exception raised in plugin tick") + await asyncio.sleep(1) + + async def _shutdown(self): + logger.info("Shutting down") + self.close() + await self._external_task_manager.wait() + await self._internal_task_manager.wait() + + def _get_capabilities(self): + return { + "platform_name": self._platform, + "features": self.features, + "token": self._handshake_token + } + + def _initialize_cache(self, data: Dict): + self._persistent_cache = data + try: + self.handshake_complete() + except Exception: + logger.exception("Unhandled exception during `handshake_complete` step") + self._internal_task_manager.create_task(self._pass_control(), "tick") + + @staticmethod + def _ping(): + pass + + # notifications + def store_credentials(self, credentials: Dict[str, Any]) -> None: + """Notify the client to store authentication credentials. + Credentials are passed on the next authenticate call. + + :param credentials: credentials that client will store; they are stored locally on a user pc + + Example use case of store_credentials: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + # temporary solution for persistent_cache vs credentials issue + self.persistent_cache["credentials"] = credentials # type: ignore + + self._connection.send_notification("store_credentials", credentials, sensitive_params=True) + + def add_game(self, game: Game) -> None: + """Notify the client to add game to the list of owned games + of the currently authenticated user. + + :param game: Game to add to the list of owned games + + Example use case of add_game: + + .. code-block:: python + :linenos: + + async def check_for_new_games(self): + games = await self.get_owned_games() + for game in games: + if game not in self.owned_games_cache: + self.owned_games_cache.append(game) + self.add_game(game) + + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_added", params) + + def remove_game(self, game_id: str) -> None: + """Notify the client to remove game from the list of owned games + of the currently authenticated user. + + :param game_id: the id of the game to remove from the list of owned games + + Example use case of remove_game: + + .. code-block:: python + :linenos: + + async def check_for_removed_games(self): + games = await self.get_owned_games() + for game in self.owned_games_cache: + if game not in games: + self.owned_games_cache.remove(game) + self.remove_game(game.game_id) + + """ + params = {"game_id": game_id} + self._connection.send_notification("owned_game_removed", params) + + def update_game(self, game: Game) -> None: + """Notify the client to update the status of a game + owned by the currently authenticated user. + + :param game: Game to update + """ + params = {"owned_game": game} + self._connection.send_notification("owned_game_updated", params) + + def unlock_achievement(self, game_id: str, achievement: Achievement) -> None: + """Notify the client to unlock an achievement for a specific game. + + :param game_id: the id of the game for which to unlock an achievement. + :param achievement: achievement to unlock. + """ + params = { + "game_id": game_id, + "achievement": achievement + } + self._connection.send_notification("achievement_unlocked", params) + + def _game_achievements_import_success(self, game_id: str, achievements: List[Achievement]) -> None: + params = { + "game_id": game_id, + "unlocked_achievements": achievements + } + self._connection.send_notification("game_achievements_import_success", params) + + def _game_achievements_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_achievements_import_failure", params) + + def _achievements_import_finished(self) -> None: + self._connection.send_notification("achievements_import_finished", None) + + def update_local_game_status(self, local_game: LocalGame) -> None: + """Notify the client to update the status of a local game. + + :param local_game: the LocalGame to update + + Example use case triggered by the :meth:`.tick` method: + + .. code-block:: python + :linenos: + :emphasize-lines: 5 + + async def _check_statuses(self): + for game in await self._get_local_games(): + if game.status == self._cached_game_statuses.get(game.id): + continue + self.update_local_game_status(LocalGame(game.id, game.status)) + self._cached_games_statuses[game.id] = game.status + await asyncio.sleep(5) # interval + + def tick(self): + if self._check_statuses_task is None or self._check_statuses_task.done(): + self._check_statuses_task = asyncio.create_task(self._check_statuses()) + """ + params = {"local_game": local_game} + self._connection.send_notification("local_game_status_changed", params) + + def add_friend(self, user: UserInfo) -> None: + """Notify the client to add a user to friends list of the currently authenticated user. + + :param user: UserInfo of a user that the client will add to friends list + """ + params = {"friend_info": user} + self._connection.send_notification("friend_added", params) + + def remove_friend(self, user_id: str) -> None: + """Notify the client to remove a user from friends list of the currently authenticated user. + + :param user_id: id of the user to remove from friends list + """ + params = {"user_id": user_id} + self._connection.send_notification("friend_removed", params) + + def update_friend_info(self, user: UserInfo) -> None: + """Notify the client about the updated friend information. + + :param user: UserInfo of a friend whose info was updated + """ + self._connection.send_notification("friend_updated", params={"friend_info": user}) + + def update_game_time(self, game_time: GameTime) -> None: + """Notify the client to update game time for a game. + + :param game_time: game time to update + """ + params = {"game_time": game_time} + self._connection.send_notification("game_time_updated", params) + + def update_user_presence(self, user_id: str, user_presence: UserPresence) -> None: + """Notify the client about the updated user presence information. + + :param user_id: the id of the user whose presence information is updated + :param user_presence: presence information of the specified user + """ + self._connection.send_notification( + "user_presence_updated", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _game_time_import_success(self, game_id: str, game_time: GameTime) -> None: + params = {"game_time": game_time} + self._connection.send_notification("game_time_import_success", params) + + def _game_time_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_time_import_failure", params) + + def _game_times_import_finished(self) -> None: + self._connection.send_notification("game_times_import_finished", None) + + def _game_library_settings_import_success(self, game_id: str, game_library_settings: GameLibrarySettings) -> None: + params = {"game_library_settings": game_library_settings} + self._connection.send_notification("game_library_settings_import_success", params) + + def _game_library_settings_import_failure(self, game_id: str, error: ApplicationError) -> None: + params = { + "game_id": game_id, + "error": error.json() + } + self._connection.send_notification("game_library_settings_import_failure", params) + + def _game_library_settings_import_finished(self) -> None: + self._connection.send_notification("game_library_settings_import_finished", None) + + def _os_compatibility_import_success(self, game_id: str, os_compatibility: Optional[OSCompatibility]) -> None: + self._connection.send_notification( + "os_compatibility_import_success", + { + "game_id": game_id, + "os_compatibility": os_compatibility + } + ) + + def _os_compatibility_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "os_compatibility_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _os_compatibility_import_finished(self) -> None: + self._connection.send_notification("os_compatibility_import_finished", None) + + def _user_presence_import_success(self, user_id: str, user_presence: UserPresence) -> None: + self._connection.send_notification( + "user_presence_import_success", + { + "user_id": user_id, + "presence": user_presence + } + ) + + def _user_presence_import_failure(self, user_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "user_presence_import_failure", + { + "user_id": user_id, + "error": error.json() + } + ) + + def _user_presence_import_finished(self) -> None: + self._connection.send_notification("user_presence_import_finished", None) + + def _local_size_import_success(self, game_id: str, size: Optional[int]) -> None: + self._connection.send_notification( + "local_size_import_success", + { + "game_id": game_id, + "local_size": size + } + ) + + def _local_size_import_failure(self, game_id: str, error: ApplicationError) -> None: + self._connection.send_notification( + "local_size_import_failure", + { + "game_id": game_id, + "error": error.json() + } + ) + + def _local_size_import_finished(self) -> None: + self._connection.send_notification("local_size_import_finished", None) + + def _subscription_games_import_success(self, subscription_name: str, + subscription_games: Optional[List[SubscriptionGame]]) -> None: + self._connection.send_notification( + "subscription_games_import_success", + { + "subscription_name": subscription_name, + "subscription_games": subscription_games + } + ) + + def _subscription_games_import_failure(self, subscription_name: str, error: ApplicationError) -> None: + self._connection.send_notification( + "subscription_games_import_failure", + { + "subscription_name": subscription_name, + "error": error.json() + } + ) + + def _subscriptions_games_partial_import_finished(self, subscription_name: str) -> None: + self._connection.send_notification( + "subscription_games_partial_import_finished", + { + "subscription_name": subscription_name + } + ) + + def _subscription_games_import_finished(self) -> None: + self._connection.send_notification("subscription_games_import_finished", None) + + def lost_authentication(self) -> None: + """Notify the client that integration has lost authentication for the + current user and is unable to perform actions which would require it. + """ + self._connection.send_notification("authentication_lost", None) + + def push_cache(self) -> None: + """Push local copy of the persistent cache to the GOG Galaxy Client replacing existing one. + """ + self._connection.send_notification( + "push_cache", + params={"data": self._persistent_cache}, + sensitive_params="data" + ) + + async def refresh_credentials(self, params: Dict[str, Any], sensitive_params) -> Dict[str, Any]: + return await self._connection.send_request("refresh_credentials", params, sensitive_params) + + # handlers + def handshake_complete(self) -> None: + """This method is called right after the handshake with the GOG Galaxy Client is complete and + before any other operations are called by the GOG Galaxy Client. + Persistent cache is available when this method is called. + Override it if you need to do additional plugin initializations. + This method is called internally.""" + + def tick(self) -> None: + """This method is called periodically. + Override it to implement periodical non-blocking tasks. + This method is called internally. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + def tick(self): + if not self.checking_for_new_games: + asyncio.create_task(self.check_for_new_games()) + if not self.checking_for_removed_games: + asyncio.create_task(self.check_for_removed_games()) + if not self.updating_game_statuses: + asyncio.create_task(self.update_game_statuses()) + + """ + + async def shutdown(self) -> None: + """This method is called on integration shutdown. + Override it to implement tear down. + This method is called by the GOG Galaxy Client.""" + + # methods + async def authenticate(self, stored_credentials: Optional[Dict] = None) -> Union[NextStep, Authentication]: + """Override this method to handle user authentication. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another url. + This method is called by the GOG Galaxy Client. + + :param stored_credentials: If the client received any credentials to store locally + in the previous session they will be passed here as a parameter. + + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES) + else: + try: + user_data = self._authenticate(stored_credentials) + except AccessDenied: + raise InvalidCredentials() + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]) \ + -> Union[NextStep, Authentication]: + """This method is called if we return :class:`~galaxy.api.types.NextStep` from :meth:`.authenticate` + or :meth:`.pass_login_credentials`. + This method's parameters provide the data extracted from the web page navigation that previous NextStep finished on. + This method should either return :class:`~galaxy.api.types.Authentication` if the authentication is finished + or :class:`~galaxy.api.types.NextStep` if it requires going to another cef url. + This method is called by the GOG Galaxy Client. + + :param step: deprecated. + :param credentials: end_uri previous NextStep finished on. + :param cookies: cookies extracted from the end_uri site. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def pass_login_credentials(self, step, credentials, cookies): + if self.got_everything(credentials,cookies): + user_data = await self.parse_credentials(credentials,cookies) + else: + next_params = self.get_next_params(credentials,cookies) + next_cookies = self.get_next_cookies(credentials,cookies) + return NextStep("web_session", next_params, cookies=next_cookies) + self.store_credentials(user_data['credentials']) + return Authentication(user_data['userId'], user_data['username']) + + """ + raise NotImplementedError() + + async def get_owned_games(self) -> List[Game]: + """Override this method to return owned games for currently logged in user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_owned_games(self): + if not self.authenticated(): + raise AuthenticationRequired() + + games = self.retrieve_owned_games() + return games + + """ + raise NotImplementedError() + + async def _start_achievements_import(self, game_ids: List[str]) -> None: + await self._achievements_importer.start(game_ids) + + async def prepare_achievements_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_unlocked_achievements. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which achievements are imported + :return: context + """ + return None + + async def get_unlocked_achievements(self, game_id: str, context: Any) -> List[Achievement]: + """Override this method to return list of unlocked achievements + for the game identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the achievements are returned + :param context: the value returned from :meth:`prepare_achievements_context` + :return: list of Achievement objects + """ + raise NotImplementedError() + + def achievements_import_complete(self): + """Override this method to handle operations after achievements import is finished + (like updating cache). + """ + + async def get_local_games(self) -> List[LocalGame]: + """Override this method to return the list of + games present locally on the users pc. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_local_games(self): + local_games = [] + for game in self.games_present_on_user_pc: + local_game = LocalGame() + local_game.game_id = game.id + local_game.local_game_state = game.get_installation_status() + local_games.append(local_game) + return local_games + + """ + raise NotImplementedError() + + async def launch_game(self, game_id: str) -> None: + """Override this method to launch the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to launch + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def launch_game(self, game_id): + await self.open_uri(f"start client://launchgame/{game_id}") + + """ + raise NotImplementedError() + + async def install_game(self, game_id: str) -> None: + """Override this method to install the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to install + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def install_game(self, game_id): + await self.open_uri(f"start client://installgame/{game_id}") + + """ + raise NotImplementedError() + + async def uninstall_game(self, game_id: str) -> None: + """Override this method to uninstall the game + identified by the provided game_id. + This method is called by the GOG Galaxy Client. + + :param str game_id: the id of the game to uninstall + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def uninstall_game(self, game_id): + await self.open_uri(f"start client://uninstallgame/{game_id}") + + """ + raise NotImplementedError() + + async def shutdown_platform_client(self) -> None: + """Override this method to gracefully terminate platform client. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def launch_platform_client(self) -> None: + """Override this method to launch platform client. Preferably minimized to tray. + This method is called by the GOG Galaxy Client.""" + raise NotImplementedError() + + async def get_friends(self) -> List[UserInfo]: + """Override this method to return the friends list + of the currently authenticated user. + This method is called by the GOG Galaxy Client. + + Example of possible override of the method: + + .. code-block:: python + :linenos: + + async def get_friends(self): + if not self._http_client.is_authenticated(): + raise AuthenticationRequired() + + friends = self.retrieve_friends() + return friends + + """ + raise NotImplementedError() + + async def _start_game_times_import(self, game_ids: List[str]) -> None: + await self._game_time_importer.start(game_ids) + + async def prepare_game_times_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_time. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game time are imported + :return: context + """ + return None + + async def get_game_time(self, game_id: str, context: Any) -> GameTime: + """Override this method to return the game time for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game time is returned + :param context: the value returned from :meth:`prepare_game_times_context` + :return: GameTime object + """ + raise NotImplementedError() + + def game_times_import_complete(self) -> None: + """Override this method to handle operations after game times import is finished + (like updating cache). + """ + + async def _start_game_library_settings_import(self, game_ids: List[str]) -> None: + await self._game_library_settings_importer.start(game_ids) + + async def prepare_game_library_settings_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_game_library_settings. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game library settings are imported + :return: context + """ + return None + + async def get_game_library_settings(self, game_id: str, context: Any) -> GameLibrarySettings: + """Override this method to return the game library settings for the game + identified by the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game library settings are imported + :param context: the value returned from :meth:`prepare_game_library_settings_context` + :return: GameLibrarySettings object + """ + raise NotImplementedError() + + def game_library_settings_import_complete(self) -> None: + """Override this method to handle operations after game library settings import is finished + (like updating cache). + """ + + async def _start_os_compatibility_import(self, game_ids: List[str]) -> None: + await self._os_compatibility_importer.start(game_ids) + + async def prepare_os_compatibility_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for get_os_compatibility. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param game_ids: the ids of the games for which game os compatibility is imported + :return: context + """ + return None + + async def get_os_compatibility(self, game_id: str, context: Any) -> Optional[OSCompatibility]: + """Override this method to return the OS compatibility for the game with the provided game_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param game_id: the id of the game for which the game os compatibility is imported + :param context: the value returned from :meth:`prepare_os_compatibility_context` + :return: OSCompatibility flags indicating compatible OSs, or None if compatibility is not know + """ + raise NotImplementedError() + + def os_compatibility_import_complete(self) -> None: + """Override this method to handle operations after OS compatibility import is finished (like updating cache).""" + + async def _start_user_presence_import(self, user_id_list: List[str]) -> None: + await self._user_presence_importer.start(user_id_list) + + async def prepare_user_presence_context(self, user_id_list: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_user_presence`. + This allows for optimizations like batch requests to platform API. + Default implementation returns None. + + :param user_id_list: the ids of the users for whom presence information is imported + :return: context + """ + return None + + async def get_user_presence(self, user_id: str, context: Any) -> UserPresence: + """Override this method to return presence information for the user with the provided user_id. + This method is called by import task initialized by GOG Galaxy Client. + + :param user_id: the id of the user for whom presence information is imported + :param context: the value returned from :meth:`prepare_user_presence_context` + :return: UserPresence presence information of the provided user + """ + raise NotImplementedError() + + def user_presence_import_complete(self) -> None: + """Override this method to handle operations after presence import is finished (like updating cache).""" + + async def _start_local_size_import(self, game_ids: List[str]) -> None: + await self._local_size_importer.start(game_ids) + + async def prepare_local_size_context(self, game_ids: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_local_size` + Default implementation returns None. + + :param game_ids: the ids of the games for which information about size is imported + :return: context + """ + return None + + async def get_local_size(self, game_id: str, context: Any) -> Optional[int]: + """Override this method to return installed game size. + + .. note:: + It is preferable to avoid iterating over local game files when overriding this method. + If possible, please use a more efficient way of game size retrieval. + + :param game_id: the id of the installed game + :param context: the value returned from :meth:`prepare_local_size_context` + :return: the size of the game on a user-owned storage device (in bytes) or `None` if the size cannot be determined + """ + raise NotImplementedError() + + def local_size_import_complete(self) -> None: + """Override this method to handle operations after local game size import is finished (like updating cache).""" + + async def get_subscriptions(self) -> List[Subscription]: + """Override this method to return a list of + Subscriptions available on platform. + This method is called by the GOG Galaxy Client. + """ + raise NotImplementedError() + + async def _start_subscription_games_import(self, subscription_names: List[str]) -> None: + await self._subscription_games_importer.start(subscription_names) + + async def prepare_subscription_games_context(self, subscription_names: List[str]) -> Any: + """Override this method to prepare context for :meth:`get_subscription_games` + Default implementation returns None. + + :param subscription_names: the names of the subscriptions' for which subscriptions games are imported + :return: context + """ + return None + + async def get_subscription_games(self, subscription_name: str, context: Any) -> AsyncGenerator[ + List[SubscriptionGame], None]: + """Override this method to provide SubscriptionGames for a given subscription. + This method should `yield` a list of SubscriptionGames -> yield [sub_games] + + This method will only be used if :meth:`get_subscriptions` has been implemented. + + :param context: the value returned from :meth:`prepare_subscription_games_context` + :return a generator object that yields SubscriptionGames + + .. code-block:: python + :linenos: + + async def get_subscription_games(subscription_name: str, context: Any): + while True: + games_page = await self._get_subscriptions_from_backend(subscription_name, i) + if not games_pages: + yield None + yield [SubGame(game['game_id'], game['game_title']) for game in games_page] + + """ + raise NotImplementedError() + + def subscription_games_import_complete(self) -> None: + """Override this method to handle operations after + subscription games import is finished (like updating cache). + """ + + +def create_and_run_plugin(plugin_class, argv): + """Call this method as an entry point for the implemented integration. + + :param plugin_class: your plugin class. + :param argv: command line arguments with which the script was started. + + Example of possible use of the method: + + .. code-block:: python + :linenos: + + def main(): + create_and_run_plugin(PlatformPlugin, sys.argv) + + if __name__ == "__main__": + main() + """ + if len(argv) < 3: + logger.critical("Not enough parameters, required: token, port") + sys.exit(1) + + token = argv[1] + + try: + port = int(argv[2]) + except ValueError: + logger.critical("Failed to parse port value: %s", argv[2]) + sys.exit(2) + + if not (1 <= port <= 65535): + logger.critical("Port value out of range (1, 65535)") + sys.exit(3) + + if not issubclass(plugin_class, Plugin): + logger.critical("plugin_class must be subclass of Plugin") + sys.exit(4) + + async def coroutine(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + extra_info = writer.get_extra_info("sockname") + logger.info("Using local address: %s:%u", *extra_info) + async with plugin_class(reader, writer, token) as plugin: + await plugin.run() + finally: + writer.close() + await writer.wait_closed() + + try: + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) + + asyncio.run(coroutine()) + except Exception: + logger.exception("Error while running plugin") + sys.exit(5) diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/types.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/types.py new file mode 100644 index 0000000..7fd0031 --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/api/types.py @@ -0,0 +1,257 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional + +from galaxy.api.consts import LicenseType, LocalGameState, PresenceState, SubscriptionDiscovery + + +@dataclass +class Authentication: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` + to inform the client that authentication has successfully finished. + + :param user_id: id of the authenticated user + :param user_name: username of the authenticated user + """ + user_id: str + user_name: str + + +@dataclass +class Cookie: + """Cookie + + :param name: name of the cookie + :param value: value of the cookie + :param domain: optional domain of the cookie + :param path: optional path of the cookie + """ + name: str + value: str + domain: Optional[str] = None + path: Optional[str] = None + + +@dataclass +class NextStep: + """Return this from :meth:`.authenticate` or :meth:`.pass_login_credentials` to open client built-in browser with given url. + For example: + + .. code-block:: python + :linenos: + + PARAMS = { + "window_title": "Login to platform", + "window_width": 800, + "window_height": 600, + "start_uri": URL, + "end_uri_regex": r"^https://platform_website\.com/.*" + } + + JS = {r"^https://platform_website\.com/.*": [ + r''' + location.reload(); + ''' + ]} + + COOKIES = [Cookie("Cookie1", "ok", ".platform.com"), + Cookie("Cookie2", "ok", ".platform.com") + ] + + async def authenticate(self, stored_credentials=None): + if not stored_credentials: + return NextStep("web_session", PARAMS, cookies=COOKIES, js=JS) + + :param auth_params: configuration options: {"window_title": :class:`str`, "window_width": :class:`str`, + "window_height": :class:`int`, "start_uri": :class:`int`, "end_uri_regex": :class:`str`} + :param cookies: browser initial set of cookies + :param js: a map of the url regex patterns into the list of *js* scripts that should be executed + on every document at given step of internal browser authentication. + """ + next_step: str + auth_params: Dict[str, str] + cookies: Optional[List[Cookie]] = None + js: Optional[Dict[str, List[str]]] = None + + +@dataclass +class LicenseInfo: + """Information about the license of related product. + + :param license_type: type of license + :param owner: optional owner of the related product, defaults to currently authenticated user + """ + license_type: LicenseType + owner: Optional[str] = None + + +@dataclass +class Dlc: + """Downloadable content object. + + :param dlc_id: id of the dlc + :param dlc_title: title of the dlc + :param license_info: information about the license attached to the dlc + """ + dlc_id: str + dlc_title: str + license_info: LicenseInfo + + +@dataclass +class Game: + """Game object. + + :param game_id: unique identifier of the game, this will be passed as parameter for methods such as launch_game + :param game_title: title of the game + :param dlcs: list of dlcs available for the game + :param license_info: information about the license attached to the game + """ + game_id: str + game_title: str + dlcs: Optional[List[Dlc]] + license_info: LicenseInfo + + +@dataclass +class Achievement: + """Achievement, has to be initialized with either id or name. + + :param unlock_time: unlock time of the achievement + :param achievement_id: optional id of the achievement + :param achievement_name: optional name of the achievement + """ + unlock_time: int + achievement_id: Optional[str] = None + achievement_name: Optional[str] = None + + def __post_init__(self): + assert self.achievement_id or self.achievement_name, \ + "One of achievement_id or achievement_name is required" + + +@dataclass +class LocalGame: + """Game locally present on the authenticated user's computer. + + :param game_id: id of the game + :param local_game_state: state of the game + """ + game_id: str + local_game_state: LocalGameState + + +@dataclass +class FriendInfo: + """ + .. deprecated:: 0.56 + Use :class:`UserInfo`. + + Information about a friend of the currently authenticated user. + + :param user_id: id of the user + :param user_name: username of the user + """ + user_id: str + user_name: str + + +@dataclass +class UserInfo: + """Information about a user of related user. + + :param user_id: id of the user + :param user_name: username of the user + :param avatar_url: the URL of the user avatar + :param profile_url: the URL of the user profile + """ + user_id: str + user_name: str + avatar_url: Optional[str] + profile_url: Optional[str] + + +@dataclass +class GameTime: + """Game time of a game, defines the total time spent in the game + and the last time the game was played. + + :param game_id: id of the related game + :param time_played: the total time spent in the game in **minutes** + :param last_played_time: last time the game was played (**unix timestamp**) + """ + game_id: str + time_played: Optional[int] + last_played_time: Optional[int] + + +@dataclass +class GameLibrarySettings: + """Library settings of a game, defines assigned tags and visibility flag. + + :param game_id: id of the related game + :param tags: collection of tags assigned to the game + :param hidden: indicates if the game should be hidden in GOG Galaxy client + """ + game_id: str + tags: Optional[List[str]] + hidden: Optional[bool] + + +@dataclass +class UserPresence: + """Presence information of a user. + + The GOG Galaxy client will prefer to generate user status basing on `game_id` (or `game_title`) + and `in_game_status` fields but if plugin is not capable of delivering it then the `full_status` will be used if + available + + :param presence_state: the state of the user + :param game_id: id of the game a user is currently in + :param game_title: name of the game a user is currently in + :param in_game_status: status set by the game itself e.x. "In Main Menu" + :param full_status: full user status e.x. "Playing : " + """ + presence_state: PresenceState + game_id: Optional[str] = None + game_title: Optional[str] = None + in_game_status: Optional[str] = None + full_status: Optional[str] = None + + +@dataclass +class Subscription: + """Information about a subscription. + + :param subscription_name: name of the subscription, will also be used as its identifier. + :param owned: whether the subscription is owned or not, None if unknown. + :param end_time: unix timestamp of when the subscription ends, None if unknown. + :param subscription_discovery: combination of settings that can be manually + chosen by user to determine subscription handling behaviour. For example, if the integration cannot retrieve games + for subscription when user doesn't own it, then USER_ENABLED should not be used. + If the integration cannot determine subscription ownership for a user then AUTOMATIC should not be used. + + """ + subscription_name: str + owned: Optional[bool] = None + end_time: Optional[int] = None + subscription_discovery: SubscriptionDiscovery = SubscriptionDiscovery.AUTOMATIC | \ + SubscriptionDiscovery.USER_ENABLED + + def __post_init__(self): + assert self.subscription_discovery in [SubscriptionDiscovery.AUTOMATIC, SubscriptionDiscovery.USER_ENABLED, + SubscriptionDiscovery.AUTOMATIC | SubscriptionDiscovery.USER_ENABLED] + + +@dataclass +class SubscriptionGame: + """Information about a game from a subscription. + + :param game_title: title of the game + :param game_id: id of the game + :param start_time: unix timestamp of when the game has been added to subscription + :param end_time: unix timestamp of when the game will be removed from subscription. + """ + game_title: str + game_id: str + start_time: Optional[int] = None + end_time: Optional[int] = None diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/http.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/http.py new file mode 100644 index 0000000..a5bc76a --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/http.py @@ -0,0 +1,147 @@ +""" +This module standardizes http traffic and the error handling for further communication with the GOG Galaxy 2.0. + +It is recommended to use provided convenient methods for HTTP requests, especially when dealing with authorized sessions. +Exemplary simple web service could looks like: + + .. code-block:: python + + from galaxy.http import create_client_session, handle_exception + + class BackendClient: + AUTH_URL = 'my-integration.com/auth' + HEADERS = { + "My-Custom-Header": "true", + } + def __init__(self): + self._session = create_client_session(headers=self.HEADERS) + + async def authenticate(self): + await self._session.request('POST', self.AUTH_URL) + + async def close(self): + # to be called on plugin shutdown + await self._session.close() + + async def _authorized_request(self, method, url, *args, **kwargs): + with handle_exceptions(): + return await self._session.request(method, url, *args, **kwargs) +""" + +import asyncio +import ssl +from contextlib import contextmanager +from http import HTTPStatus + +import aiohttp +import certifi +import logging + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, + TooManyRequests, UnknownBackendResponse, UnknownError +) + + +logger = logging.getLogger(__name__) + +#: Default limit of the simultaneous connections for ssl connector. +DEFAULT_LIMIT = 20 +#: Default timeout in seconds used for client session. +DEFAULT_TIMEOUT = 60 + + +class HttpClient: + """ + .. deprecated:: 0.41 + Use http module functions instead + """ + def __init__(self, limit=DEFAULT_LIMIT, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT), cookie_jar=None): + connector = create_tcp_connector(limit=limit) + self._session = create_client_session(connector=connector, timeout=timeout, cookie_jar=cookie_jar) + + async def close(self): + """Closes connection. Should be called in :meth:`~galaxy.api.plugin.Plugin.shutdown`""" + await self._session.close() + + async def request(self, method, url, *args, **kwargs): + with handle_exception(): + return await self._session.request(method, url, *args, **kwargs) + + +def create_tcp_connector(*args, **kwargs) -> aiohttp.TCPConnector: + """ + Creates TCP connector with reasonable defaults. + For details about available parameters refer to + `aiohttp.TCPConnector `_ + """ + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + kwargs.setdefault("ssl", ssl_context) + kwargs.setdefault("limit", DEFAULT_LIMIT) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.TCPConnector(*args, **kwargs) # type: ignore + + +def create_client_session(*args, **kwargs) -> aiohttp.ClientSession: + """ + Creates client session with reasonable defaults. + For details about available parameters refer to + `aiohttp.ClientSession `_ + + Exemplary customization: + + .. code-block:: python + + from galaxy.http import create_client_session, create_tcp_connector + + session = create_client_session( + headers={ + "Keep-Alive": "true" + }, + connector=create_tcp_connector(limit=40), + timeout=100) + """ + kwargs.setdefault("connector", create_tcp_connector()) + kwargs.setdefault("timeout", aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)) + kwargs.setdefault("raise_for_status", True) + # due to https://github.com/python/mypy/issues/4001 + return aiohttp.ClientSession(*args, **kwargs) # type: ignore + + +@contextmanager +def handle_exception(): + """ + Context manager translating network related exceptions + to custom :mod:`~galaxy.api.errors`. + """ + try: + yield + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ServerDisconnectedError: + raise BackendNotAvailable() + except aiohttp.ClientConnectionError: + raise NetworkError() + except aiohttp.ContentTypeError as error: + raise UnknownBackendResponse(error.message) + except aiohttp.ClientResponseError as error: + if error.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired(error.message) + if error.status == HTTPStatus.FORBIDDEN: + raise AccessDenied(error.message) + if error.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable(error.message) + if error.status == HTTPStatus.TOO_MANY_REQUESTS: + raise TooManyRequests(error.message) + if error.status >= 500: + raise BackendError(error.message) + if error.status >= 400: + logger.warning( + "Got status %d while performing %s request for %s", + error.status, error.request_info.method, str(error.request_info.url) + ) + raise UnknownError(error.message) + except aiohttp.ClientError as e: + logger.exception("Caught exception while performing request") + raise UnknownError(repr(e)) diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/proc_tools.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/proc_tools.py new file mode 100644 index 0000000..4c2df33 --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/proc_tools.py @@ -0,0 +1,87 @@ +import sys +from dataclasses import dataclass +from typing import Iterable, NewType, Optional, List, cast + + +ProcessId = NewType("ProcessId", int) + + +@dataclass +class ProcessInfo: + pid: ProcessId + binary_path: Optional[str] + + +if sys.platform == "win32": + from ctypes import byref, sizeof, windll, create_unicode_buffer, FormatError, WinError + from ctypes.wintypes import DWORD + + + def pids() -> Iterable[ProcessId]: + _PROC_ID_T = DWORD + list_size = 4096 + + def try_get_pids(list_size: int) -> List[ProcessId]: + result_size = DWORD() + proc_id_list = (_PROC_ID_T * list_size)() + + if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)): + raise WinError(descr="Failed to get process ID list: %s" % FormatError()) # type: ignore + + return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))]) + + while True: + proc_ids = try_get_pids(list_size) + if len(proc_ids) < list_size: + return proc_ids + + list_size *= 2 + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + _PROC_QUERY_LIMITED_INFORMATION = 0x1000 + + process_info = ProcessInfo(pid=pid, binary_path=None) + + h_process = windll.kernel32.OpenProcess(_PROC_QUERY_LIMITED_INFORMATION, False, pid) + if not h_process: + return process_info + + try: + def get_exe_path() -> Optional[str]: + _MAX_PATH = 260 + _WIN32_PATH_FORMAT = 0x0000 + + exe_path_buffer = create_unicode_buffer(_MAX_PATH) + exe_path_len = DWORD(len(exe_path_buffer)) + + return cast(str, exe_path_buffer[:exe_path_len.value]) if windll.kernel32.QueryFullProcessImageNameW( + h_process, _WIN32_PATH_FORMAT, exe_path_buffer, byref(exe_path_len) + ) else None + + process_info.binary_path = get_exe_path() + finally: + windll.kernel32.CloseHandle(h_process) + return process_info +else: + import psutil + + + def pids() -> Iterable[ProcessId]: + for pid in psutil.pids(): + yield pid + + + def get_process_info(pid: ProcessId) -> Optional[ProcessInfo]: + process_info = ProcessInfo(pid=pid, binary_path=None) + try: + process_info.binary_path = psutil.Process(pid=pid).as_dict(attrs=["exe"])["exe"] + except psutil.NoSuchProcess: + pass + finally: + return process_info + + +def process_iter() -> Iterable[Optional[ProcessInfo]]: + for pid in pids(): + yield get_process_info(pid) diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/reader.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/reader.py new file mode 100644 index 0000000..732e658 --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/reader.py @@ -0,0 +1,28 @@ +from asyncio import StreamReader + + +class StreamLineReader: + """Handles StreamReader readline without buffer limit""" + def __init__(self, reader: StreamReader): + self._reader = reader + self._buffer = bytes() + self._processed_buffer_it = 0 + + async def readline(self): + while True: + # check if there is no unprocessed data in the buffer + if not self._buffer or self._processed_buffer_it != 0: + chunk = await self._reader.read(1024*1024) + if not chunk: + return bytes() # EOF + self._buffer += chunk + + it = self._buffer.find(b"\n", self._processed_buffer_it) + if it < 0: + self._processed_buffer_it = len(self._buffer) + continue + + line = self._buffer[:it] + self._buffer = self._buffer[it+1:] + self._processed_buffer_it = 0 + return line diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/registry_monitor.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/registry_monitor.py new file mode 100644 index 0000000..1396535 --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/registry_monitor.py @@ -0,0 +1,99 @@ +import sys + + +if sys.platform == "win32": + import logging + import ctypes + from ctypes.wintypes import LONG, HKEY, LPCWSTR, DWORD, BOOL, HANDLE, LPVOID + + LPSECURITY_ATTRIBUTES = LPVOID + + RegOpenKeyEx = ctypes.windll.advapi32.RegOpenKeyExW + RegOpenKeyEx.restype = LONG + RegOpenKeyEx.argtypes = [HKEY, LPCWSTR, DWORD, DWORD, ctypes.POINTER(HKEY)] + + RegCloseKey = ctypes.windll.advapi32.RegCloseKey + RegCloseKey.restype = LONG + RegCloseKey.argtypes = [HKEY] + + RegNotifyChangeKeyValue = ctypes.windll.advapi32.RegNotifyChangeKeyValue + RegNotifyChangeKeyValue.restype = LONG + RegNotifyChangeKeyValue.argtypes = [HKEY, BOOL, DWORD, HANDLE, BOOL] + + CloseHandle = ctypes.windll.kernel32.CloseHandle + CloseHandle.restype = BOOL + CloseHandle.argtypes = [HANDLE] + + CreateEvent = ctypes.windll.kernel32.CreateEventW + CreateEvent.restype = BOOL + CreateEvent.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR] + + WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject + WaitForSingleObject.restype = DWORD + WaitForSingleObject.argtypes = [HANDLE, DWORD] + + ERROR_SUCCESS = 0x00000000 + + KEY_READ = 0x00020019 + KEY_QUERY_VALUE = 0x00000001 + + REG_NOTIFY_CHANGE_NAME = 0x00000001 + REG_NOTIFY_CHANGE_LAST_SET = 0x00000004 + + WAIT_OBJECT_0 = 0x00000000 + WAIT_TIMEOUT = 0x00000102 + +class RegistryMonitor: + + def __init__(self, root, subkey): + self._root = root + self._subkey = subkey + self._event = CreateEvent(None, False, False, None) + + self._key = None + self._open_key() + if self._key: + self._set_key_update_notification() + + def close(self): + CloseHandle(self._event) + if self._key: + RegCloseKey(self._key) + self._key = None + + def is_updated(self): + wait_result = WaitForSingleObject(self._event, 0) + + # previously watched + if wait_result == WAIT_OBJECT_0: + self._set_key_update_notification() + return True + + # no changes or no key before + if wait_result != WAIT_TIMEOUT: + # unexpected error + logging.warning("Unexpected WaitForSingleObject result %s", wait_result) + return False + + if self._key is None: + self._open_key() + + if self._key is not None: + self._set_key_update_notification() + + return False + + def _set_key_update_notification(self): + filter_ = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET + status = RegNotifyChangeKeyValue(self._key, True, filter_, self._event, True) + if status != ERROR_SUCCESS: + # key was deleted + RegCloseKey(self._key) + self._key = None + + def _open_key(self): + access = KEY_QUERY_VALUE | KEY_READ + self._key = HKEY() + rc = RegOpenKeyEx(self._root, self._subkey, 0, access, ctypes.byref(self._key)) + if rc != ERROR_SUCCESS: + self._key = None diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/task_manager.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/task_manager.py new file mode 100644 index 0000000..e7bb517 --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/task_manager.py @@ -0,0 +1,53 @@ +import asyncio +import logging +from collections import OrderedDict +from itertools import count + + +logger = logging.getLogger(__name__) + + +class TaskManager: + def __init__(self, name): + self._name = name + self._tasks = OrderedDict() + self._task_counter = count() + + def create_task(self, coro, description, handle_exceptions=True): + """Wrapper around asyncio.create_task - takes care of canceling tasks on shutdown""" + + async def task_wrapper(task_id): + try: + result = await coro + logger.debug("Task manager %s: finished task %d (%s)", self._name, task_id, description) + return result + except asyncio.CancelledError: + if handle_exceptions: + logger.debug("Task manager %s: canceled task %d (%s)", self._name, task_id, description) + else: + raise + except Exception: + if handle_exceptions: + logger.exception("Task manager %s: exception raised in task %d (%s)", self._name, task_id, description) + else: + raise + finally: + del self._tasks[task_id] + + task_id = next(self._task_counter) + logger.debug("Task manager %s: creating task %d (%s)", self._name, task_id, description) + task = asyncio.create_task(task_wrapper(task_id)) + self._tasks[task_id] = task + return task + + def cancel(self): + for task in self._tasks.values(): + task.cancel() + + async def wait(self): + # Tasks can spawn other tasks + while True: + tasks = self._tasks.values() + if not tasks: + return + await asyncio.gather(*tasks, return_exceptions=True) diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/tools.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/tools.py new file mode 100644 index 0000000..8cb5540 --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/tools.py @@ -0,0 +1,22 @@ +import io +import os +import zipfile +from glob import glob + + +def zip_folder(folder): + files = glob(os.path.join(folder, "**"), recursive=True) + files = [file.replace(folder + os.sep, "") for file in files] + files = [file for file in files if file] + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zipf: + for file in files: + zipf.write(os.path.join(folder, file), arcname=file) + return zip_buffer + + +def zip_folder_to_file(folder, filename): + zip_content = zip_folder(folder).getbuffer() + with open(filename, "wb") as archive: + archive.write(zip_content) diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/unittest/__init__.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/unittest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/unittest/mock.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/unittest/mock.py new file mode 100644 index 0000000..da2e033 --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/galaxy/unittest/mock.py @@ -0,0 +1,39 @@ +import asyncio +from unittest.mock import MagicMock + + +class AsyncMock(MagicMock): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + async def __call__(self, *args, **kwargs): + return super(AsyncMock, self).__call__(*args, **kwargs) + + +def coroutine_mock(): + """ + .. deprecated:: 0.45 + Use: :class:`MagicMock` with meth:`~.async_return_value`. + """ + coro = MagicMock(name="CoroutineResult") + corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro)) + corofunc.coro = coro + return corofunc + + +async def skip_loop(iterations=1): + for _ in range(iterations): + await asyncio.sleep(0) + + +async def async_return_value(return_value, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + return return_value + + +async def async_raise(error, loop_iterations_delay=0): + if loop_iterations_delay > 0: + await skip_loop(loop_iterations_delay) + raise error diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/manifest.json b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/manifest.json new file mode 100644 index 0000000..3f93137 --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/manifest.json @@ -0,0 +1,11 @@ +{ + "name": "GOG Galaxy SNES RetroArch plugin", + "platform": "snes", + "guid": "bc831044-f772-4391-8c22-529f42cb9799", + "version": "0.4", + "description": "Galaxy Plugin to add SNES roms and start them with the RetroArch emulator", + "author": "jshackles", + "email": "jshackles@gmail.com", + "url": "https://github.com/jshackles/RetroGOG", + "script": "plugin.py" +} diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/plugin.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/plugin.py new file mode 100644 index 0000000..c0abb81 --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/plugin.py @@ -0,0 +1,149 @@ +import asyncio +import subprocess +import sys +import json, urllib.request, os, os.path +import user_config +import datetime +import logging +import time +from collections import namedtuple +from typing import Any, Callable, Dict, List, NewType, Optional +from galaxy.api.consts import LicenseType, LocalGameState, Platform +from galaxy.api.plugin import Plugin, create_and_run_plugin +from galaxy.api.types import Achievement, Authentication, Game, LicenseInfo, LocalGame, GameTime + +from version import __version__ as version + +class Retroarch(Plugin): + + def __init__(self, reader, writer, token): + super().__init__(Platform.SuperNintendoEntertainmentSystem, version, reader, writer, token) + self.game_cache = [] + self.playlist_path = user_config.emu_path + "playlists/Nintendo - Super Nintendo Entertainment System.lpl" + self.proc = None + self.game_run = "" + + async def authenticate(self, stored_credentials=None): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def pass_login_credentials(self, step, credentials, cookies): + creds = {} + creds["user"] = "RAUser" + self.store_credentials(creds) + return Authentication("RAUser", "Retroarch") + + async def get_owned_games(self): + self.update_game_cache() + return self.game_cache + + # Format helper for game names + def format_game(self, game): + game_return = game.rsplit(" (")[0] + game_return = game_return.replace("'","") + return game_return + + #Scans retroarch playlist for roms in rom_path and adds them to self.game_cache + #as roms don't need to be installed, owned games and local games are the same and both run update_game_cache + def update_game_cache(self): + game_list = [] + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + rom_path = entry["path"].split("#")[0] + if os.path.isfile(rom_path): + provided_name = self.format_game(entry["label"]) + game_list.append( + Game( + provided_name, + provided_name, + None, + LicenseInfo(LicenseType.SinglePurchase, None) + ) + ) + + #adds games when added while running + for entry in game_list: + if entry not in self.game_cache: + self.game_cache.append(entry) + self.add_game(entry) + + #removes games when removed while running + for entry in self.game_cache: + if entry not in game_list: + self.game_cache.remove(entry) + self.remove_game(entry.game_id) + + #runs update_game_cache in case it is started before get_owned_games. If it runs after it, it just returns self.game_cache with each game as installed + async def get_local_games(self): + if not self.game_cache: + self.update_game_cache() + local_game_list = [] + for game_entry in self.game_cache: + local_game_list.append(LocalGame(game_entry.game_id, 1)) + return local_game_list + + # Only as placeholders so the launch game feature is recognized + async def install_game(self, game_id): + pass + + async def uninstall_game(self, game_id): + pass + + def shutdown(self): + pass + + #potentially give user more customization possibilities like starting in fullscreen etc + async def launch_game(self, game_id): + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for entry in playlist_dict["items"]: + if game_id == self.format_game(entry["label"]): + self.update_local_game_status(LocalGame(game_id, 2)) + self.game_run = self.format_game(entry["label"]) + self.proc = subprocess.Popen(os.path.abspath(user_config.emu_path + "retroarch.exe" + " -L \"" + user_config.emu_path + "cores/" + user_config.core + "\" \"" + entry["path"])) + break + + #imports retroarch playtime if existent. For this to work, activate "Save runtime log (aggregate)" in RetroArch settings -> Savings + async def get_game_time(self, game_id: str, context:any): + file_path = "" + time = 0 + last_played = None + + if os.path.isfile(self.playlist_path): + with open(self.playlist_path) as playlist_json: + playlist_dict = json.load(playlist_json) + for rom in playlist_dict["items"]: + if game_id == self.format_game(rom["label"]): + file_path = user_config.emu_path + "/playlists/logs/" + rom["path"].rsplit("\\",1)[1].rsplit("#")[0].rsplit(".",1)[0] + ".lrtl" + if os.path.isfile(file_path): + with open(file_path) as json_data: + time_data = json.load(json_data) + last_played = datetime.datetime.timestamp(datetime.datetime.strptime(time_data["last_played"],'%Y-%m-%d %H:%M:%S')) + min_data = datetime.datetime.strptime(time_data["runtime"], '%H:%M:%S') + time = min_data.hour*60 + min_data.minute + return GameTime(game_id, time, last_played) + + #checks if game is (still) running, adjusts game_cache and game_time + def tick(self): + try: + if self.proc.poll() is not None: + self.update_local_game_status(LocalGame(self.game_run, 1)) + self.update_game_time(self.get_game_time(self.game_run,None)) + self.proc = None + except AttributeError: + pass + + self.update_game_cache() + self.get_local_games() + +def main(): + create_and_run_plugin(Retroarch, sys.argv) + +if __name__ == "__main__": + main() diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/user_config.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/user_config.py new file mode 100644 index 0000000..4d4d3a4 --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/user_config.py @@ -0,0 +1,11 @@ +# Enter the path for your roms and RetroArch here. Be sure to add a "/" at the end of each path. +# example: +# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/ + +emu_path = "" + +# Enter your core DLL file here, be sure to include the file extension +# example: +# core = "snes9x_libretro.dll" + +core = "" \ No newline at end of file diff --git a/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/version.py b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/version.py new file mode 100644 index 0000000..58d168b --- /dev/null +++ b/plugins/snes_bc831044-f772-4391-8c22-529f42cb9799/version.py @@ -0,0 +1 @@ +__version__ = '0.4' diff --git a/src/RetroGOG.sln b/src/RetroGOG.sln new file mode 100644 index 0000000..4356524 --- /dev/null +++ b/src/RetroGOG.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30413.136 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RetroGOG", "RetroGOG\RetroGOG.csproj", "{2BA1681E-BB10-4334-AA93-03E439F7DF9C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2BA1681E-BB10-4334-AA93-03E439F7DF9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2BA1681E-BB10-4334-AA93-03E439F7DF9C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2BA1681E-BB10-4334-AA93-03E439F7DF9C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2BA1681E-BB10-4334-AA93-03E439F7DF9C}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {6E3F6675-366D-4374-89CE-BCE096B9B2B3} + EndGlobalSection +EndGlobal diff --git a/src/RetroGOG/App.config b/src/RetroGOG/App.config new file mode 100644 index 0000000..8e15646 --- /dev/null +++ b/src/RetroGOG/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/RetroGOG/Program.cs b/src/RetroGOG/Program.cs new file mode 100644 index 0000000..c2d316c --- /dev/null +++ b/src/RetroGOG/Program.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography.X509Certificates; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace RetroGOG +{ + public static class Globals + { + public static string GOGPluginPath = ""; + public static string RAPath = ""; + public static string TempCore = ""; + } + + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new frmMain()); + } + } +} diff --git a/src/RetroGOG/Properties/AssemblyInfo.cs b/src/RetroGOG/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..b7c5f33 --- /dev/null +++ b/src/RetroGOG/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("RetroGOG")] +[assembly: AssemblyDescription("RetroGOG allows you to play your Retroarch games in GOG Galaxy 2.0")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("RetroGOG")] +[assembly: AssemblyProduct("RetroGOG")] +[assembly: AssemblyCopyright("Copyright © 2020")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("2ba1681e-bb10-4334-aa93-03e439f7df9c")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/RetroGOG/Properties/Resources.Designer.cs b/src/RetroGOG/Properties/Resources.Designer.cs new file mode 100644 index 0000000..df63d03 --- /dev/null +++ b/src/RetroGOG/Properties/Resources.Designer.cs @@ -0,0 +1,173 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace RetroGOG.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RetroGOG.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap arrow { + get { + object obj = ResourceManager.GetObject("arrow", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap downloadgog { + get { + object obj = ResourceManager.GetObject("downloadgog", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap galaxy_logo { + get { + object obj = ResourceManager.GetObject("galaxy_logo", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap no { + get { + object obj = ResourceManager.GetObject("no", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap retroarch { + get { + object obj = ResourceManager.GetObject("retroarch", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). + /// + internal static System.Drawing.Icon retroGOG { + get { + object obj = ResourceManager.GetObject("retroGOG", resourceCulture); + return ((System.Drawing.Icon)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap retroGOG1 { + get { + object obj = ResourceManager.GetObject("retroGOG1", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap step_1 { + get { + object obj = ResourceManager.GetObject("step_1", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap step_2 { + get { + object obj = ResourceManager.GetObject("step_2", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap warn { + get { + object obj = ResourceManager.GetObject("warn", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap yes { + get { + object obj = ResourceManager.GetObject("yes", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + } +} diff --git a/src/RetroGOG/Properties/Resources.resx b/src/RetroGOG/Properties/Resources.resx new file mode 100644 index 0000000..1ec1b93 --- /dev/null +++ b/src/RetroGOG/Properties/Resources.resx @@ -0,0 +1,154 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + ..\Resources\arrow.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\downloadgog.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\galaxy logo.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\no.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\retroarch.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\retroGOG.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\retroGOG.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\step_1.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\step_2.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\warn.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\yes.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + \ No newline at end of file diff --git a/src/RetroGOG/Properties/Settings.Designer.cs b/src/RetroGOG/Properties/Settings.Designer.cs new file mode 100644 index 0000000..4db3be6 --- /dev/null +++ b/src/RetroGOG/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace RetroGOG.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/src/RetroGOG/Properties/Settings.settings b/src/RetroGOG/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/src/RetroGOG/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/RetroGOG/Resources/arrow.png b/src/RetroGOG/Resources/arrow.png new file mode 100644 index 0000000..16f6fbf Binary files /dev/null and b/src/RetroGOG/Resources/arrow.png differ diff --git a/src/RetroGOG/Resources/downloadgog.png b/src/RetroGOG/Resources/downloadgog.png new file mode 100644 index 0000000..a0c2e50 Binary files /dev/null and b/src/RetroGOG/Resources/downloadgog.png differ diff --git a/src/RetroGOG/Resources/galaxy logo.png b/src/RetroGOG/Resources/galaxy logo.png new file mode 100644 index 0000000..76d73a2 Binary files /dev/null and b/src/RetroGOG/Resources/galaxy logo.png differ diff --git a/src/RetroGOG/Resources/no.png b/src/RetroGOG/Resources/no.png new file mode 100644 index 0000000..5f2f8eb Binary files /dev/null and b/src/RetroGOG/Resources/no.png differ diff --git a/src/RetroGOG/Resources/retroGOG.ico b/src/RetroGOG/Resources/retroGOG.ico new file mode 100644 index 0000000..d251c32 Binary files /dev/null and b/src/RetroGOG/Resources/retroGOG.ico differ diff --git a/src/RetroGOG/Resources/retroGOG.png b/src/RetroGOG/Resources/retroGOG.png new file mode 100644 index 0000000..2256c1b Binary files /dev/null and b/src/RetroGOG/Resources/retroGOG.png differ diff --git a/src/RetroGOG/Resources/retroarch.png b/src/RetroGOG/Resources/retroarch.png new file mode 100644 index 0000000..fc02fe8 Binary files /dev/null and b/src/RetroGOG/Resources/retroarch.png differ diff --git a/src/RetroGOG/Resources/step_1.png b/src/RetroGOG/Resources/step_1.png new file mode 100644 index 0000000..fdc3830 Binary files /dev/null and b/src/RetroGOG/Resources/step_1.png differ diff --git a/src/RetroGOG/Resources/step_2.png b/src/RetroGOG/Resources/step_2.png new file mode 100644 index 0000000..bb88559 Binary files /dev/null and b/src/RetroGOG/Resources/step_2.png differ diff --git a/src/RetroGOG/Resources/warn.png b/src/RetroGOG/Resources/warn.png new file mode 100644 index 0000000..97a8dd6 Binary files /dev/null and b/src/RetroGOG/Resources/warn.png differ diff --git a/src/RetroGOG/Resources/yes.png b/src/RetroGOG/Resources/yes.png new file mode 100644 index 0000000..3276f3d Binary files /dev/null and b/src/RetroGOG/Resources/yes.png differ diff --git a/src/RetroGOG/RetroGOG.csproj b/src/RetroGOG/RetroGOG.csproj new file mode 100644 index 0000000..709796a --- /dev/null +++ b/src/RetroGOG/RetroGOG.csproj @@ -0,0 +1,168 @@ + + + + + Debug + AnyCPU + {2BA1681E-BB10-4334-AA93-03E439F7DF9C} + WinExe + RetroGOG + RetroGOG + v4.5 + 512 + true + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + retroGOG.ico + + + + + + + + + + + + + + + + + + Form + + + frmAbout.cs + + + Form + + + frmComplete.cs + + + Form + + + frmCoreSelect.cs + + + Form + + + frmDependencies.cs + + + Form + + + frmMain.cs + + + Form + + + frmPluginSelect.cs + + + + + frmAbout.cs + + + frmComplete.cs + + + frmCoreSelect.cs + + + frmDependencies.cs + + + frmMain.cs + + + frmPluginSelect.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + + + + + + + + + + + + + + + False + .NET Framework 3.5 SP1 + false + + + + \ No newline at end of file diff --git a/src/RetroGOG/frmAbout.Designer.cs b/src/RetroGOG/frmAbout.Designer.cs new file mode 100644 index 0000000..e7ec4de --- /dev/null +++ b/src/RetroGOG/frmAbout.Designer.cs @@ -0,0 +1,186 @@ +namespace RetroGOG +{ + partial class frmAbout + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); + this.logoPictureBox = new System.Windows.Forms.PictureBox(); + this.labelProductName = new System.Windows.Forms.Label(); + this.labelVersion = new System.Windows.Forms.Label(); + this.labelCopyright = new System.Windows.Forms.Label(); + this.labelCompanyName = new System.Windows.Forms.Label(); + this.textBoxDescription = new System.Windows.Forms.TextBox(); + this.okButton = new System.Windows.Forms.Button(); + this.tableLayoutPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).BeginInit(); + this.SuspendLayout(); + // + // tableLayoutPanel + // + this.tableLayoutPanel.ColumnCount = 2; + this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33F)); + this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 67F)); + this.tableLayoutPanel.Controls.Add(this.logoPictureBox, 0, 0); + this.tableLayoutPanel.Controls.Add(this.labelProductName, 1, 0); + this.tableLayoutPanel.Controls.Add(this.labelVersion, 1, 1); + this.tableLayoutPanel.Controls.Add(this.labelCopyright, 1, 2); + this.tableLayoutPanel.Controls.Add(this.labelCompanyName, 1, 3); + this.tableLayoutPanel.Controls.Add(this.textBoxDescription, 1, 4); + this.tableLayoutPanel.Controls.Add(this.okButton, 1, 5); + this.tableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill; + this.tableLayoutPanel.Location = new System.Drawing.Point(9, 9); + this.tableLayoutPanel.Name = "tableLayoutPanel"; + this.tableLayoutPanel.RowCount = 6; + this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); + this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); + this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); + this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); + this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); + this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); + this.tableLayoutPanel.Size = new System.Drawing.Size(417, 265); + this.tableLayoutPanel.TabIndex = 0; + // + // logoPictureBox + // + this.logoPictureBox.Image = global::RetroGOG.Properties.Resources.retroGOG1; + this.logoPictureBox.Location = new System.Drawing.Point(3, 3); + this.logoPictureBox.Name = "logoPictureBox"; + this.tableLayoutPanel.SetRowSpan(this.logoPictureBox, 6); + this.logoPictureBox.Size = new System.Drawing.Size(131, 136); + this.logoPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; + this.logoPictureBox.TabIndex = 12; + this.logoPictureBox.TabStop = false; + // + // labelProductName + // + this.labelProductName.Dock = System.Windows.Forms.DockStyle.Fill; + this.labelProductName.Location = new System.Drawing.Point(143, 0); + this.labelProductName.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0); + this.labelProductName.MaximumSize = new System.Drawing.Size(0, 17); + this.labelProductName.Name = "labelProductName"; + this.labelProductName.Size = new System.Drawing.Size(271, 17); + this.labelProductName.TabIndex = 19; + this.labelProductName.Text = "RetroGOG Installation Wizard"; + this.labelProductName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // labelVersion + // + this.labelVersion.Dock = System.Windows.Forms.DockStyle.Fill; + this.labelVersion.Location = new System.Drawing.Point(143, 26); + this.labelVersion.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0); + this.labelVersion.MaximumSize = new System.Drawing.Size(0, 17); + this.labelVersion.Name = "labelVersion"; + this.labelVersion.Size = new System.Drawing.Size(271, 17); + this.labelVersion.TabIndex = 0; + this.labelVersion.Text = "Version"; + this.labelVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // labelCopyright + // + this.labelCopyright.Dock = System.Windows.Forms.DockStyle.Fill; + this.labelCopyright.Location = new System.Drawing.Point(143, 52); + this.labelCopyright.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0); + this.labelCopyright.MaximumSize = new System.Drawing.Size(0, 17); + this.labelCopyright.Name = "labelCopyright"; + this.labelCopyright.Size = new System.Drawing.Size(271, 17); + this.labelCopyright.TabIndex = 21; + this.labelCopyright.Text = "Copyright"; + this.labelCopyright.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // labelCompanyName + // + this.labelCompanyName.Dock = System.Windows.Forms.DockStyle.Fill; + this.labelCompanyName.Location = new System.Drawing.Point(143, 78); + this.labelCompanyName.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0); + this.labelCompanyName.MaximumSize = new System.Drawing.Size(0, 17); + this.labelCompanyName.Name = "labelCompanyName"; + this.labelCompanyName.Size = new System.Drawing.Size(271, 17); + this.labelCompanyName.TabIndex = 22; + this.labelCompanyName.Text = "Company Name"; + this.labelCompanyName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // textBoxDescription + // + this.textBoxDescription.Dock = System.Windows.Forms.DockStyle.Fill; + this.textBoxDescription.Location = new System.Drawing.Point(143, 107); + this.textBoxDescription.Margin = new System.Windows.Forms.Padding(6, 3, 3, 3); + this.textBoxDescription.Multiline = true; + this.textBoxDescription.Name = "textBoxDescription"; + this.textBoxDescription.ReadOnly = true; + this.textBoxDescription.ScrollBars = System.Windows.Forms.ScrollBars.Both; + this.textBoxDescription.Size = new System.Drawing.Size(271, 126); + this.textBoxDescription.TabIndex = 23; + this.textBoxDescription.TabStop = false; + this.textBoxDescription.Text = "Description"; + // + // okButton + // + this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.okButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.okButton.Location = new System.Drawing.Point(339, 239); + this.okButton.Name = "okButton"; + this.okButton.Size = new System.Drawing.Size(75, 23); + this.okButton.TabIndex = 24; + this.okButton.Text = "&OK"; + this.okButton.Click += new System.EventHandler(this.okButton_Click); + // + // frmAbout + // + this.AcceptButton = this.okButton; + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(435, 283); + this.Controls.Add(this.tableLayoutPanel); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "frmAbout"; + this.Padding = new System.Windows.Forms.Padding(9); + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "About RetroGOG"; + this.Load += new System.EventHandler(this.frmAbout_Load); + this.tableLayoutPanel.ResumeLayout(false); + this.tableLayoutPanel.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel; + private System.Windows.Forms.PictureBox logoPictureBox; + private System.Windows.Forms.Label labelProductName; + private System.Windows.Forms.Label labelVersion; + private System.Windows.Forms.Label labelCopyright; + private System.Windows.Forms.Label labelCompanyName; + private System.Windows.Forms.TextBox textBoxDescription; + private System.Windows.Forms.Button okButton; + } +} diff --git a/src/RetroGOG/frmAbout.cs b/src/RetroGOG/frmAbout.cs new file mode 100644 index 0000000..13779a3 --- /dev/null +++ b/src/RetroGOG/frmAbout.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace RetroGOG +{ + partial class frmAbout : Form + { + public frmAbout() + { + InitializeComponent(); + this.Text = String.Format("About {0}", AssemblyTitle); + this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion); + this.labelCopyright.Text = AssemblyCopyright; + this.labelCompanyName.Text = AssemblyCompany; + this.textBoxDescription.Text = AssemblyDescription; + } + + #region Assembly Attribute Accessors + + public string AssemblyTitle + { + get + { + object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false); + if (attributes.Length > 0) + { + AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0]; + if (titleAttribute.Title != "") + { + return titleAttribute.Title; + } + } + return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); + } + } + + public string AssemblyVersion + { + get + { + return Assembly.GetExecutingAssembly().GetName().Version.ToString(); + } + } + + public string AssemblyDescription + { + get + { + object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false); + if (attributes.Length == 0) + { + return ""; + } + return ((AssemblyDescriptionAttribute)attributes[0]).Description; + } + } + + public string AssemblyProduct + { + get + { + object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false); + if (attributes.Length == 0) + { + return ""; + } + return ((AssemblyProductAttribute)attributes[0]).Product; + } + } + + public string AssemblyCopyright + { + get + { + object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); + if (attributes.Length == 0) + { + return ""; + } + return ((AssemblyCopyrightAttribute)attributes[0]).Copyright; + } + } + + public string AssemblyCompany + { + get + { + object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); + if (attributes.Length == 0) + { + return ""; + } + return ((AssemblyCompanyAttribute)attributes[0]).Company; + } + } + #endregion + + private void okButton_Click(object sender, EventArgs e) + { + this.Close(); + } + + private void frmAbout_Load(object sender, EventArgs e) + { + + } + + } +} diff --git a/src/RetroGOG/frmAbout.resx b/src/RetroGOG/frmAbout.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/src/RetroGOG/frmAbout.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/RetroGOG/frmComplete.Designer.cs b/src/RetroGOG/frmComplete.Designer.cs new file mode 100644 index 0000000..8fd39c6 --- /dev/null +++ b/src/RetroGOG/frmComplete.Designer.cs @@ -0,0 +1,177 @@ +namespace RetroGOG +{ + partial class frmComplete + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmComplete)); + this.btnBack = new System.Windows.Forms.Button(); + this.btnAbout = new System.Windows.Forms.Button(); + this.btnCancel = new System.Windows.Forms.Button(); + this.lblExplain2 = new System.Windows.Forms.Label(); + this.lblExplain = new System.Windows.Forms.Label(); + this.lblWelcom = new System.Windows.Forms.Label(); + this.pictureBox1 = new System.Windows.Forms.PictureBox(); + this.pictureBox2 = new System.Windows.Forms.PictureBox(); + this.label1 = new System.Windows.Forms.Label(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); + this.SuspendLayout(); + // + // btnBack + // + this.btnBack.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.btnBack.Location = new System.Drawing.Point(93, 343); + this.btnBack.Name = "btnBack"; + this.btnBack.Size = new System.Drawing.Size(75, 23); + this.btnBack.TabIndex = 13; + this.btnBack.Text = "< < &Back"; + this.btnBack.UseVisualStyleBackColor = true; + this.btnBack.Click += new System.EventHandler(this.btnBack_Click); + // + // btnAbout + // + this.btnAbout.Location = new System.Drawing.Point(12, 343); + this.btnAbout.Name = "btnAbout"; + this.btnAbout.Size = new System.Drawing.Size(75, 23); + this.btnAbout.TabIndex = 12; + this.btnAbout.Text = "&About"; + this.btnAbout.UseVisualStyleBackColor = true; + this.btnAbout.Click += new System.EventHandler(this.btnAbout_Click); + // + // btnCancel + // + this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.btnCancel.Location = new System.Drawing.Point(543, 343); + this.btnCancel.Name = "btnCancel"; + this.btnCancel.Size = new System.Drawing.Size(75, 23); + this.btnCancel.TabIndex = 11; + this.btnCancel.Text = "&Finish"; + this.btnCancel.UseVisualStyleBackColor = true; + this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); + // + // lblExplain2 + // + this.lblExplain2.AutoSize = true; + this.lblExplain2.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblExplain2.Location = new System.Drawing.Point(13, 63); + this.lblExplain2.Name = "lblExplain2"; + this.lblExplain2.Size = new System.Drawing.Size(430, 18); + this.lblExplain2.TabIndex = 16; + this.lblExplain2.Text = "Your configured plugins should now be available in GOG Galaxy."; + // + // lblExplain + // + this.lblExplain.AutoSize = true; + this.lblExplain.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblExplain.Location = new System.Drawing.Point(13, 45); + this.lblExplain.Name = "lblExplain"; + this.lblExplain.Size = new System.Drawing.Size(199, 18); + this.lblExplain.TabIndex = 15; + this.lblExplain.Text = "This wizard is now complete."; + // + // lblWelcom + // + this.lblWelcom.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.lblWelcom.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblWelcom.Location = new System.Drawing.Point(-1, 9); + this.lblWelcom.Name = "lblWelcom"; + this.lblWelcom.Size = new System.Drawing.Size(630, 24); + this.lblWelcom.TabIndex = 14; + this.lblWelcom.Text = "Thank you for using the RetroGOG Installation Wizard"; + this.lblWelcom.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // pictureBox1 + // + this.pictureBox1.Image = global::RetroGOG.Properties.Resources.step_1; + this.pictureBox1.InitialImage = global::RetroGOG.Properties.Resources.step_1; + this.pictureBox1.Location = new System.Drawing.Point(12, 122); + this.pictureBox1.Name = "pictureBox1"; + this.pictureBox1.Size = new System.Drawing.Size(304, 215); + this.pictureBox1.TabIndex = 17; + this.pictureBox1.TabStop = false; + // + // pictureBox2 + // + this.pictureBox2.Image = global::RetroGOG.Properties.Resources.step_2; + this.pictureBox2.Location = new System.Drawing.Point(64, 122); + this.pictureBox2.Name = "pictureBox2"; + this.pictureBox2.Size = new System.Drawing.Size(554, 215); + this.pictureBox2.TabIndex = 18; + this.pictureBox2.TabStop = false; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.label1.Location = new System.Drawing.Point(16, 85); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(363, 18); + this.label1.TabIndex = 19; + this.label1.Text = "If GOG Galaxy 2.0 is already running, please re-start it."; + // + // frmComplete + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(630, 378); + this.Controls.Add(this.label1); + this.Controls.Add(this.pictureBox1); + this.Controls.Add(this.pictureBox2); + this.Controls.Add(this.lblExplain2); + this.Controls.Add(this.lblExplain); + this.Controls.Add(this.lblWelcom); + this.Controls.Add(this.btnBack); + this.Controls.Add(this.btnAbout); + this.Controls.Add(this.btnCancel); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.Name = "frmComplete"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "RetroGOG"; + ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button btnBack; + private System.Windows.Forms.Button btnAbout; + private System.Windows.Forms.Button btnCancel; + private System.Windows.Forms.Label lblExplain2; + private System.Windows.Forms.Label lblExplain; + private System.Windows.Forms.Label lblWelcom; + private System.Windows.Forms.PictureBox pictureBox1; + private System.Windows.Forms.PictureBox pictureBox2; + private System.Windows.Forms.Label label1; + } +} \ No newline at end of file diff --git a/src/RetroGOG/frmComplete.cs b/src/RetroGOG/frmComplete.cs new file mode 100644 index 0000000..3b803c3 --- /dev/null +++ b/src/RetroGOG/frmComplete.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace RetroGOG +{ + public partial class frmComplete : Form + { + public frmComplete() + { + InitializeComponent(); + } + + private void btnAbout_Click(object sender, EventArgs e) + { + Form frmAbout = new frmAbout(); + frmAbout.Show(); + } + + private void btnBack_Click(object sender, EventArgs e) + { + this.Hide(); + Form frmPluginSelect = new frmPluginSelect(); + frmPluginSelect.Closed += (s, args) => this.Close(); + frmPluginSelect.Show(); + } + + private void btnCancel_Click(object sender, EventArgs e) + { + this.Close(); + } + } +} diff --git a/src/RetroGOG/frmComplete.resx b/src/RetroGOG/frmComplete.resx new file mode 100644 index 0000000..accb675 --- /dev/null +++ b/src/RetroGOG/frmComplete.resx @@ -0,0 +1,1889 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + + AAABAAYAAAAAAAEAIADdFwAAZgAAAICAAAABACAAKAgBAEMYAABAQAAAAQAgAChCAABrIAEAMDAAAAEA + IACoJQAAk2IBACAgAAABACAAqBAAADuIAQAQEAAAAQAgAGgEAADjmAEAiVBORw0KGgoAAAANSUhEUgAA + AQAAAAEACAQAAAD2e2DtAAAXpElEQVR42u2deYAUxb3HPzOzB7ssuxzLfQmIXBpFWSCiiIhBIhoFTEzU + FzXmqVEQiOgDESV4LA/QKGh8JmqMmngkwovhKYgcigcgdxS5WZBjuZY92JOZeX8sM8zudPX0Od1L12f+ + 6a7q6vlV9ber6y6QSCQSiUQikUgk3sKn7PwCG5sfG3pyWOpgeh2nirDTdkoMkE4O2ceKFmYszV1y7oHJ + ig9RQQBz2Nj34PiTI6uaOx0BiVWkVTb6uNXcgUsnBOv7xAng7k4780tHnUp32mSJ1fiDWcvbP/Tmurqu + gdiTfF/2LTv/eTIvlOK0sRLrCfuruhbffhHDPl8T8zGIyQEmpG7LL5wQ9um/taQh0Wx+jzteKI6cRR/3 + A6lbXz76y7qPP5VudKcdmUhVNEQqOMx2tlNRzz17aZ/R807UHp9+sjN9nz5T+EDs48/lJobTtu43QtLg + CFHEMv5GQR3Xph/0HPXCKYiWAXJu2z/zzONP5VZmMoBs/E7bLzGJj0x6M5pmbKQm6lrZI5h29yeLOS2A + X5+zc0EwI+LZjHzGkOq05RIL8XM+g1jLiahLxYDyFd8UgB/msPvp6mYRj2b8nh86ba/EBs5jLl2iZ8HU + wjnTG0EAWvc7ODt0+lOQSj4XO22pxCaakMciqk6f1bQ9+e+t3/h/z6Fxp9Iil/xCvv1nNV2YGD0O+4on + PJbi/7bFyZERp1zudNpCic2M4ILocXleQR//0aFV0e//TTR22j6JzQS4LXoc9B+6wV9+deQ0jeFOWydJ + AgNpFT2uGOJPuyJy0oW2TtsmSQKZXHjmJM8fOi9yfK5s9fMIPaNHJxv7i6In7Zy2S5IkzuT0YfxV0ZNM + p+2SJInYJ+0/0zUs2/29gl9wLPEgUgAeRwrA40gBeBwpAI8jBeBxpAA8jhSAx5EC8DhSAB5HCsDjSAF4 + HCkAjyMF4HGkADyOFIDHkQLwOFIAHkcKwONIAXgcKQCPIwXgcSxaEO4YK/mWw1QS0vSnAdJpTDYtaEd3 + 2iKXJXQKCwRQzWv8lZMm7tCK/vyYvq5ZluYkRUAujZw2JAmYFkCYOfzD5D0O8y8W0oM7uNLxb9JJXmYx + x/DRhhv5BWnmb+lqTKf3Ot63xJAw3zGZSRSZv5UJyhnHWxwhRJD9zOOhmJW1zk5MC2C+hSuJh1jB7exw + MDneY2Od85XMd9CaZGBaABssNmg/D7DLmbQgzNI4t+UO2ZIsTAqgyoYsu5AplDmSGJUcjXPb64glycO0 + AOzYSmIHLzqSGNVUxrmdJGjgTg0HpwvdAuY78hkIKrRihDjldGLYim07A6TTUcE1SDUVlCYsW9fwNlOS + nhhhxWYsLU1bDRfbBNCJNxTdQwSp4Qjf8AEbVD4gyxlHltOp4wFsE4BP5dYZZNON6/iAWXFr2Uco4lv6 + O506HsDBMoCP63lQaECYb50zzUM4vDvQSBawWeD3vea7lLGTPRzkBOWESKUxLehAVzonLXrlrGATZWTR + iytpEuOznzXs4gSQTQd60Vtzj0cx2ymgkBNUEiKVJuTSnq50tvStdVgAAa4UCqA4Yegw+1nCp2ylWqE0 + 4SeHPH7EQNs7ddYzjYPRsxf4HQMAKGAuK+vUInw042rGcI7KJjwhdvMxK9nJKYVYBcghj6FcSgZW4Pj+ + YOLVSdVL3yE28he+VKmkhShiMYtpx83coLoIXhmLWcsxxXaASsaeXkCzET0YSae4K77nt5TEnB9jMq/R + mc+ZFifiMMd5h/cZxb2KRdxTfMVbrFWJe5DjLGIRLbmBMbQwnf6OC0BcIVRT+CHm8onGGvoBnmEBExko + 8D/K/Sr9D8GYxu7P+TuzuKTeFX+s8/gBSniTq3hYQU6ROL/DDubESWAHz7JGY7XzCH/kfX7FKJOP0PGG + oN1Cn5ZCny+4nUW6Gmh2MYF5ghCv6Oh+KuG5eg+olM8VrlvCZOHjr2Utr9Y5D/MP7mSVrlaHY8xigkLz + tR4cFkA5Hwv9uim6hplvKNI1/JkpVCn4bNV1nwP1+in2KpZVSilNeKcPKY+xbjb5MedaCfMld7Jdd7gz + OCqAKuYIy/pp9FF0/xczDbfOL+VxhU+OvjWSc+p9mgoN94YcjeYRIebwjuH7HGCsiYZzxwQQ4it+wz+F + /l3prOC6gVmm2uaX1Mt4AX6po8UxlbvqVeMqNYetT2b06/2myTFVR3mQYwbD2lYIrOFAnNspqinhGPvZ + xkYOq2p+jII2y5iumk0GSAGCKhIJ8zoDuKiOW3de5XXWU0yYijibfGTgw08WbbmAa+laz994T0Hf0+0F + G3jJdJ/qXp4m39DDtE0Au7neROhu/FjB9TX2Ca7305eR9KY5PorZyTKWCd7Nap7n5XrR7sp0AI4xKm5w + ayYfWVTjrktTfoMPqGAW1cKrMriIvrQlQDE7WM33QqmsYLFimiXC8WqgEulMVhiMWcjfBdfn8BDDottd + NKUzQ9nK7wTFu018yeVJikmAwQyhNVXsYzMbKDztfi5Tqd2p40NhIdTHcH5Np5gmo0qW8xxHFK8O8z8M + MbDkvwsFEGBSvUy6lvcFQ88zmE3fONcezOU+Qfn43SQJIIXJXBf9lN1MJbvZSAXn0e/0TIhq/ioI62Ms + t9b7DDbiGn7AeEGRbz+LuFG3jY63A9Qnk2ncoOBeyYeCEHcrPH6A5kwVDOr+msNJicsoflIngRvRi5u5 + g0HRiTBr2CMIezO3KT6cdjxLriDMewbKEi4TwHn8gWsVfb6JaW2PpRWjhXfrI9gGs4avkxCXjJgN2kQs + Fri349fC3oL23CPw22GgOugiAbTit7wiqP3DKoG6h6kW0X4kcE9GV/OFCXdhC/GlwGcM2SrhRtBe5/3E + uEIAafTlMf7Bz4UPM8wmgU9/Qiq/CwWhRLUJKxmY8IoCwZjqRgxTDZcu9F+v20oXFAKb8t8JN6yuFD6y + 5/iDSrgwPsWcI3FXs3kuSHjFDkGu1ilh6+QA/iy4Y0jnO+0CAZzgUWYkkEAlxwU+uzGCHYPZ69M14RWi + ZvCeCUP2ELiXUEJTXVbaJoBzmA2EqaGYfWxihUr3SCHjeYLBKncrsXiOXnO7oh2liYYGZlGXVuLeiSY0 + VqwUV1HqFgGkcU70OI9RlPIKbwsbacv5L/JVJGBm8rkSibNns+RquEbUrJ2jIWy2YpoEFfs71UhaIbAJ + 45mh0lJVzWOsE/paOzsnIwnbZGerDPpKFCstb6XyNSHdfRNJrQVczXSV+falPCIs6lm5dESABwTVKCtp + rOEaUayqNYRVvsave//nJFcDr2SsyptxhIcF2aJVU0TSyWOuStORdWgZiNpE4H5cQ9gTiq6pujuukl4L + +Bnf8JHQdxuzeFRBlU1opNi7F2CIhjU8fKTQmFzOobfKQDNr0bKySCuBe+JWisOCb326agOSEkkXgJ9J + bGa/0H8h/RkR59qIXMVKU4jfKA4ccR4tCdtJ4L6FYIKs/BuBe67uvNKBlsAc/ksleiGe5VCca7rgMYfZ + ovFfj/O/vMRrfO2iyZ49BZ/DgwmHqa4U3lEvjjQFD1Ts74twnGcUHtJFgquXamrUWcIoZvAnXuAe7hL0 + qIuwr9EoN6aqHMsplaFyAMeE65bk6bbBEQH4uEe1sWMZn8W5DRTkGp8JO1QjBHmDqTFjeTcxQ2hX/BsZ + tnWBCFHLx0IKhGHC/CVuJkItaYLeTzUc6gxqxgSV2kCY5+IKOd0FTas1zFEdJlrB08ytd8VqhY9MbWLE + J0dId9OKHq4RyLqMp4T/u5L3BD79DcwUcqw3cIhqj9feuHGyKcLPxirmCt/SPdzDgrgPSkgwhjZVoexe + Y3i8rRa6CafAr2WyQuN5mBVMFbQB+LjZgAWOCcDHRFW9vhmXzY2kteKVYf7Ko9HRdmco4VX+Q7G8HBA0 + 1KYp1KKDijN/rMLPHcL6wqfcxsKYVKhhOzOYJGwWv9hACcDR3sCW3M/vhEWswyzk53VcGnMvjyteG2Yx + qxjOFXQmixClfM8XLFEQRS29BFJKpblCHfwN2nMpGZRxmAIOEGAQXSxLhb4MZ6HA73seoxndaEMKxexh + n8rHLp37dLcCgsPdwSNYovJ+zWd0vSx5BJ8oFA9rKeZd3iOdVMLUKE4XP8OdQp8u9RaKBChlKlmkUEPF + 6U/NSzzG1RalgY8HWK8whyJCkcbha7cY7OAy+QlI3OGhRgqTVFqudsWNAgrwqKDiVEuYSkopS7B43TVc + KvT7geC+pRRRFi1pVDIzOqRElALaU6Y5T2vqOVDjcpUxhOqYFECmMNtpoil8B+5V8Y0f4dacWQlH2qlz + AZNUIj1A48j64uinQrTQvZ5FKfrwpCkJXMwMw91lJgUQEDZnam2gHUU/oZ/SgIkuzFPNBdS5mNmqve2t + uU7TfVKiAm8jePP0TTm9jNmGF3u4gtkmOstM1wKUs1Of5iaJAI8IH4nyBPHO/IlhBgwPcBNzEybzfcJx + yXVjHRF+F8U7+lRkrUwer3CR7mw8jXvI190BFItpAYxWzOzPZZDmO3TkYcUMrIVCp1AtTXmap3WVxH30 + YS4PadiZJJPnuVq1PB1gKNOjj6oxP1G4Jo/uulIRoAMvMUnYQ6hkRx6vxs1W1kug3eORwx8KikDqZNGG + lfUaYlowU1DRUqYrzVhd7x6ZPE5vYQgfXbmeThRxNGFbfToDmMB9dWbZqdGIoVxIDSVxaxim0IGhjOfW + OkI6nw31Whbb8qShUYd++nAtzTmUcNRyOpfxIHfpkEss+2JmWfkuiabfBG4xdLswa3ie706fBbicBxSX + iVVnHb+PTtfw0Y9x9NIQKsj3fM5atnBEQQgt6cNABtHaUEZXzhEOUEQVtd/8FrQhR7Gfv4wXWXC6fc7P + YCbqLAHUp4otfMY6tik0B7fhfPpzKa1N1MC+YFz02AIBAIQpYCfl5NBb03BI5XvsZQflZNOTVjqjF6aU + AxyjjGrCpJFFC9ppGpdnFcVspogm9Db4VipxioPRdQJr49SeJhbEKVYAFjUE+TjHRNk8co/Ohgd3+Mg2 + VRQyTw6XWX7PFDoayEv14YqpYRLnkALwOFIAHkcKwONIAXgcKQCPIwXgcaQAPI4UgMeRAvA4UgAeRwrA + 40gBeBwpAI8jBeBxpAA8jhSAx5EC8DhSAB5HCsDjSAF4HCkAjyMF4HGkADyOLSuEhCxcWi1gWqOnLFvp + z2c6udyVMmCxAGpYxWds4aiF0fTTnPO4jEG6llwA2M9S1lKgsB2sUXyk04m+DNU9C6qGL1nJd5anTE8u + 41INc55V4mTN3EAI8jEvs8+2dTVbcjujNE+FLmQeSyzeZeQMAS7nfs0iOMVi/qiy6atZWnMHN+h6k2Pn + BlpUBijjEaay18ZlVY8wi3GaFnkNs5xb+dC2xw9BlnM7H2iKbQmTmWbjiwGF5DPR8GqGlgiglIkssS2C + Z1jDWA17fn7EI4Lt2KykjCd4O+FVJUxgWRJS5gvGCXcgUscCAQR5SmWzF2vZwdQES7du5glbF3eNjfdz + CRaRPMUMhWXn7GEr0wzleRYIYFFS3v4I6/ibim9V0h4/wCnyBTt31LJQuKq3HazmXQOhTAugmleSsgvf + GURrZQN8aGD3XDMcjFvT+AwVvJbklHndwO5qpgXwtcrC5vZQwscCnxALkpzksFCY46wSbgxpF8dZqjuM + aQF8muRIqv3nQbYn3ZZ9wr1L3ZQyYkwLQOuWLVayVbDty64kfv8jhKPLY9XHTSkjxrQA9G2/Yg0VMft/ + OG0LwoqpE9acFO5GKsK0AJL/zkFIUOFxwhbxvzphTVB3VdC0AJJd6FL7VzfZ0lCQ3cEex/YNI7IYyrk6 + /ibIXj7RtHmqEfowSNf26qWsYr1N73gWV9FNV8oUsES14ckINgugFzMNLJt6N1P5ynJbUhjPT3VneXew + iCcVt601R29mGtj54G6msMZSO2z9BGQYevzQlKcsXHA1whh+ZiC6fkbwS8ttySLf0MYXzSxPGVsFMMTw + osnZXGuxLamMNrzK7k90D0ZJhPGUaSZcRN8Ytgqgm0Nhlcg28ea00rgBjna6mghrbcrYKgAzWxmY2wZB + KaJmomq1Ne5JGVkN9DhSAB5HCsDjSAF4HCkAjyMF4HGkADyOFIDHkQLwOFIAHkcKwONIAXgcKQCPIwXg + caQAPI4UgMeRAvA4UgAeRwrA40gBeBxbBVDtdOxiCJpaoc/qmNi3gplebBVA8pdrEFNKoeGwhyi12Br3 + pIytAviUfU7HL0oN7xqe4/e+5VO9V7gmZWwVQCWTkr6CkJj5vGHgMxBkAW9abks5D7PX6QQBbJ8cuoPb + GEw3DZMZbrZ9onKI5/mIQTTXPEUsTAlfsdkWa7ZxK1domh18i+EpbVqwfXp4OR9puMrHaPtNAbaxLQn/ + oo1yPtRwlZ9f2CoAWQ30OKYFYKc6G4YtbkoB/ZgWgJm16q3GGVvSdbq7C9MCsH4hh4ZmSyud7u7CtAB6 + Ox2DGLpavpBDYnzCFHBTyogxLYDBTscghjacl/T/7ExngY+bUkaMaQFcTBen4xATmRuTXiS7Tvit708n + pxNEA6YFkMZ/uqgcPJzuSf2/9two9GvEr1yUMiIsaAe4ih87HYsoaUwjI2n/lsoUslX8r+FqpxMkIRYI + wM/DDHA6HlF68liSJJDCgwniHWAKlzidIAmwpCUwk1mMdE12N4yZ5Nr+LzlMZ1TCq7J4hmtckzJKWNQU + nMk0ZtHdJVG9lLcYZWM+kMo1vM5wTbFtzHTy6eaSlInHsh4YP0O4nPV8xncc1j2CxmdxArVgCnexnHXs + oczCnUMb05G+DKG9jlABrmIIa1nJdxzWPRbIbuFY2gUXoB/9AAjpTvSA5VFrxU/5KRDWvYuGCL/hxxGg + P/0Npoy9/XU29cG6qZPRZ4O4jOOmlHGjPZIkIwXgcaQAPI4UgMeRAvA4rhVAhdMGuBZrU8a1Avi30wa4 + FmuHqbtUAAUsdNoEl7KLRZbez4UCCLOJCfIToECIDUzUvTmsOqZbAmdbvKVaDXvZ6qp5xUaZafEc4BoK + 2Gr5vGLTAvg/Siw26WzhXw0iF3PhJ0CSTBqoANzau+40+tOlQQrA30Bm3SSfgO6UaZACyCHLaRNcSlMy + dYZokAK4wGkDXIv+lGmQArjSaQNcio8husM0QAG0ayCTrpJPRwbpDtPgBODnPtKcNsKV+BlroFmnwQng + WoY5bYJLuZErDIRqYAIYzCRXDfF0D1cx3tDDTMbKTBaRws+43/KN3M8GUrmFuw2mTAMRQBqX8CsuctoM + F5JOP+4yUTE2LYA8i7sn4w3MpQd5dGxoXyv629ynmUouPelHB1MpY1oAM22NZENmjtMGaKKhvVYSi5EC + 8DhSAB5HCsDjSAF4HCkAjyMF4HGkADyOFIDHkQLwOFIAHkcKwONIAXgcKQCPIwXgcaQAPI7/zHRCq1bU + lbid2CftPzOUsCHMZpdYQeySHv6c6OFhp+2SJInCmGN/06LI4Q7LVtWWuJvt0aPMKv/x6HJcOznutGWS + JFDFxuixf6O/0dLISTnLnLZNkgQ2szd6nPGZv9XitGjp7x3L16CSuI0wb0WP/eHmC/y9D2QsiTjsYb7T + 9klsZjWfR48ztrZf458YbjnXH4w4vRhTQJCcfRznqZiifva8WVV+GLg0a3nEqYzJHHLaSolNlDGV/dGz + zJ3d3wQ/TAh2eCilKuK8h3HscdpSiQ0c52FWR898oZaTny0+vVnXpoMX+0ujC+8UsYiWLt7pTmKENTzI + lpjz5n+78snF4ehubUNWVl5Y2TPiWcUyVtOU1nI2/llANRuZxUsUx7g12ThwzKOVELO05Nicf88vqbf8 + Vmv60ou2NJarcjRAQlRQyDbWs7deR1/mtq4/er2g9jgmn7+/2Za/nBjptNkSu2myseMNb+yJnMW82qsr + R/w9mFLxw7AcI3DW4gu1eDvvphdjKnp18vY1obs+qVxRfUFNW1kCPBvJ2NX+3qFPPFqn31/hQU9rtOH6 + kt+W9wvKnOCswUfm1ux53d94tjjeR5HHU3afX3hjxRDyyuzbhV2SBDJqAhszPm02v/3Xs63d2kUikUgk + EolEIpFIJA2R/wdOE2BbbcdkRgAAAABJRU5ErkJggigAAACAAAAAAAEAAAEAIAAAAAAAAAABABMLAAAT + CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAICAgAFPT08sPz8/bjMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4A+Pj5xTU1NMnR0dAIA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAImJiQBHR0dEOTk5xzQ0NP4zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk50UVFRVGOjo4AAAAAAAAAAAAAAAAAAAAAAAAAAABs + bGwEPj4+jzQ0NP4zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/z4+PqFdXV0IAAAAAAAAAAAAAAAAZmZmAT09PZ8zMzP/MzMz/zMzM/9iYmL/r6+v/9jY2P/k + 5OT/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5OTk/9ra2v+zs7P/aWlp/zMzM/8zMzP/MzMz/zw8PLJ6enoEAAAAAAAAAABC + QkJqMzMz/zMzM/88PDz/tbW1//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////wcHB/0FBQf8zMzP/MzMz/z8/P34AAAAAWlpaEjY2Nu4zMzP/NjY2/8XFxf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////0tLS/zo6Ov8zMzP/NTU19lFRUR8/ + Pz9xMzMz/zMzM/+Kior///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////m5ub/zMzM/8zMzP/Pj4+hjo6OsAzMzP/NTU1/+Xl5f////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////w8PD/Ozs7/zMzM/85 + OTnVQUFB+zMzM/9TU1P///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////9jY2P/MzMz/zY2Nv01NTX/MzMz/2lpaf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////3p6ev8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ////////////////////////////////////uLi4/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1 + tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1 + tbX/vb29/+Li4v////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////9zc3P+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1 + tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7e3t//MzMz/9/f3//////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////86 + Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NTU1/2lpaf/h4eH///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9DQ0P/p6en//7+/v////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + /////////////////////////////////////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0NDQ//c3Nz///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/iYmJ//////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + ////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/1tbW//+ + /v7///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////52dnf8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/wsLC//////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/83Nzf////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9qamr/////////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/n5+f//////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////+dnZ3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/z8/P//8/Pz///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/OTk5//f39////////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////9hYWH/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9b + W1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1FRUf80NDT/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5SUlP////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////sLCw/1tbW/9b + W1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9b + W1v/W1tb/1tbW/9aWlr/Pz8//zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////8DAwP81NTX/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////z8/P/Z2dn/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////2hoaP8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+UlJT///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////Nzc3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////9zc3P8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////94eHj/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/lJSU//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/2 + 9vb///////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////c + 3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + ///////////////////////////////////////////////x8fH/vLy8/6Wlpf+jo6P/o6Oj/6Ojo/+j + o6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo//9/f3/////////////////eHh4/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5SUlP////////////////////////////////////////////r6+v/I + yMj/qKio/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+j + o6P/o6Oj/6Ojo/+jo6P/o6Oj/6enp//FxcX/+Pj4//////////////////////////////////////// + /////////////////////v7+/9XV1f+tra3/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+j + o6P/o6Oj/6Ojo/+jo6P/0dHR/////////////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85 + OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v////////////////////////////////////////////////////////////////////////////9 + /f3/nJyc/z09Pf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/NDQ0//v7+/////////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////// + //////////////////////////////++vr7/SkpK/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9G + Rkb/t7e3/////////////////////////////////////////////////9vb2/9eXl7/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+ZmZn///////////// + ////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + /////////////////////////////////////v7+/4SEhP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/80NDT/+/v7/////////////////3h4eP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT/////////////////////////////////s7Oz/zU1Nf8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/80NDT/q6ur//////////////////////// + ///////////////a2tr/QEBA/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5mZmf/////////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/OTk5//b29v///////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr///////////////////////////////////////////////////////////////////////C + wsL/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zQ0NP/7+/v/////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP// + /////////////////////////+rq6v89PT3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/86Ojr/5OTk/////////////////////////////f39/1tbW/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/mZmZ//////// + /////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + /////////////////////////////////////////25ubv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NDQ0//v7+/////////////////94 + eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU////////////////////////////oKCg/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+Wlpb///////////// + ///////////////Q0ND/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+ZmZn/////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zk5Of/29vb///////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + ////RERE/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/80NDT/+/v7/////////////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+U + lJT///////////////////////////92dnb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2xsbP///////////////////////////6enp/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5mZmf// + ///////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP/7+/v///////////// + ////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP///////////////////////////2xsbP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////// + ////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/mZmZ/////////////////9zc3P8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/85OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/R0dH/2pqav9ra2v/a2tr/2tra/9r + a2v/a2tr/2tra/9ra2v/a2tr//z8/P////////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/lJSU////////////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/89 + PT3/aGho/21tbf9tbW3/bW1t/21tbf9tbW3/bW1t/21tbf9tbW3/bW1t/21tbf9paWn/Pj4+/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////////////////////+dnZ3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zY2Nv9gYGD/a2tr/2tra/9ra2v/a2tr/2tra/9ra2v/a2tr/2tra/+1 + tbX/////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/2pqav/39/f///////////////////////////////////////////////////////////// + /////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////9s + bGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/SEhI/+bm5v////////////////////////////////// + ///////////////////////////////q6ur/TU1N/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv// + /////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/82Njb/x8fH//////// + ///////////////////////////////////////////////////////////////c3Nz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/OTk5//b29v///////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/xcXF//////////////////////// + ////////////////////////////////////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5SUlP///////////////////////////2xsbP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+T + k5P///////////////////////////////////////////////////////////////////////////+a + mpr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi////////////////////////////nZ2d/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2FhYf////////////////////////////////////////////////// + /////////////////////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + /////////////////////////////////////////////////////////zo6Ov8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM//R0dH///////////////////////////////////////////////////////////// + //////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////////////////////// + ////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5+fn/////////////////////////////////// + /////////////////////////////////////////6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9i + YmL///////////////////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//////// + ////////////////////////////////////////////////////////////////////3Nzc/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + ////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9HR0f////////////////// + /////////////////////////////////////////////////////////3h4eP8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+UlJT///////////////////////////9sbGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/n5+f//////////////////////////////////////////////////////////////////////// + ////pqam/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv///////////////////////////52dnf8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9tbW3///////////////////////////////////////////// + ///////////////////////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////86Ojr/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/0dHR//////////////////////////////////////////////////////// + ////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP////////////////// + /////////2xsbP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+fn5////////////////////////////// + //////////////////////////////////////////////+mpqb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/YmJi////////////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/21tbf// + /////////////////////////////////////////////////////////////////////////9zc3P8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + /////////////////////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//R0dH///////////// + //////////////////////////////////////////////////////////////94eHj/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/lJSU////////////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5+fn/////////////////////////////////////////////////////////////////// + /////////6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////////////////////+d + nZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//////////////////////////////////////// + ////////////////////////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/2 + 9vb///////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ////////////////////////////////////////////////////////////////////Ojo6/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/9HR0f////////////////////////////////////////////////// + /////////////////////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////// + //////////////9sbGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/n5+f//////////////////////// + ////////////////////////////////////////////////////pqam/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/2JiYv///////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9t + bW3////////////////////////////////////////////////////////////////////////////c + 3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/0dHR//////// + ////////////////////////////////////////////////////////////////////eHh4/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5SUlP///////////////////////////2xsbP8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+fn5////////////////////////////////////////////////////////////// + //////////////+mpqb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////////////////////// + ////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/21tbf////////////////////////////////// + /////////////////////////////////////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85 + OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v//////////////////////////////////////////////////////////////////////zo6Ov8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM//R0dH///////////////////////////////////////////// + //////////////////////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////// + ////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5+fn/////////////////// + /////////////////////////////////////////////////////////6ampv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9iYmL///////////////////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/bW1t//////////////////////////////////////////////////////////////////////// + ////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9HR0f// + /////////////////////////////////////////////////////////////////////////3h4eP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////9sbGz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/n5+f//////////////////////////////////////////////////////// + ////////////////////pqam/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv////////////////// + /////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9tbW3///////////////////////////// + ///////////////////////////////////////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/OTk5//b29v///////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////86 + Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/0dHR//////////////////////////////////////// + ////////////////////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP// + /////////////////////////2xsbP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+fn5////////////// + //////////////////////////////////////////////////////////////+mpqb/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/YmJi////////////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/21tbf////////////////////////////////////////////////////////////////// + /////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + /////////////////////////////////////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//R + 0dH///////////////////////////////////////////////////////////////////////////94 + eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU////////////////////////////bGxs/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5+fn/////////////////////////////////////////////////// + /////////////////////////6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////// + //////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//////////////////////// + ////////////////////////////////////////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zk5Of/29vb///////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + ////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9DQ0P////////////////////////////////// + /////////////////////////////////////////3Z2dv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+U + lJT///////////////////////////9sbGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/np6e//////// + ////////////////////////////////////////////////////////////////////paWl/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2JiYv///////////////////////////52dnf8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + ///////////////b29v/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/p6en///////////////////////////////////////////////////////////////////////8 + /Pz/UVFR/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP///////////////////////////2xsbP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/91dXX///////////////////////////////////////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////// + ////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/0lJSf/5+fn///////////// + /////////////////////////////////////////////////////////7Kysv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/85OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/89PT3/qamp/9PT0//U1NT/1NTU/9TU1P/U + 1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/U1NT/y8vL/3R0dP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/lJSU////////////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP+N + jY3/0NDQ/9TU1P/U1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/R0dH/k5OT/zU1Nf8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////////////////////+dnZ3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/21tbf/Jycn/1NTU/9TU1P/U1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/U + 1NT/1NTU/9PT0/+urq7/QEBA/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////9s + bGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv// + /////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/OTk5//b29v///////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////88PDz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5aWlv///////////////////////////25ubv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/ZGRk////////////////////////////n5+f/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/86Ojr/+Pj4//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + /////////////////////////////////////////////////////////1NTU/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys//////////////////////// + ////hYWF/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/97 + e3v///////////////////////////+2trb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0pKSv////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + ////////////////////kJCQ/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zY2Nv/n5+f////////////////////////////CwsL/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/7m5uf///////////////////////////+3t7f86 + Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/h4eH//////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + ///////////////////////////////////////////////////////////////s7Oz/RUVF/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/jIyM//////////////////////// + //////////39/f9lZWX/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9e + Xl7/+/v7/////////////////////////////////5WVlf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0FBQf/n5+f///////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + ///////////////////////////////S0tL/RERE/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/3d3d//5+fn//////////////////////////////////////+3t7f9cXFz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/V1dX/+np6f////////////////////////////////// + /////Pz8/39/f/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9CQkL/zMzM//////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ///////////////////////////////////////////////////////////////////////////////s + 7Oz/kJCQ/1JSUv89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89 + PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/QkJC/2lpaf+6urr//v7+//////////////////////// + //////////////////////////n5+f+mpqb/Xl5e/z8/P/89PT3/PT09/z09Pf89PT3/PT09/z09Pf89 + PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf8/Pz//XFxc/6Kiov/3 + 9/f//////////////////////////////////////////////////v7+/7+/v/9ra2v/Q0ND/z09Pf89 + PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89 + PT3/PT09/z09Pf9RUVH/jY2N/+np6f////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////////////////////////////////39/f/8/Pz//Pz8//z8/P/8 + /Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/+ + /v7///////////////////////////////////////////////////////////////////////////// + /////v7+//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8 + /Pz//Pz8//z8/P/8/Pz//Pz8//7+/v////////////////////////////////////////////////// + /////////////////////////////////////Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8 + /Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//f39//////////////////////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + ///////////////////////////////IyMj/gICA/3Z2dv+lpaX/+Pj4//////////////////////// + /////////////////////////////////////////8rKyv+BgYH/dnZ2/6Ghof/19fX///////////// + ///////////////////////////////+/v7/4eHh/66urv+MjIz/eXl5/3Jycv94eHj/i4uL/66urv/k + 5OT///////////////////////////////////////////////////////////////////////z8/P/p + 6en/2NjY/9jY2P/k5OT/+Pj4////////////////////////////3t7e/4iIiP92dnb/pKSk//j4+P// + ///////////////////////////////////////////////////////////////////////////////x + 8fH/vLy8/5OTk/97e3v/c3Nz/3h4eP+Li4v/sLCw/+Xl5f////////////////////////////////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ////////////////////////////////////////////////////////////////////t7e3/zU1Nf8z + MzP/MzMz/zMzM/9qamr//v7+//////////////////////////////////////////////////////+n + p6f/NTU1/zMzM/8zMzP/MzMz/15eXv/6+vr/////////////////////////////////wcHB/19fX/80 + NDT/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zU1Nf9lZWX/yMjI//////////////////////// + //////////////////////////v7+/+dnZ3/SUlJ/zMzM/8zMzP/MzMz/zMzM/88PDz/b29v/9nZ2f// + /////////+Li4v8/Pz//MzMz/zMzM/8zMzP/cnJy//7+/v////////////////////////////////// + ///////////////////////////////o6Oj/hISE/zs7O/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/NTU1/2lpaf/Pz8////////////////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////9VVVX/MzMz/zMzM/8zMzP/MzMz/zMzM//Q0ND///////////// + ////////////////////////////////////0dHR/zc3N/8zMzP/MzMz/zMzM/8zMzP/MzMz/8fHx/// + ////////////////////9/f3/3t7e/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/80NDT/hoaG//r6+v//////////////////////////////////////hISE/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/RERE//f39///////kZGR/zMzM/8zMzP/MzMz/zMzM/8z + MzP/3d3d////////////////////////////////////////////////////////////vLy8/z8/P/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP+Pj4///Pz8//////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v/////////////////////////////////////////////////////////////////+/v7/zc3N/8z + MzP/MzMz/zMzM/8zMzP/MzMz/6+vr/////////////////////////////////////////////j4+P9U + VFT/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/19fX//////////////////r6+v9sbGz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/f39///////// + /////////////////////////+bm5v82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/83 + Nzf/8PDw//////91dXX/MzMz/zMzM/8zMzP/MzMz/zMzM//CwsL///////////////////////////// + /////////////////////////7W1tf82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9/f3///v7+//////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ///////////////////////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys//////// + ////////////////////////////////////lJSU/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/1hYWP/9 + /f3/////////////////lJSU/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/0xMTP+Hh4f/mZmZ/4eHh/9Q + UFD/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/yMjI////////////////////////////ubm5/zMzM/8z + MzP/MzMz/zMzM/82Njb/iIiI/5ubm/9/f3//ampq/7W1tf///////////3Nzc/8zMzP/MzMz/zMzM/8z + MzP/MzMz/7+/v//////////////////////////////////////////////////a2tr/OTk5/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0RERP9aWlr/S0tL/zQ0NP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+o + qKj//////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////j4+P82 + Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+srKz//////////////////////////////////////9jY2P84 + ODj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/t7e3/////////////////+bm5v85OTn/MzMz/zMzM/8z + MzP/MzMz/zMzM/+Ojo7/+fn5//////////////////z8/P+urq7/Pj4+/zMzM/8zMzP/MzMz/zMzM/+K + ior///////////////////////////+hoaH/MzMz/zMzM/8zMzP/MzMz/3d3d/////////////////// + ////////////////////c3Nz/zMzM/8zMzP/MzMz/zMzM/8zMzP/v7+///////////////////////// + /////////////////////v7+/2lpaf8zMzP/MzMz/zMzM/8zMzP/MzMz/0JCQv+9vb3/+/v7///////+ + /v7/1tbW/1lZWf8zMzP/MzMz/zMzM/8zMzP/MzMz/0BAQP/w8PD///////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + ////////////////////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/6ysrP// + ///////////////////////////////7+/v/XV1d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/15eXv/9 + /f3/////////////////l5eX/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//7+/v////////////////// + ///////////////d3d3/UFBQ/zMzM/8zMzP/MzMz/6Ojo////////////////////////////5eXl/8z + MzP/MzMz/zMzM/8zMzP/lZWV//////////////////////////////////////9zc3P/MzMz/zMzM/8z + MzP/MzMz/zMzM/+/v7/////////////////////////////////////////////b29v/NDQ0/zMzM/8z + MzP/MzMz/zMzM/82Njb/z8/P////////////////////////////8PDw/0tLS/8zMzP/MzMz/zMzM/8z + MzP/MzMz/6Wlpf////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra//////////////////////////////////////////////////////////////////4 + +Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys/////////////////////////////////6CgoP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/84ODj/1tbW//////////////////////9cXFz/MzMz/zMzM/8z + MzP/MzMz/zMzM//Kysr////////////////////////////////////////////u7u7/hISE/2dnZ/+X + l5f/+vr6////////////////////////////lZWV/zMzM/8zMzP/MzMz/zMzM/+ampr///////////// + /////////////////////////3Nzc/8zMzP/MzMz/zMzM/8zMzP/MzMz/7+/v/////////////////// + /////////////////////////5ycnP8zMzP/MzMz/zMzM/8zMzP/MzMz/3Nzc/////////////////// + ////////////////////q6ur/zMzM/8zMzP/MzMz/zMzM/8zMzP/ZmZm//////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////j4+P82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+s + rKz////////////////////////////a2tr/Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5qamv// + ////////////////////+fn5/zw8PP8zMzP/MzMz/zMzM/8zMzP/NDQ0/7S0tP++vr7/vr6+/76+vv++ + vr7/vr6+/76+vv++vr7/vr6+/7+/v//Ly8v/6urq//////////////////////////////////////+V + lZX/MzMz/zMzM/8zMzP/MzMz/5qamv//////////////////////////////////////c3Nz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/vr6+////////////////////////////////////////////dHR0/zMzM/8z + MzP/MzMz/zMzM/8zMzP/sbGx///////////////////////////////////////p6en/MzMz/zMzM/8z + MzP/MzMz/zMzM/9AQED//Pz8////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + ////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/6ysrP//////////////////////7+/v/1JSUv8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9tbW3//f39///////////////////////u7u7/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/81 + NTX/ZmZm/+rq6v///////////////////////////5WVlf8zMzP/MzMz/zMzM/8zMzP/mpqa//////// + //////////////////////////////9zc3P/MzMz/zMzM/8zMzP/MzMz/zMzM/+4uLj///////////// + //////////////////////////////9eXl7/MzMz/zMzM/8zMzP/MzMz/zMzM//Pz8////////////// + //////////////////////////////87Ozv/MzMz/zMzM/8zMzP/MzMz/zY2Nv/w8PD///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ///////////////////////////////////////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8z + MzP/rKys/////////////////+Dg4P9YWFj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/W1tb//Pz8/// + /////////////////////////+np6f8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/fHx8//////////////////////// + ////lZWV/zMzM/8zMzP/MzMz/zMzM/+ampr//////////////////////////////////////3Nzc/8z + MzP/MzMz/zMzM/8zMzP/MzMz/62trf///////////////////////////////////////////1lZWf8z + MzP/MzMz/zMzM/8zMzP/MzMz/9bW1v///////////////////////////////////////////0FBQf8z + MzP/MzMz/zMzM/8zMzP/NDQ0/+zs7P///////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////j4+P82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/9mZmb/iYmJ/4KCgv9lZWX/NjY2/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2JiYv/v7+//////////////////////////////////8/Pz/zQ0NP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9NTU3///////////////////////////+VlZX/MzMz/zMzM/8zMzP/MzMz/5qamv// + ////////////////////////////////////c3Nz/zMzM/8zMzP/MzMz/zMzM/8zMzP/mZmZ//////// + ////////////////////////////////////ZGRk/zMzM/8zMzP/MzMz/zMzM/8zMzP/x8fH//////// + ///////////////////////////////7+/v/NjY2/zMzM/8zMzP/MzMz/zMzM/84ODj/9PT0//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + ////////////////////////////////////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/83Nzf/mpqa/+np6f// + ///////////////////////////////9/f3/RkZG/zMzM/8zMzP/MzMz/zMzM/8zMzP/m5ub/6urq/+r + q6v/q6ur/6urq/+rq6v/q6ur/6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/01NTf////////////////// + /////////5WVlf8zMzP/MzMz/zMzM/8zMzP/mpqa//////////////////////////////////////9z + c3P/MzMz/zMzM/8zMzP/MzMz/zMzM/92dnb///////////////////////////////////////////+A + gID/MzMz/zMzM/8zMzP/MzMz/zMzM/+enp7//////////////////////////////////////9fX1/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0pKSv////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + ///////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5/4qKiv/09PT///////////////////////////9y + cnL/MzMz/zMzM/8zMzP/MzMz/zMzM/+zs7P/////////////////////////////////ysrK/zMzM/8z + MzP/MzMz/zMzM/8zMzP/aWlp////////////////////////////lZWV/zMzM/8zMzP/MzMz/zMzM/+a + mpr//////////////////////////////////////3Nzc/8zMzP/MzMz/zMzM/8zMzP/MzMz/0NDQ//5 + +fn//////////////////////////////////////7CwsP8zMzP/MzMz/zMzM/8zMzP/MzMz/1VVVf/8 + /Pz/////////////////////////////////ioqK/zMzM/8zMzP/MzMz/zMzM/8zMzP/enp6//////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////j4+P82Njb/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/1dXV//r6+v//////////////////////7a2tv8zMzP/MzMz/zMzM/8zMzP/MzMz/1FRUf/z + 8/P///////////////////////v7+/9mZmb/MzMz/zMzM/8zMzP/MzMz/zMzM/+jo6P///////////// + //////////////+VlZX/MzMz/zMzM/8zMzP/MzMz/5qamv////////////////////////////////// + ////c3Nz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5ycnP/////////////////z8/P/0dHR/+7u7v// + ////7+/v/zs7O/8zMzP/MzMz/zMzM/8zMzP/MzMz/5iYmP/+/v7//////////////////////8fHx/84 + ODj/MzMz/zMzM/8zMzP/MzMz/zMzM//BwcH///////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + ////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2VlZf/+/v7///////////// + ////+fn5/05OTv8zMzP/MzMz/zMzM/8zMzP/MzMz/1lZWf/FxcX/8vLy//Pz8//Ozs7/aGho/zMzM/8z + MzP/MzMz/zMzM/8zMzP/Pz8//+/v7////////////////////////////5WVlf8zMzP/MzMz/zMzM/8z + MzP/mpqa//////////////////////////////////////9zc3P/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/NDQ0/2RkZP99fX3/YmJi/zk5Of8zMzP/PDw8/7y8vP//////jIyM/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/3Jycv/CwsL/29vb/8zMzP+NjY3/ODg4/zMzM/8zMzP/MzMz/zMzM/8zMzP/W1tb//39/f// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ///////////////////////////////////////////////////////////////4+Pj/NjY2/zMzM/8z + MzP/MzMz/zMzM/8zMzP/pKSk//Ly8v/y8vL/8vLy//Ly8v/u7u7/4eHh/8XFxf+RkZH/Pz8//zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/8LCwv//////////////////////xMTE/zU1Nf8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/82Njb/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+oqKj///////////// + ////9vb2/3Nzc/88PDz/NjY2/zMzM/8zMzP/MzMz/zMzM/82Njb/OTk5/0ZGRv92dnb/7e3t//////// + /////////3Nzc/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/RUVF//v7+//z8/P/UFBQ/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zs7O//W1tb///////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////j4+P82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+srKz///////////// + ///////////////////////////////c3Nz/Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/f39///////// + ////////////////////paWl/zQ0NP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/hoaG//7+/v////////////////+2trb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+goKD/////////////////fn5+/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/+Pj4///////f39//SUlJ/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/86Ojr/v7+///////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v/////////////////////////////////////////////////////////////////+Pj4/zY2Nv8z + MzP/MzMz/zMzM/8zMzP/MzMz/6ysrP////////////////////////////////////////////////9s + bGz/MzMz/zMzM/8zMzP/MzMz/zMzM/9cXFz/////////////////////////////////vLy8/0ZGRv8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/Ozs7/6SkpP/+/v7///////////// + /////////9zc3P88PDz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NjY2/8nJyf// + //////////////+tra3/MzMz/zMzM/8zMzP/MzMz/0pKSv9dXV3/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/4eHh//////////////////q6ur/bW1t/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/VlZW/9TU1P////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ///////////////////////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys//////// + /////////////////////////////////////////3BwcP8zMzP/MzMz/zMzM/8zMzP/MzMz/1NTU/// + ////////////////////////////////////8vLy/6Kiov9aWlr/NTU1/zMzM/8zMzP/MzMz/zMzM/80 + NDT/SUlJ/46Ojv/m5ub//////////////////////////////////////+fn5/+4uLj/cHBw/zMzM/8z + MzP/MzMz/zMzM/9zc3P/srKy/7S0tP/d3d3///////////////////////j4+P9kZGT/MzMz/zMzM/84 + ODj/urq6//Dw8P9ycnL/NDQ0/zMzM/8zMzP/MzMz/01NTf+oqKj//Pz8///////////////////////+ + /v7/ysrK/3d3d/8+Pj7/MzMz/zMzM/8zMzP/MzMz/zMzM/84ODj/Z2dn/7W1tf/6+vr///////////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////j4+P82 + Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+srKz////////////////////////////////////////////r + 6+v/Pz8//zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////////////////////////////////////// + ///////////////w8PD/0dHR/8HBwf++vr7/ysrK/+Xl5f/+/v7///////////////////////////// + //////////////////////////////+VlZX/MzMz/zMzM/8zMzP/MzMz/5qamv////////////////// + //////////////////////////z8/P/Pz8//wMDA/+jo6P/////////////////k5OT/wsLC/8HBwf/d + 3d3//v7+//////////////////////////////////////////////////v7+//d3d3/xsbG/729vf/D + w8P/19fX//b29v////////////////////////////////////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + ////////////////////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/6urq//9 + /f3//f39//39/f/9/f3//f39//v7+//z8/P/xMTE/1VVVf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+N + jY3///////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////5WVlf8z + MzP/MzMz/zMzM/8zMzP/mpqa//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra//////////////////////////////////////////////////////////////////4 + +Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/Pj4+/0VFRf9FRUX/RUVF/0VFRf9ERET/Pj4+/zQ0NP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NDQ0/9jY2P////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////lpaW/zMzM/8zMzP/MzMz/zMzM/+ampr///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////r6+v82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+C + goL///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////+c + nJz/MzMz/zMzM/8zMzP/MzMz/6Kiov////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////0tLS/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/ampq//f39/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////76+vv8zMzP/MzMz/zMzM/8zMzP/xMTE//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////oaGh/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/PT09/5iYmP/7 + +/v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////f39/4aGhv85OTn/Ozs7/4+Pj//+/v7///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + ///////////////9/f3/sLCw/2dnZ/9PT0//TU1N/01NTf9NTU3/TU1N/01NTf9NTU3/TU1N/01NTf9N + TU3/T09P/1ZWVv9lZWX/gICA/7CwsP/w8PD///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////X19f/29vb///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////fHx8/zMzM/8z + MzP/Ozs7/zMzM/9fX1////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////9wcHD/MzMz/zMzM/89PT3cMzMz/z4+Pv/39/f///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////Pz8/0pKSv8z + MzP/OTk57Dw8PJUzMzP/MzMz/7W1tf////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////Gxsb/MzMz/zMzM/87OzuqS0tLNjQ0NP0zMzP/TExM//Hx8f// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////9/f3/1dXV/8z + MzP/MzMz/0VFRUmNjY0APDw8rTMzM/8zMzP/ZGRk//Hx8f////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////b29v9wcHD/MzMz/zMzM/86OjrAgYGBAgAAAABTU1MYNzc34zMzM/8z + MzP/TExM/7a2tv/39/f///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////r6+v++vr7/U1NT/zMzM/8z + MzP/NjY27E1NTSMAAAAAAAAAAAAAAABKSkoqNzc34jMzM/8zMzP/MzMz/z4+Pv9gYGD/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9iYmL/QUFB/zMzM/8zMzP/MzMz/zY2NutHR0c3AAAAAAAAAAAAAAAAAAAAAAAAAABT + U1MXPDw8rDQ0NP0zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP47 + Ozu5TU1NIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACNjY0AS0tLNTw8PJU9PT3bOzs7/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/Ojo6/0BAQOM8PDycR0dHPo+PjwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////////////////////// + ////////////////////+AAAAAAAAAAAAAAAAAAAH+AAAAAAAAAAAAAAAAAAAAfAAAAAAAAAAAAAAAAA + AAADgAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAHA + AAAAAAAAAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAB/AAAAAAAAAAAAAAAAAAAA////////////////// + //////////////////////////////////////////////8oAAAAQAAAAIAAAAABACAAAAAAAABAAAAT + CwAAEwsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgICAAENDQyYzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQEJCQil0dHQAAAAAAAAAAAAAAAAAPz8/JTc3N8Iz + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/Nzc3yD8/PyoA + AAAAQkJCGzU1NedWVlb/xMTE/+/v7//y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y + 8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y + 8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y + 8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/v + 7+//x8fH/1paWv81NTXsQUFBIDg4OJxKSkr/8PDw//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////09PT/T09P/zc3N6Y4ODjum5ub//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////6Ojo/81NTX0MzMz/7W1tf// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////+9 + vb3/MzMz/zMzM/+1tbX///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////++vr7/MzMz/zMzM/+1 + tbX/////////////////////////////////29vb/9ra2v/a2tr/2tra/9ra2v/a2tr/2tra/9ra2v/a + 2tr/2tra/9ra2v/a2tr/5+fn//////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////k5OT/2tra/9ra2v/a + 2tr/2tra/9ra2v/a2tr/2tra/9ra2v/a2tr/2tra/9ra2v/g4OD//f39//////////////////////// + ////vr6+/zMzM/8zMzP/tbW1/////////////////////////////////zc3N/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9wcHD/9vb2//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////aGho/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/1RUVP/h + 4eH//////////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////83 + Nzf/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5aWlv// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////2hoaP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/ZWVl//////////////////////++vr7/MzMz/zMzM/+1tbX///////////// + ////////////////////Nzc3/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9mZmb///////////////////////////////////////////////////////////// + //////////////////////////////////////////////9oaGj/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zg4OP/8/Pz/////////////////vr6+/zMzM/8z + MzP/tbW1/////////////////////////////////66urv+tra3/ra2t/62trf+tra3/ra2t/62trf+t + ra3/ra2t/62trf+RkZH/NDQ0/zMzM/8zMzP/Y2Nj//////////////////////////////////////// + ////////////////////////////////////////////////////////////////////wsLC/62trf+t + ra3/ra2t/62trf+tra3/ra2t/62trf+tra3/ra2t/6Ojo/9AQED/MzMz/zMzM/82Njb/+/v7//////// + /////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////////////////////// + /////////////////////////////////////////1FRUf8zMzP/MzMz/2NjY/////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////hISE/zMzM/8z + MzP/NjY2//v7+/////////////////++vr7/MzMz/zMzM/+1tbX///////////////////////////// + //////////////////////////////////////////////////////////////9VVVX/MzMz/zMzM/9j + Y2P///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////4iIiP8zMzP/MzMz/zY2Nv/7+/v/////////////////vr6+/zMzM/8zMzP/tbW1//////// + //////////////////////////7+/v+ysrL/cnJy/2tra/9ra2v/a2tr/2tra/9ra2v/a2tr//39/f// + ////VVVV/zMzM/8zMzP/Y2Nj/////////////////+/v7/+Pj4//bGxs/2tra/9ra2v/a2tr/2tra/9r + a2v/a2tr/2tra/9ra2v/bGxs/46Ojv/t7e3//////////////////////87Ozv96enr/a2tr/2tra/9r + a2v/a2tr/2tra/9ra2v/2tra//////+IiIj/MzMz/zMzM/82Njb/+/v7/////////////////76+vv8z + MzP/MzMz/7W1tf////////////////////////////////+enp7/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM//9/f3//////1VVVf8zMzP/MzMz/2NjY/////////////r6+v9WVlb/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/U1NT//j4+P///////////8zMzP82 + Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/8zMzP//////iIiI/zMzM/8zMzP/NjY2//v7+/// + //////////////++vr7/MzMz/zMzM/+1tbX/////////////////////////////////RkZG/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP//f39//////9VVVX/MzMz/zMzM/9jY2P////////////F + xcX/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//A + wMD///////////93d3f/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//MzMz//////4iIiP8z + MzP/MzMz/zY2Nv/7+/v/////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////// + /////////zc3N/8zMzP/MzMz/zMzM/9GRkb/T09P/09PT/9PT0//T09P//39/f//////VVVV/zMzM/8z + MzP/Y2Nj////////////tra2/zMzM/8zMzP/MzMz/zU1Nf9PT0//UFBQ/1BQUP9QUFD/UFBQ/09PT/82 + Njb/MzMz/zMzM/8zMzP/sbGx////////////aGho/zMzM/8zMzP/MzMz/z8/P/9PT0//T09P/09PT/9P + T0//09PT//////+IiIj/MzMz/zMzM/82Njb/+/v7/////////////////76+vv8zMzP/MzMz/7W1tf// + //////////////////////////////83Nzf/MzMz/zMzM/9lZWX//f39//////////////////////// + /////////1VVVf8zMzP/MzMz/2NjY////////////7a2tv8zMzP/MzMz/zMzM/+wsLD///////////// + ////////////////////tLS0/zMzM/8zMzP/MzMz/7Gxsf///////////2hoaP8zMzP/MzMz/z8/P//x + 8fH/////////////////////////////////iIiI/zMzM/8zMzP/NjY2//v7+/////////////////++ + vr7/MzMz/zMzM/+1tbX/////////////////////////////////Nzc3/zMzM/8zMzP/goKC//////// + //////////////////////////////9VVVX/MzMz/zMzM/9jY2P///////////+2trb/MzMz/zMzM/8z + MzP/z8/P/////////////////////////////////9LS0v8zMzP/MzMz/zMzM/+xsbH///////////9o + aGj/MzMz/zMzM/9QUFD//////////////////////////////////////4iIiP8zMzP/MzMz/zY2Nv/7 + +/v/////////////////vr6+/zMzM/8zMzP/tbW1/////////////////////////////////zc3N/8z + MzP/MzMz/4KCgv//////////////////////////////////////VVVV/zMzM/8zMzP/Y2Nj//////// + ////tra2/zMzM/8zMzP/MzMz/8/Pz//////////////////////////////////S0tL/MzMz/zMzM/8z + MzP/sbGx////////////aGho/zMzM/8zMzP/UFBQ//////////////////////////////////////+I + iIj/MzMz/zMzM/82Njb/+/v7/////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////83Nzf/MzMz/zMzM/+CgoL//////////////////////////////////////1VVVf8z + MzP/MzMz/2NjY////////////7a2tv8zMzP/MzMz/zMzM//Pz8////////////////////////////// + ////0tLS/zMzM/8zMzP/MzMz/7Gxsf///////////2hoaP8zMzP/MzMz/1BQUP////////////////// + ////////////////////iIiI/zMzM/8zMzP/NjY2//v7+/////////////////++vr7/MzMz/zMzM/+1 + tbX/////////////////////////////////Nzc3/zMzM/8zMzP/goKC//////////////////////// + //////////////9VVVX/MzMz/zMzM/9jY2P///////////+2trb/MzMz/zMzM/8zMzP/z8/P//////// + /////////////////////////9LS0v8zMzP/MzMz/zMzM/+xsbH///////////9oaGj/MzMz/zMzM/9Q + UFD//////////////////////////////////////4iIiP8zMzP/MzMz/zY2Nv/7+/v///////////// + ////vr6+/zMzM/8zMzP/tbW1/////////////////////////////////zc3N/8zMzP/MzMz/4KCgv// + ////////////////////////////////////VVVV/zMzM/8zMzP/Y2Nj////////////tra2/zMzM/8z + MzP/MzMz/8/Pz//////////////////////////////////S0tL/MzMz/zMzM/8zMzP/sbGx//////// + ////aGho/zMzM/8zMzP/UFBQ//////////////////////////////////////+IiIj/MzMz/zMzM/82 + Njb/+/v7/////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////83 + Nzf/MzMz/zMzM/93d3f//////////////////////////////////v7+/0tLS/8zMzP/MzMz/2NjY/// + /////////7a2tv8zMzP/MzMz/zMzM//ExMT/////////////////////////////////yMjI/zMzM/8z + MzP/MzMz/7Gxsf///////////2hoaP8zMzP/MzMz/0dHR//9/f3///////////////////////////// + ////fX19/zMzM/8zMzP/NjY2//v7+/////////////////++vr7/MzMz/zMzM/+1tbX///////////// + ////////////////////Nzc3/zMzM/8zMzP/NjY2/3h4eP+EhIT/hISE/4SEhP+EhIT/hISE/2lpaf8z + MzP/MzMz/zMzM/9jY2P///////////+2trb/MzMz/zMzM/8zMzP/SkpK/4KCgv+EhIT/hISE/4SEhP+E + hIT/g4OD/0xMTP8zMzP/MzMz/zMzM/+xsbH///////////9oaGj/MzMz/zMzM/8zMzP/Z2dn/4SEhP+E + hIT/hISE/4SEhP+EhIT/enp6/zY2Nv8zMzP/MzMz/zY2Nv/7+/v/////////////////vr6+/zMzM/8z + MzP/tbW1/////////////////////////////////z09Pf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/ampq////////////vLy8/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/t7e3////////////b29v/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/86Ojr//f39//////// + /////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////99fX3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/6qqqv///////////+/v7/9A + QED/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/Pj4+/+zs7P// + /////////6+vr/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/eHh4//////////////////////++vr7/MzMz/zMzM/+1tbX///////////////////////////// + ////9PT0/319ff89PT3/ODg4/zg4OP84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84ODj/RERE/5iYmP/+ + /v7/////////////////0NDQ/1paWv84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84 + ODj/WVlZ/83Nzf/////////////////+/v7/nJyc/0VFRf84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84 + ODj/ODg4/zg4OP89PT3/e3t7//Ly8v//////////////////////vr6+/zMzM/8zMzP/tbW1//////// + //////////////////////////////////////////7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+ + /v7//v7+/////////////////////////////////////////////v7+//7+/v/+/v7//v7+//7+/v/+ + /v7//v7+//7+/v/+/v7//v7+/////////////////////////////////////////////v7+//7+/v/+ + /v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//////////////////////////////////////76+vv8z + MzP/MzMz/7W1tf////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////++vr7/MzMz/zMzM/+1tbX///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////++ + vr7/MzMz/zMzM/+1tbX///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////Hx8f+9 + vb3/5+fn/////////////////////////////////9LS0v/FxcX//Pz8///////////////////////j + 4+P/wcHB/7q6uv/Ozs7/+Pj4//////////////////////////////////n5+f/r6+v/9/f3//////// + ////9/f3/7+/v//n5+f///////////////////////////////////////z8/P/T09P/u7u7/8DAwP/l + 5eX//////////////////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////9dXV3/MzMz/0FBQf/z8/P//////////////////////6urq/8zMzP/MzMz/5SUlP// + /////////9zc3P9iYmL/MzMz/zMzM/8zMzP/MzMz/0BAQP+goKD//v7+/////////////////5SUlP85 + OTn/MzMz/zU1Nf9wcHD//f39/3l5ef8zMzP/Q0ND//b29v///////////////////////////7m5uf9J + SUn/MzMz/zMzM/8zMzP/MzMz/2hoaP/i4uL///////////////////////////++vr7/MzMz/zMzM/+1 + tbX////////////////////////////8/Pz/NTU1/zMzM/8zMzP/1tbW/////////////////+Li4v87 + Ozv/MzMz/zMzM/+YmJj//////+Pj4/9BQUH/MzMz/zMzM/9OTk7/YWFh/zo6Ov8zMzP/MzMz/56env// + /////////+fn5/80NDT/MzMz/0lJSf9gYGD/YmJi//v7+/9UVFT/MzMz/zMzM//g4OD///////////// + /////////7Kysv80NDT/MzMz/zMzM/9BQUH/OTk5/zMzM/8zMzP/RkZG/+np6f////////////////// + ////vr6+/zMzM/8zMzP/tbW1/////////////////////////////Pz8/zQ0NP8zMzP/MzMz/9XV1f// + //////////7+/v9oaGj/MzMz/zMzM/8+Pj7/7e3t//////96enr/MzMz/zMzM/+Li4v//v7+///////q + 6ur/aGho/zMzM/9lZWX////////////Ozs7/MzMz/zMzM//Dw8P/////////////////U1NT/zMzM/8z + MzP/39/f//////////////////b29v9BQUH/MzMz/zQ0NP+zs7P//v7+//T09P9ycnL/MzMz/zMzM/+C + goL//////////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////z8/P80 + NDT/MzMz/zMzM//V1dX///////////+tra3/MzMz/zMzM/8zMzP/qqqq///////+/v7/QEBA/zMzM/8z + MzP/z8/P/97e3v/e3t7/3t7e/9ra2v+oqKj/5OTk////////////ysrK/zMzM/8zMzP/zMzM//////// + /////////1NTU/8zMzP/MzMz/9/f3//////////////////Dw8P/MzMz/zMzM/9iYmL///////////// + ////5OTk/zMzM/8zMzP/Q0ND//7+/v////////////////++vr7/MzMz/zMzM/+1tbX///////////// + ///////////////8/Pz/NDQ0/zMzM/8zMzP/1dXV///////Jycn/Ozs7/zMzM/8zMzP/e3t7//7+/v// + ////9fX1/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/4CAgP///////////8rKyv8z + MzP/MzMz/8zMzP////////////////9TU1P/MzMz/zMzM//Z2dn/////////////////ra2t/zMzM/8z + MzP/g4OD//////////////////////84ODj/MzMz/zQ0NP/39/f/////////////////vr6+/zMzM/8z + MzP/tbW1/////////////////////////////Pz8/zQ0NP8zMzP/MzMz/1VVVf9TU1P/NDQ0/zMzM/8z + MzP/WVlZ//b29v////////////v7+/84ODj/MzMz/zMzM/9ra2v/b29v/29vb/9ubm7/MzMz/zMzM/9A + QED////////////Kysr/MzMz/zMzM//MzMz/////////////////U1NT/zMzM/8zMzP/w8PD//////// + /////////7i4uP8zMzP/MzMz/3Nzc//////////////////09PT/NDQ0/zMzM/86Ojr//Pz8//////// + /////////76+vv8zMzP/MzMz/7W1tf////////////////////////////z8/P80NDT/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9KSkr/zc3N////////////ZGRk/zMzM/8zMzP/vb29//////// + ////ysrK/zMzM/8zMzP/XV1d////////////ysrK/zMzM/8zMzP/zMzM/////////////////1NTU/8z + MzP/MzMz/4ODg////////Pz8/+/v7//n5+f/NTU1/zMzM/88PDz/5OTk////////////oqKi/zMzM/8z + MzP/aGho//////////////////////++vr7/MzMz/zMzM/+1tbX////////////////////////////8 + /Pz/NDQ0/zMzM/8zMzP/f39//5KSkv+SkpL/g4OD/01NTf8zMzP/MzMz/z8/P//v7+///////8PDw/80 + NDT/MzMz/zw8PP+IiIj/i4uL/0BAQP8zMzP/MzMz/7W1tf//////2tra/4GBgf8zMzP/MzMz/4KCgv+u + rq7/+vr6//////9TU1P/MzMz/zMzM/8zMzP/UlJS/0BAQP81NTX/v7+//4GBgf8zMzP/MzMz/0NDQ/+B + gYH/cHBw/zQ0NP8zMzP/NTU1/8vLy///////////////////////vr6+/zMzM/8zMzP/tbW1//////// + /////////////////////Pz8/zQ0NP8zMzP/MzMz/9XV1f/////////////////29vb/Q0ND/zMzM/8z + MzP/tra2////////////paWl/zg4OP8zMzP/MzMz/zMzM/8zMzP/NTU1/5eXl////////////4CAgP8z + MzP/MzMz/zMzM/8zMzP/NDQ0/9ra2v//////ZGRk/zMzM/85OTn/Pj4+/zMzM/8zMzP/MzMz/66urv/3 + 9/f/dXV1/zMzM/8zMzP/MzMz/zMzM/8zMzP/PDw8/7Ozs////////////////////////////76+vv8z + MzP/MzMz/7W1tf////////////////////////////z8/P80NDT/MzMz/zMzM//V1dX///////////// + ////+vr6/0VFRf8zMzP/MzMz/62trf/////////////////l5eX/n5+f/35+fv97e3v/mJiY/9zc3P// + ///////////////5+fn/r6+v/zMzM/8zMzP/sLCw/+Tk5P///////////9bW1v99fX3/tra2/9jY2P+D + g4P/gYGB/7y8vP/+/v7////////////Q0ND/k5OT/3p6ev+AgID/paWl/+vr6/////////////////// + //////////////++vr7/MzMz/zMzM/+1tbX////////////////////////////8/Pz/NDQ0/zMzM/8z + MzP/i4uL/6Ghof+hoaH/mJiY/2BgYP8zMzP/MzMz/zMzM//Z2dn///////////////////////////// + /////////////////////////////////////////8rKyv8zMzP/MzMz/83Nzf////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////// + /////v7+/zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+FhYX///////////// + ///////////////////////////////////////////////////////////////W1tb/MzMz/zMzM//Z + 2dn///////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf// + //////////////////////////////+goKD/R0dH/0BAQP9AQED/QEBA/0BAQP9AQED/SEhI/2VlZf+x + sbH//v7+//////////////////////////////////////////////////////////////////////// + /////v7+/62trf+wsLD///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////++ + vr7/MzMz/zMzM/+1tbX///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////++vr7/MzMz/zMzM/+1 + tbX///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////+9vb3/MzMz/zc3N/alpaX///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////ra2t/zQ0NPo3 + NzeyWlpa//v7+/////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////f39/2FhYf83Nze8Pj4+MTQ0NPh1dXX/6+vr//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////7e3t/3t7e/80NDT6Pj4+OQAAAAA8PDxJNTU16jY2Nv9MTEz/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/TU1N/zY2Nv81NTXtOzs7UAAAAAAAAAAAAAAAAEtLSw09 + PT1cNzc3gDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDc3N4A+Pj5gSEhIEAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAP//////////wAAAAAAAAAOAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAHAAAAAAAAAA///////////KAAAADAAAABg + AAAAAQAgAAAAAAAAJAAAEwsAABMLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA9PT0lNzc3kTMzM68z + MzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68z + MzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68z + MzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzY2NpQ8PDwoAAAAADs7OzM6 + OjrvkpKS/8DAwP/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/C + wsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/C + wsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wcHB/5WVlf87 + OzvxOzs7ODY2NsGtra3///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////+0tLT/NjY2yTs7O/zv7+////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////z8/P/Ozs7/jo6Ov/09PT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////01NTf9KSkr/SkpK/0pKSv9KSkr/SkpK/0pKSv9K + Skr/SkpK/11dXf/MzMz///////////////////////////////////////////////////////////// + ////////////////////m5ub/0pKSv9KSkr/SkpK/0pKSv9KSkr/SkpK/0pKSv9KSkr/Tk5O/5CQkP/8 + /Pz////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9ISEj/+vr6//////////////////////////////////////// + ////////////////////////////////////jo6O/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+2trb////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////15eXv9b + W1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9YWFj/NTU1/zMzM/80NDT/7+/v//////////////////////// + ////////////////////////////////////////////////////pKSk/1tbW/9bW1v/W1tb/1tbW/9b + W1v/W1tb/1tbW/9DQ0P/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + ////////////////////////////////////////////////////dHR0/zMzM/80NDT/7+/v//////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////MzMz/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/0 + 9PT////////////////////////////6+vr/8/Pz//Pz8//z8/P/8/Pz//b29v//////gICA/zMzM/80 + NDT/7+/v/////////////Pz8//T09P/z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//29vb///////////// + //////////7+/v/09PT/8/Pz//Pz8//z8/P/8/Pz//39/f/Z2dn/MzMz/zMzM/+YmJj////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////8HBwf9HR0f/NjY2/zY2Nv82Njb/NjY2/2dnZ/// + ////gICA/zMzM/80NDT/7+/v///////e3t7/VVVV/zY2Nv82Njb/NjY2/zY2Nv82Njb/NjY2/zY2Nv88 + PDz/kJCQ////////////8/Pz/2pqav84ODj/NjY2/zY2Nv82Njb/NjY2/9nZ2f/Z2dn/MzMz/zMzM/+Y + mJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////0pKSv8zMzP/MzMz/zMzM/8z + MzP/MzMz/2VlZf//////gICA/zMzM/80NDT/7+/v//////92dnb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/9jY2P//////oqKi/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9nZ2f/Z + 2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8z + MzP/NjY2/3V1df97e3v/e3t7/5ubm///////gICA/zMzM/80NDT/7+/v//////9iYmL/MzMz/zMzM/9o + aGj/fHx8/3x8fP98fHz/e3t7/0ZGRv8zMzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/WVlZ/3t7e/97 + e3v/e3t7/+bm5v/Z2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////////zY2Nv8zMzP/ampq////////////////////////////gICA/zMzM/80NDT/7+/v//////9i + YmL/MzMz/0FBQf/7+/v//////////////////////6ampv8zMzP/MzMz/8TExP//////jo6O/zMzM/8z + MzP/3d3d///////////////////////Z2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////////zY2Nv8zMzP/bm5u////////////////////////////gICA/zMzM/80 + NDT/7+/v//////9iYmL/MzMz/0NDQ//+/v7//////////////////////6urq/8zMzP/MzMz/8TExP// + ////jo6O/zMzM/8zMzP/4uLi///////////////////////Z2dn/MzMz/zMzM/+YmJj////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8zMzP/bm5u//////////////////////// + ////gICA/zMzM/80NDT/7+/v//////9iYmL/MzMz/0NDQ//+/v7//////////////////////6urq/8z + MzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/4uLi///////////////////////Z2dn/MzMz/zMzM/+Y + mJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8zMzP/bm5u//////// + ////////////////////gICA/zMzM/80NDT/7+/v//////9iYmL/MzMz/0NDQ//+/v7///////////// + /////////6urq/8zMzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/4uLi///////////////////////Z + 2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8z + MzP/aGho////////////////////////////enp6/zMzM/80NDT/7+/v//////9iYmL/MzMz/0BAQP/7 + +/v//////////////////////6Wlpf8zMzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/29vb//////// + ///////////////S0tL/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////////zY2Nv8zMzP/NDQ0/2lpaf9vb2//b29v/29vb/9ra2v/Nzc3/zMzM/80NDT/7+/v//////9i + YmL/MzMz/zMzM/9dXV3/b29v/29vb/9vb2//b29v/0FBQf8zMzP/MzMz/8TExP//////jo6O/zMzM/8z + MzP/UFBQ/29vb/9vb2//b29v/29vb/9OTk7/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////////01NTf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9D + Q0P/+Pj4//////95eXn/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NDQ0/9vb2/// + ////paWl/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+wsLD////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////8nJyf9NTU3/Nzc3/zc3N/83Nzf/Nzc3/zc3N/83 + Nzf/Nzc3/0hISP+9vb3////////////j4+P/Xl5e/zc3N/83Nzf/Nzc3/zc3N/83Nzf/Nzc3/zc3N/8/ + Pz//m5ub////////////9vb2/3R0dP85OTn/Nzc3/zc3N/83Nzf/Nzc3/zc3N/83Nzf/OTk5/3t7e//4 + +Pj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////////////////v7+//7+/v/+ + /v7//v7+//7+/v/+/v7//v7+//////////////////////////////////7+/v/+/v7//v7+//7+/v/+ + /v7//v7+//7+/v/////////////////////////////////+/v7//v7+//7+/v/+/v7//v7+//7+/v/+ + /v7//v7+///////////////////////4+Pj/PDw8/zo6Ov/09PT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zo6Ov/09PT///////////////////////7+/v/6+vr////////////////////////////5 + +fn///////////////////////7+/v/39/f//Pz8//////////////////////////////////////// + //////////7+/v/6+vr//////////////////////////////////v7+//b29v/9/f3///////////// + ///////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////2xsbP9ERET/2dnZ//////// + /////////6ampv8+Pj7/lJSU///////6+vr/mJiY/01NTf88PDz/QUFB/3Z2dv/j4+P////////////g + 4OD/bm5u/1hYWP90dHT/6+vr/39/f/9ERET/3Nzc//////////////////v7+/+bm5v/TU1N/zs7O/9F + RUX/goKC/+/v7//////////////////4+Pj/PDw8/zo6Ov/09PT//////////////////f39/zQ0NP8z + MzP/ra2t////////////2tra/zg4OP8zMzP/ioqK//////9+fn7/MzMz/0ZGRv+Hh4f/ZmZm/zQ0NP9M + TEz/+Pj4//////+Dg4P/MzMz/29vb/+BgYH/5eXl/0tLS/8zMzP/tLS0/////////////////4GBgf8z + MzP/Pj4+/3BwcP9JSUn/MzMz/1lZWf/4+Pj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////Pz8/zQ0NP8zMzP/ra2t///////7+/v/YGBg/zMzM/9AQED/5+fn/+Xl5f82Njb/MzMz/9bW1v// + /////v7+/6mpqf9vb2//9/f3//////9ycnL/MzMz/9fX1////////////0tLS/8zMzP/tLS0//////// + ////5ubm/zQ0NP80NDT/y8vL///////s7Oz/QUFB/zMzM/+5ubn////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////Pz8/zQ0NP8zMzP/ra2t//39/f+Pj4//MzMz/zU1Nf+4uLj//////8fHx/8z + MzP/MzMz/01NTf9OTk7/Tk5O/09PT/9wcHD/9fX1//////9xcXH/MzMz/9nZ2f///////////0tLS/8z + MzP/sLCw////////////w8PD/zMzM/9AQED/+fn5////////////Z2dn/zMzM/+VlZX////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////Pz8/zQ0NP8zMzP/RkZG/0ZGRv8zMzP/MzMz/2pqav/x + 8fH//////9LS0v8zMzP/MzMz/4uLi/+Tk5P/jo6O/zMzM/8zMzP/2NjY//////9xcXH/MzMz/9nZ2f// + /////////0tLS/8zMzP/mZmZ////////////z8/P/zMzM/84ODj/7u7u///////+/v7/V1dX/zMzM/+h + oaH////////////4+Pj/PDw8/zo6Ov/09PT//////////////////Pz8/zQ0NP8zMzP/QEBA/0lJSf9G + Rkb/NjY2/zMzM/9NTU3/6enp//j4+P9LS0v/MzMz/4yMjP/f39//lZWV/zMzM/9FRUX/9vb2//b29v9q + amr/MzMz/8bGxv/5+fn//////0tLS/8zMzP/S0tL/6+vr/+SkpL/z8/P/0lJSf8zMzP/enp6/9PT0/+b + m5v/NDQ0/zg4OP/e3t7////////////4+Pj/PDw8/zo6Ov/09PT//////////////////Pz8/zQ0NP8z + MzP/rKys//39/f/8/Pz/4ODg/zw8PP8zMzP/nJyc///////Ly8v/QUFB/zMzM/8zMzP/MzMz/z09Pf/C + wsL//////3R0dP8zMzP/MzMz/zQ0NP+Ghob//////1VVVf8zMzP/PDw8/zMzM/8zMzP/jIyM/83Nzf9D + Q0P/MzMz/zMzM/8zMzP/ODg4/62trf/////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////Pz8/zQ0NP8zMzP/ra2t////////////6+vr/z09Pf8zMzP/kpKS////////////8PDw/7Kysv+b + m5v/ra2t/+zs7P////////////X19f9oaGj/MzMz/8LCwv/39/f//////9HR0f+oqKj/5eXl/6CgoP+z + s7P/+Pj4///////y8vL/tLS0/5ubm/+rq6v/5ubm///////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////f39/zU1Nf8zMzP/RkZG/1NTU/9RUVH/PT09/zMzM/83Nzf/0tLS//////// + //////////////////////////////////////////////90dHT/MzMz/9vb2/////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////3l5ef8+Pj7/PT09/z09Pf89PT3/QkJC/2FhYf/B + wcH////////////////////////////////////////////////////////////FxcX/i4uL//r6+v// + //////////////////////////////////////////////////////////////////////////////// + ///////////////4+Pj/PDw8/zo6Ov/09PT///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zs7O/7x8fH///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////19fX/Ozs7/zY2NtC/v7////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////FxcX/NjY21zo6OkpDQ0P5srKy/+Dg4P/h4eH/4eHh/+Hh4f/h + 4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h + 4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h + 4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4ODg/7W1tf9FRUX7OTk5UHFxcQA6OjpCNjY2uTQ0NN8z + MzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98z + MzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98z + MzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfNDQ03zc3N7w6OjpGa2trAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAP///////wAAgAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////8AACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAABMLAAAT + CwAAAAAAAAAAAAAAAAAARERECjMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAz + MzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAz + MzMgMzMzIDMzMyBDQ0MKAAAAADc3N0pjY2PwkpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+S + kpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+S + kpL/kpKS/5KSkv+SkpL/kpKS/2VlZfE3NzdOWVlZ4vv7+/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////Pz8/1tbW+Z0dHT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////eHh4/3R0dP////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////94eHj/dHR0//////// + /////////4iIiP+Hh4f/h4eH/4eHh/+Hh4f/h4eH/6Kiov/9/f3///////////////////////////// + ////////////////////0tLS/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/iIiI/8zMzP///////////3h4eP90 + dHT/////////////////NTU1/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/7+/v/////////////////// + //////////////////////////////+0tLT/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/QUFB//7+/v// + ////eHh4/3R0dP/////////////////W1tb/1tbW/9bW1v/W1tb/1tbW/4WFhf8zMzP/sbGx//////// + //////////////////////////////////////////Dw8P/W1tb/1tbW/9bW1v/W1tb/09PT/0pKSv81 + NTX//f39//////94eHj/dHR0/////////////////+zs7P+3t7f/tbW1/7W1tf/a2tr/qqqq/zMzM/+x + sbH//////9/f3/+1tbX/tbW1/7W1tf+1tbX/tbW1/97e3v///////////9HR0f+1tbX/tbW1/7W1tf/2 + 9vb/XV1d/zU1Nf/9/f3//////3h4eP90dHT/////////////////UlJS/zMzM/8zMzP/MzMz/5iYmP+q + qqr/MzMz/7Gxsf/v7+//PDw8/zMzM/8zMzP/MzMz/zMzM/8zMzP/Ozs7/+7u7v/Q0ND/NDQ0/zMzM/8z + MzP/MzMz/+Xl5f9dXV3/NTU1//39/f//////eHh4/3R0dP////////////////81NTX/QEBA/6SkpP+n + p6f/09PT/6qqqv8zMzP/sbGx/9ra2v8zMzP/U1NT/6enp/+np6f/p6en/1RUVP8zMzP/2NjY/7S0tP8z + MzP/aGho/6enp/+np6f/9PT0/11dXf81NTX//f39//////94eHj/dHR0/////////////////zU1Nf9b + W1v/////////////////qqqq/zMzM/+xsbH/2tra/zMzM/+BgYH/////////////////g4OD/zMzM//Y + 2Nj/tLS0/zMzM/+np6f/////////////////XV1d/zU1Nf/9/f3//////3h4eP90dHT///////////// + ////NTU1/1tbW/////////////////+qqqr/MzMz/7Gxsf/a2tr/MzMz/4GBgf////////////////+D + g4P/MzMz/9jY2P+0tLT/MzMz/6enp/////////////////9dXV3/NTU1//39/f//////eHh4/3R0dP// + //////////////81NTX/WFhY/////////////////6enp/8zMzP/sbGx/9ra2v8zMzP/fn5+//////// + /////////4CAgP8zMzP/2NjY/7S0tP8zMzP/paWl/////////////////1tbW/81NTX//f39//////94 + eHj/dHR0/////////////////zY2Nv80NDT/WVlZ/1tbW/9bW1v/QUFB/zMzM/+zs7P/3Nzc/zMzM/85 + OTn/W1tb/1tbW/9bW1v/OTk5/zMzM//Z2dn/tbW1/zMzM/9AQED/W1tb/1tbW/9ZWVn/NDQ0/zY2Nv/9 + /f3//////3h4eP90dHT/////////////////iIiI/zc3N/81NTX/NTU1/zU1Nf81NTX/UVFR/+np6f/7 + +/v/Z2dn/zY2Nv81NTX/NTU1/zU1Nf82Njb/ZmZm//r6+v/r6+v/UlJS/zU1Nf81NTX/NTU1/zU1Nf83 + Nzf/hoaG////////////eHh4/3R0dP////////////////////////////7+/v/+/v7//v7+//7+/v// + /////////////////////v7+//7+/v/+/v7//v7+//7+/v///////////////////////v7+//7+/v/+ + /v7//v7+//////////////////////94eHj/dHR0//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3h4eP90dHT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////eHh4/3R0dP////////////////+Q + kJD/xsbG////////////rKys/6Kiov//////z8/P/4KCgv97e3v/tra2////////////sbGx/5OTk//b + 29v/mZmZ/8jIyP///////////+3t7f+Tk5P/eHh4/6CgoP/4+Pj///////////94eHj/dHR0//////// + /////f39/zQ0NP+EhIT//////9LS0v81NTX/fX19/9fX1/83Nzf/g4OD/6Ghof9AQED/wMDA/+3t7f8z + MzP/m5ub/9fX1/9DQ0P/iYmJ///////9/f3/VlZW/1NTU/+bm5v/Q0ND/3l5ef///////////3h4eP90 + dHT////////////9/f3/NDQ0/4SEhP/y8vL/U1NT/0VFRf/q6ur/mZmZ/zMzM/+FhYX/iYmJ/3p6ev/Y + 2Nj/5OTk/zMzM//m5ub//////0NDQ/+Hh4f//////9zc3P8zMzP/ubm5//////+UlJT/Nzc3//39/f// + ////eHh4/3R0dP////////////39/f80NDT/PDw8/zs7O/8zMzP/c3Nz//Pz8/+lpaX/MzMz/6ampv+q + qqr/MzMz/6enp//k5OT/MzMz/+bm5v//////Q0ND/2tra//+/v7/4+Pj/zMzM/+kpKT//////39/f/9C + QkL//v7+//////94eHj/dHR0/////////////f39/zQ0NP9vb2//ycnJ/7Gxsf83Nzf/hoaG//Dw8P9R + UVH/S0tL/0xMTP9NTU3/7Ozs/4SEhP8zMzP/ZmZm//X19f9HR0f/Nzc3/z4+Pv91dXX/iIiI/zc3N/9W + Vlb/NTU1/6ysrP///////////3h4eP90dHT////////////9/f3/NDQ0/3Fxcf/Q0ND/vLy8/zg4OP97 + e3v///////j4+P/Hx8f/xMTE//b29v//////3Nzc/zMzM//Y2Nj//////9TU1P/j4+P/wcHB/+7u7v// + ////2NjY/76+vv/k5OT/////////////////eHh4/3R0dP////////////////9VVVX/OTk5/zk5Of88 + PDz/X19f/+Dg4P/////////////////////////////////19fX/cXFx//X19f////////////////// + //////////////////////////////////////////////94eHj/dHR0//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////3h4eP90dHT///////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////eHh4/3R0dP// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////94 + eHj/X19f6v7+/v////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////v7+/2FhYe03NzdcdHR0+qampv+np6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+n + p6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+n + p6f/p6en/6enp/92dnb7Nzc3YQAAAAA+Pj4aNTU1QDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNANTU1QEBAQBwAAAAAgAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAEoAAAAEAAAACAAAAABACAAAAAAAAAEAAAT + CwAAEwsAAAAAAAAAAAAAWFhYUYeHh4+IiIiPiIiIj4iIiI+IiIiPiIiIj4iIiI+IiIiPiIiIj4iIiI+I + iIiPiIiIj4iIiI+IiIiPWVlZUrS0tPj///////////////////////////////////////////////// + /////////////////////////7a2tvm6urr//////8PDw//Dw8P/w8PD/+fn5/////////////////// + ////9PT0/8PDw//Dw8P/w8PD//Ly8v+8vLz/urq6//////+FhYX/hISE/3BwcP91dXX///////////// + /////////+jo6P+EhIT/hISE/2FhYf+cnJz/vLy8/7q6uv//////ioqK/3R0dP+ysrL/cnJy/8LCwv90 + dHT/dHR0/4CAgP/v7+//e3t7/3R0dP+lpaX/mZmZ/7y8vP+6urr//////0FBQf/S0tL/ycnJ/3Jycv+H + h4f/n5+f/9PT0/9PT0//xsbG/11dXf/T09P/q6ur/5mZmf+8vLz/urq6//////9HR0f//////9TU1P9y + cnL/h4eH/7+/v///////Wlpa/8bGxv9tbW3//////62trf+ZmZn/vLy8/7q6uv//////SkpK/0hISP9C + QkL/iIiI/5ycnP9AQED/SEhI/0JCQv/d3d3/Pz8//0hISP8+Pj7/rq6u/7y8vP+6urr///////////// + //////////////////////////////////////////////////////////////+8vLz/urq6///////V + 1dX//////9PT0//z8/P/v7+//+3t7f/s7Oz/29vb/9jY2P//////4ODg/8XFxf/9/f3/vLy8/7q6uv/+ + /v7/XFxc/8XFxf94eHj/dnZ2/4yMjP+VlZX/jo6O/9bW1v9mZmb/9vb2/2VlZf+cnJz/q6ur/7y8vP+6 + urr//v7+/0RERP96enr/iYmJ/4aGhv96enr/hYWF/3R0dP/Q0ND/S0tL/6Wlpf9mZmb/goKC/7u7u/+8 + vLz/urq6//7+/v9NTU3/gICA/3x8fP/9/f3/4uLi//39/f+dnZ3/8/Pz/+3t7f/r6+v/9fX1/+jo6P// + ////vLy8/7q6uv////////////////////////////////////////////////////////////////// + /////////7y8vP+2trb6//////////////////////////////////////////////////////////// + //////////////+3t7f7YWFhXJCQkJ+QkJCfkJCQn5CQkJ+QkJCfkJCQn5CQkJ+QkJCfkJCQn5CQkJ+Q + kJCfkJCQn5CQkJ+QkJCfYmJiXgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + + + \ No newline at end of file diff --git a/src/RetroGOG/frmCoreSelect.Designer.cs b/src/RetroGOG/frmCoreSelect.Designer.cs new file mode 100644 index 0000000..747de14 --- /dev/null +++ b/src/RetroGOG/frmCoreSelect.Designer.cs @@ -0,0 +1,104 @@ +namespace RetroGOG +{ + partial class frmCoreSelect + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.cboCore = new System.Windows.Forms.ComboBox(); + this.btnSave = new System.Windows.Forms.Button(); + this.lblConsoleName = new System.Windows.Forms.Label(); + this.label1 = new System.Windows.Forms.Label(); + this.SuspendLayout(); + // + // cboCore + // + this.cboCore.FormattingEnabled = true; + this.cboCore.Location = new System.Drawing.Point(12, 47); + this.cboCore.Name = "cboCore"; + this.cboCore.Size = new System.Drawing.Size(369, 21); + this.cboCore.TabIndex = 0; + // + // btnSave + // + this.btnSave.Location = new System.Drawing.Point(306, 74); + this.btnSave.Name = "btnSave"; + this.btnSave.Size = new System.Drawing.Size(75, 23); + this.btnSave.TabIndex = 1; + this.btnSave.Text = "&Save"; + this.btnSave.UseVisualStyleBackColor = true; + this.btnSave.Click += new System.EventHandler(this.btnSave_Click); + // + // lblConsoleName + // + this.lblConsoleName.AutoSize = true; + this.lblConsoleName.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblConsoleName.Location = new System.Drawing.Point(9, 26); + this.lblConsoleName.Name = "lblConsoleName"; + this.lblConsoleName.Size = new System.Drawing.Size(46, 18); + this.lblConsoleName.TabIndex = 2; + this.lblConsoleName.Text = "label1"; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.label1.Location = new System.Drawing.Point(9, 8); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(129, 18); + this.label1.TabIndex = 3; + this.label1.Text = "Choose a core for"; + // + // frmCoreSelect + // + this.AcceptButton = this.btnSave; + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(393, 108); + this.Controls.Add(this.label1); + this.Controls.Add(this.lblConsoleName); + this.Controls.Add(this.btnSave); + this.Controls.Add(this.cboCore); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.MaximizeBox = false; + this.Name = "frmCoreSelect"; + this.ShowInTaskbar = false; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Select Retroarch Plugin"; + this.Load += new System.EventHandler(this.frmCoreSelect_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.ComboBox cboCore; + private System.Windows.Forms.Button btnSave; + private System.Windows.Forms.Label lblConsoleName; + private System.Windows.Forms.Label label1; + } +} \ No newline at end of file diff --git a/src/RetroGOG/frmCoreSelect.cs b/src/RetroGOG/frmCoreSelect.cs new file mode 100644 index 0000000..99d80f0 --- /dev/null +++ b/src/RetroGOG/frmCoreSelect.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace RetroGOG +{ + public partial class frmCoreSelect : Form + { + public frmCoreSelect() + { + InitializeComponent(); + } + + private void frmCoreSelect_Load(object sender, EventArgs e) + { + lblConsoleName.Text = this.Text; + this.Text = "Select Retorarch Plugin"; + var files = Directory.EnumerateFiles(Globals.RAPath.Replace("retroarch.exe", "cores\\")).Select(Path.GetFileName); + foreach (var file in files) + { + cboCore.Items.Add(file); + } + } + + private void btnSave_Click(object sender, EventArgs e) + { + Globals.TempCore = cboCore.Text; + this.Close(); + } + } +} diff --git a/src/RetroGOG/frmCoreSelect.resx b/src/RetroGOG/frmCoreSelect.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/src/RetroGOG/frmCoreSelect.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/RetroGOG/frmDependencies.Designer.cs b/src/RetroGOG/frmDependencies.Designer.cs new file mode 100644 index 0000000..d97844d --- /dev/null +++ b/src/RetroGOG/frmDependencies.Designer.cs @@ -0,0 +1,268 @@ +namespace RetroGOG +{ + partial class frmDependencies + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmDependencies)); + this.btnAbout = new System.Windows.Forms.Button(); + this.btnCancel = new System.Windows.Forms.Button(); + this.btnNext = new System.Windows.Forms.Button(); + this.btnBack = new System.Windows.Forms.Button(); + this.pictureBox2 = new System.Windows.Forms.PictureBox(); + this.pictureBox1 = new System.Windows.Forms.PictureBox(); + this.lblExplain = new System.Windows.Forms.Label(); + this.imgRetroStatus = new System.Windows.Forms.PictureBox(); + this.imgGOGStatus = new System.Windows.Forms.PictureBox(); + this.lblRetroStatus = new System.Windows.Forms.Label(); + this.lblGOGStatus = new System.Windows.Forms.Label(); + this.lblRetroBrowse = new System.Windows.Forms.Label(); + this.txtRetroPath = new System.Windows.Forms.TextBox(); + this.btnRetroBrowse = new System.Windows.Forms.Button(); + this.tmrCheck = new System.Windows.Forms.Timer(this.components); + this.btnDownloadGOG = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.imgRetroStatus)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.imgGOGStatus)).BeginInit(); + this.SuspendLayout(); + // + // btnAbout + // + this.btnAbout.Location = new System.Drawing.Point(12, 343); + this.btnAbout.Name = "btnAbout"; + this.btnAbout.Size = new System.Drawing.Size(75, 23); + this.btnAbout.TabIndex = 8; + this.btnAbout.Text = "&About"; + this.btnAbout.UseVisualStyleBackColor = true; + this.btnAbout.Click += new System.EventHandler(this.btnAbout_Click); + // + // btnCancel + // + this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.btnCancel.Location = new System.Drawing.Point(543, 343); + this.btnCancel.Name = "btnCancel"; + this.btnCancel.Size = new System.Drawing.Size(75, 23); + this.btnCancel.TabIndex = 7; + this.btnCancel.Text = "&Cancel"; + this.btnCancel.UseVisualStyleBackColor = true; + this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); + // + // btnNext + // + this.btnNext.Enabled = false; + this.btnNext.Location = new System.Drawing.Point(462, 343); + this.btnNext.Name = "btnNext"; + this.btnNext.Size = new System.Drawing.Size(75, 23); + this.btnNext.TabIndex = 6; + this.btnNext.Text = "&Next > >"; + this.btnNext.UseVisualStyleBackColor = true; + this.btnNext.Click += new System.EventHandler(this.btnNext_Click); + // + // btnBack + // + this.btnBack.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.btnBack.Location = new System.Drawing.Point(93, 343); + this.btnBack.Name = "btnBack"; + this.btnBack.Size = new System.Drawing.Size(75, 23); + this.btnBack.TabIndex = 9; + this.btnBack.Text = "< < &Back"; + this.btnBack.UseVisualStyleBackColor = true; + this.btnBack.Click += new System.EventHandler(this.btnBack_Click); + // + // pictureBox2 + // + this.pictureBox2.Image = global::RetroGOG.Properties.Resources.galaxy_logo; + this.pictureBox2.Location = new System.Drawing.Point(39, 39); + this.pictureBox2.Name = "pictureBox2"; + this.pictureBox2.Size = new System.Drawing.Size(48, 48); + this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; + this.pictureBox2.TabIndex = 12; + this.pictureBox2.TabStop = false; + // + // pictureBox1 + // + this.pictureBox1.Image = global::RetroGOG.Properties.Resources.retroarch; + this.pictureBox1.InitialImage = global::RetroGOG.Properties.Resources.retroarch; + this.pictureBox1.Location = new System.Drawing.Point(39, 93); + this.pictureBox1.Name = "pictureBox1"; + this.pictureBox1.Size = new System.Drawing.Size(48, 48); + this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; + this.pictureBox1.TabIndex = 11; + this.pictureBox1.TabStop = false; + // + // lblExplain + // + this.lblExplain.AutoSize = true; + this.lblExplain.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblExplain.Location = new System.Drawing.Point(9, 9); + this.lblExplain.Name = "lblExplain"; + this.lblExplain.Size = new System.Drawing.Size(500, 18); + this.lblExplain.TabIndex = 13; + this.lblExplain.Text = "Please wait while we look for your Retroarch and GOG Galaxy applications"; + // + // imgRetroStatus + // + this.imgRetroStatus.Location = new System.Drawing.Point(93, 100); + this.imgRetroStatus.Name = "imgRetroStatus"; + this.imgRetroStatus.Size = new System.Drawing.Size(32, 32); + this.imgRetroStatus.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; + this.imgRetroStatus.TabIndex = 14; + this.imgRetroStatus.TabStop = false; + // + // imgGOGStatus + // + this.imgGOGStatus.Location = new System.Drawing.Point(93, 46); + this.imgGOGStatus.Name = "imgGOGStatus"; + this.imgGOGStatus.Size = new System.Drawing.Size(32, 32); + this.imgGOGStatus.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; + this.imgGOGStatus.TabIndex = 15; + this.imgGOGStatus.TabStop = false; + // + // lblRetroStatus + // + this.lblRetroStatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblRetroStatus.Location = new System.Drawing.Point(131, 109); + this.lblRetroStatus.Name = "lblRetroStatus"; + this.lblRetroStatus.Size = new System.Drawing.Size(487, 23); + this.lblRetroStatus.TabIndex = 16; + // + // lblGOGStatus + // + this.lblGOGStatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblGOGStatus.Location = new System.Drawing.Point(131, 55); + this.lblGOGStatus.Name = "lblGOGStatus"; + this.lblGOGStatus.Size = new System.Drawing.Size(487, 23); + this.lblGOGStatus.TabIndex = 17; + // + // lblRetroBrowse + // + this.lblRetroBrowse.AutoSize = true; + this.lblRetroBrowse.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblRetroBrowse.Location = new System.Drawing.Point(90, 182); + this.lblRetroBrowse.Name = "lblRetroBrowse"; + this.lblRetroBrowse.Size = new System.Drawing.Size(343, 18); + this.lblRetroBrowse.TabIndex = 18; + this.lblRetroBrowse.Text = "Please enter the path to your Retroarch installation:"; + this.lblRetroBrowse.Visible = false; + // + // txtRetroPath + // + this.txtRetroPath.Enabled = false; + this.txtRetroPath.Location = new System.Drawing.Point(93, 203); + this.txtRetroPath.Name = "txtRetroPath"; + this.txtRetroPath.Size = new System.Drawing.Size(444, 20); + this.txtRetroPath.TabIndex = 19; + this.txtRetroPath.Visible = false; + // + // btnRetroBrowse + // + this.btnRetroBrowse.Location = new System.Drawing.Point(543, 200); + this.btnRetroBrowse.Name = "btnRetroBrowse"; + this.btnRetroBrowse.Size = new System.Drawing.Size(75, 23); + this.btnRetroBrowse.TabIndex = 20; + this.btnRetroBrowse.Text = "B&rowse"; + this.btnRetroBrowse.UseVisualStyleBackColor = true; + this.btnRetroBrowse.Visible = false; + this.btnRetroBrowse.Click += new System.EventHandler(this.btnRetroBrowse_Click); + // + // tmrCheck + // + this.tmrCheck.Enabled = true; + this.tmrCheck.Tick += new System.EventHandler(this.tmrCheck_Tick); + // + // btnDownloadGOG + // + this.btnDownloadGOG.Cursor = System.Windows.Forms.Cursors.Hand; + this.btnDownloadGOG.Image = global::RetroGOG.Properties.Resources.downloadgog; + this.btnDownloadGOG.Location = new System.Drawing.Point(50, 272); + this.btnDownloadGOG.Name = "btnDownloadGOG"; + this.btnDownloadGOG.Size = new System.Drawing.Size(534, 54); + this.btnDownloadGOG.TabIndex = 21; + this.btnDownloadGOG.UseVisualStyleBackColor = true; + this.btnDownloadGOG.Visible = false; + this.btnDownloadGOG.Click += new System.EventHandler(this.btnDownloadGOG_Click); + // + // frmDependencies + // + this.AcceptButton = this.btnNext; + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.CancelButton = this.btnBack; + this.ClientSize = new System.Drawing.Size(630, 378); + this.Controls.Add(this.btnDownloadGOG); + this.Controls.Add(this.btnRetroBrowse); + this.Controls.Add(this.txtRetroPath); + this.Controls.Add(this.lblRetroBrowse); + this.Controls.Add(this.lblGOGStatus); + this.Controls.Add(this.lblRetroStatus); + this.Controls.Add(this.imgGOGStatus); + this.Controls.Add(this.imgRetroStatus); + this.Controls.Add(this.lblExplain); + this.Controls.Add(this.pictureBox2); + this.Controls.Add(this.pictureBox1); + this.Controls.Add(this.btnBack); + this.Controls.Add(this.btnAbout); + this.Controls.Add(this.btnCancel); + this.Controls.Add(this.btnNext); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.Name = "frmDependencies"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "RetroGOG"; + this.Load += new System.EventHandler(this.frmDependencies_Load); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.imgRetroStatus)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.imgGOGStatus)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button btnAbout; + private System.Windows.Forms.Button btnCancel; + private System.Windows.Forms.Button btnNext; + private System.Windows.Forms.Button btnBack; + private System.Windows.Forms.PictureBox pictureBox2; + private System.Windows.Forms.PictureBox pictureBox1; + private System.Windows.Forms.Label lblExplain; + private System.Windows.Forms.PictureBox imgRetroStatus; + private System.Windows.Forms.PictureBox imgGOGStatus; + private System.Windows.Forms.Label lblRetroStatus; + private System.Windows.Forms.Label lblGOGStatus; + private System.Windows.Forms.Label lblRetroBrowse; + private System.Windows.Forms.TextBox txtRetroPath; + private System.Windows.Forms.Button btnRetroBrowse; + private System.Windows.Forms.Timer tmrCheck; + private System.Windows.Forms.Button btnDownloadGOG; + } +} \ No newline at end of file diff --git a/src/RetroGOG/frmDependencies.cs b/src/RetroGOG/frmDependencies.cs new file mode 100644 index 0000000..47015ed --- /dev/null +++ b/src/RetroGOG/frmDependencies.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.IO; + + +namespace RetroGOG +{ + public partial class frmDependencies : Form + { + public bool GOGFound = false; + public bool RAFound = false; + + public frmDependencies() + { + InitializeComponent(); + } + + private void btnAbout_Click(object sender, EventArgs e) + { + Form frmAbout = new frmAbout(); + frmAbout.Show(); + } + + private void btnBack_Click(object sender, EventArgs e) + { + this.Hide(); + Form frmMain = new frmMain(); + frmMain.Closed += (s, args) => this.Close(); + frmMain.Show(); + } + + private void btnCancel_Click(object sender, EventArgs e) + { + if (MessageBox.Show("Are you sure you want to exit the wizard? Any unsaved progress will be lost.", "RetroGOG", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes) + { + this.Close(); + } + } + + private void frmDependencies_Load(object sender, EventArgs e) + { + // Check for various dependencies and files / directories + if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\GOG Galaxy\\GalaxyClient.exe")) + { + imgGOGStatus.Image = Properties.Resources.yes; + lblGOGStatus.Text = "GOG Galaxy 2.0 is installed in the default location."; + GOGFound = true; + } + else + { + imgGOGStatus.Image = Properties.Resources.no; + lblGOGStatus.Text = "GOG Galaxy 2.0 was not found on this system."; + btnDownloadGOG.Visible = true; + } + + if (Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\GOG.com\\Galaxy\\plugins\\installed")) + { + Globals.GOGPluginPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\GOG.com\\Galaxy\\plugins\\installed"; + } + else + { + imgGOGStatus.Image = Properties.Resources.no; + lblGOGStatus.Text = "GOG Galaxy 2.0 was not found on this system."; + GOGFound = false; + } + + if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\RetroArch\\retroarch.exe")) + { + imgRetroStatus.Image = Properties.Resources.yes; + lblRetroStatus.Text = "Retroarch found in the default location."; + Globals.RAPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\RetroArch\\retroarch.exe"; + RAFound = true; + } + else + { + imgRetroStatus.Image = Properties.Resources.warn; + lblRetroStatus.Text = "Retroarch not found in the default location."; + lblRetroBrowse.Visible = true; + txtRetroPath.Visible = true; + btnRetroBrowse.Visible = true; + } + } + + private void tmrCheck_Tick(object sender, EventArgs e) + { + if (GOGFound == true && RAFound == true) + { + btnNext.Enabled = true; + } + } + + private void btnRetroBrowse_Click(object sender, EventArgs e) + { + OpenFileDialog browser = new OpenFileDialog(); + browser.Title = "Please select your retroarch.exe file"; + browser.InitialDirectory = @"c:\"; + browser.Filter = "Retroarch Application|retroarch.exe"; + browser.FilterIndex = 2; + browser.RestoreDirectory = true; + if (browser.ShowDialog() == DialogResult.OK) + { + txtRetroPath.Text = browser.FileName; + imgRetroStatus.Image = Properties.Resources.yes; + lblRetroStatus.Text = "Retroarch location has been entered by user."; + Globals.RAPath = txtRetroPath.Text; + RAFound = true; + } + } + + private void btnNext_Click(object sender, EventArgs e) + { + this.Hide(); + Form frmPluginSelect = new frmPluginSelect(); + frmPluginSelect.Closed += (s, args) => this.Close(); + frmPluginSelect.Show(); + } + + private void btnDownloadGOG_Click(object sender, EventArgs e) + { + System.Diagnostics.Process.Start("https://www.gog.com/galaxy"); + } + } +} diff --git a/src/RetroGOG/frmDependencies.resx b/src/RetroGOG/frmDependencies.resx new file mode 100644 index 0000000..1678609 --- /dev/null +++ b/src/RetroGOG/frmDependencies.resx @@ -0,0 +1,1895 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + + 17, 17 + + + + + AAABAAYAAAAAAAEAIADdFwAAZgAAAICAAAABACAAKAgBAEMYAABAQAAAAQAgAChCAABrIAEAMDAAAAEA + IACoJQAAk2IBACAgAAABACAAqBAAADuIAQAQEAAAAQAgAGgEAADjmAEAiVBORw0KGgoAAAANSUhEUgAA + AQAAAAEACAQAAAD2e2DtAAAXpElEQVR42u2deYAUxb3HPzOzB7ssuxzLfQmIXBpFWSCiiIhBIhoFTEzU + FzXmqVEQiOgDESV4LA/QKGh8JmqMmngkwovhKYgcigcgdxS5WZBjuZY92JOZeX8sM8zudPX0Od1L12f+ + 6a7q6vlV9ber6y6QSCQSiUQikUgk3sKn7PwCG5sfG3pyWOpgeh2nirDTdkoMkE4O2ceKFmYszV1y7oHJ + ig9RQQBz2Nj34PiTI6uaOx0BiVWkVTb6uNXcgUsnBOv7xAng7k4780tHnUp32mSJ1fiDWcvbP/Tmurqu + gdiTfF/2LTv/eTIvlOK0sRLrCfuruhbffhHDPl8T8zGIyQEmpG7LL5wQ9um/taQh0Wx+jzteKI6cRR/3 + A6lbXz76y7qPP5VudKcdmUhVNEQqOMx2tlNRzz17aZ/R807UHp9+sjN9nz5T+EDs48/lJobTtu43QtLg + CFHEMv5GQR3Xph/0HPXCKYiWAXJu2z/zzONP5VZmMoBs/E7bLzGJj0x6M5pmbKQm6lrZI5h29yeLOS2A + X5+zc0EwI+LZjHzGkOq05RIL8XM+g1jLiahLxYDyFd8UgB/msPvp6mYRj2b8nh86ba/EBs5jLl2iZ8HU + wjnTG0EAWvc7ODt0+lOQSj4XO22pxCaakMciqk6f1bQ9+e+t3/h/z6Fxp9Iil/xCvv1nNV2YGD0O+4on + PJbi/7bFyZERp1zudNpCic2M4ILocXleQR//0aFV0e//TTR22j6JzQS4LXoc9B+6wV9+deQ0jeFOWydJ + AgNpFT2uGOJPuyJy0oW2TtsmSQKZXHjmJM8fOi9yfK5s9fMIPaNHJxv7i6In7Zy2S5IkzuT0YfxV0ZNM + p+2SJInYJ+0/0zUs2/29gl9wLPEgUgAeRwrA40gBeBwpAI8jBeBxpAA8jhSAx5EC8DhSAB5HCsDjSAF4 + HCkAjyMF4HGkADyOFIDHkQLwOFIAHkcKwONIAXgcKQCPIwXgcSxaEO4YK/mWw1QS0vSnAdJpTDYtaEd3 + 2iKXJXQKCwRQzWv8lZMm7tCK/vyYvq5ZluYkRUAujZw2JAmYFkCYOfzD5D0O8y8W0oM7uNLxb9JJXmYx + x/DRhhv5BWnmb+lqTKf3Ot63xJAw3zGZSRSZv5UJyhnHWxwhRJD9zOOhmJW1zk5MC2C+hSuJh1jB7exw + MDneY2Od85XMd9CaZGBaABssNmg/D7DLmbQgzNI4t+UO2ZIsTAqgyoYsu5AplDmSGJUcjXPb64glycO0 + AOzYSmIHLzqSGNVUxrmdJGjgTg0HpwvdAuY78hkIKrRihDjldGLYim07A6TTUcE1SDUVlCYsW9fwNlOS + nhhhxWYsLU1bDRfbBNCJNxTdQwSp4Qjf8AEbVD4gyxlHltOp4wFsE4BP5dYZZNON6/iAWXFr2Uco4lv6 + O506HsDBMoCP63lQaECYb50zzUM4vDvQSBawWeD3vea7lLGTPRzkBOWESKUxLehAVzonLXrlrGATZWTR + iytpEuOznzXs4gSQTQd60Vtzj0cx2ymgkBNUEiKVJuTSnq50tvStdVgAAa4UCqA4Yegw+1nCp2ylWqE0 + 4SeHPH7EQNs7ddYzjYPRsxf4HQMAKGAuK+vUInw042rGcI7KJjwhdvMxK9nJKYVYBcghj6FcSgZW4Pj+ + YOLVSdVL3yE28he+VKmkhShiMYtpx83coLoIXhmLWcsxxXaASsaeXkCzET0YSae4K77nt5TEnB9jMq/R + mc+ZFifiMMd5h/cZxb2KRdxTfMVbrFWJe5DjLGIRLbmBMbQwnf6OC0BcIVRT+CHm8onGGvoBnmEBExko + 8D/K/Sr9D8GYxu7P+TuzuKTeFX+s8/gBSniTq3hYQU6ROL/DDubESWAHz7JGY7XzCH/kfX7FKJOP0PGG + oN1Cn5ZCny+4nUW6Gmh2MYF5ghCv6Oh+KuG5eg+olM8VrlvCZOHjr2Utr9Y5D/MP7mSVrlaHY8xigkLz + tR4cFkA5Hwv9uim6hplvKNI1/JkpVCn4bNV1nwP1+in2KpZVSilNeKcPKY+xbjb5MedaCfMld7Jdd7gz + OCqAKuYIy/pp9FF0/xczDbfOL+VxhU+OvjWSc+p9mgoN94YcjeYRIebwjuH7HGCsiYZzxwQQ4it+wz+F + /l3prOC6gVmm2uaX1Mt4AX6po8UxlbvqVeMqNYetT2b06/2myTFVR3mQYwbD2lYIrOFAnNspqinhGPvZ + xkYOq2p+jII2y5iumk0GSAGCKhIJ8zoDuKiOW3de5XXWU0yYijibfGTgw08WbbmAa+laz994T0Hf0+0F + G3jJdJ/qXp4m39DDtE0Au7neROhu/FjB9TX2Ca7305eR9KY5PorZyTKWCd7Nap7n5XrR7sp0AI4xKm5w + ayYfWVTjrktTfoMPqGAW1cKrMriIvrQlQDE7WM33QqmsYLFimiXC8WqgEulMVhiMWcjfBdfn8BDDottd + NKUzQ9nK7wTFu018yeVJikmAwQyhNVXsYzMbKDztfi5Tqd2p40NhIdTHcH5Np5gmo0qW8xxHFK8O8z8M + MbDkvwsFEGBSvUy6lvcFQ88zmE3fONcezOU+Qfn43SQJIIXJXBf9lN1MJbvZSAXn0e/0TIhq/ioI62Ms + t9b7DDbiGn7AeEGRbz+LuFG3jY63A9Qnk2ncoOBeyYeCEHcrPH6A5kwVDOr+msNJicsoflIngRvRi5u5 + g0HRiTBr2CMIezO3KT6cdjxLriDMewbKEi4TwHn8gWsVfb6JaW2PpRWjhXfrI9gGs4avkxCXjJgN2kQs + Fri349fC3oL23CPw22GgOugiAbTit7wiqP3DKoG6h6kW0X4kcE9GV/OFCXdhC/GlwGcM2SrhRtBe5/3E + uEIAafTlMf7Bz4UPM8wmgU9/Qiq/CwWhRLUJKxmY8IoCwZjqRgxTDZcu9F+v20oXFAKb8t8JN6yuFD6y + 5/iDSrgwPsWcI3FXs3kuSHjFDkGu1ilh6+QA/iy4Y0jnO+0CAZzgUWYkkEAlxwU+uzGCHYPZ69M14RWi + ZvCeCUP2ELiXUEJTXVbaJoBzmA2EqaGYfWxihUr3SCHjeYLBKncrsXiOXnO7oh2liYYGZlGXVuLeiSY0 + VqwUV1HqFgGkcU70OI9RlPIKbwsbacv5L/JVJGBm8rkSibNns+RquEbUrJ2jIWy2YpoEFfs71UhaIbAJ + 45mh0lJVzWOsE/paOzsnIwnbZGerDPpKFCstb6XyNSHdfRNJrQVczXSV+falPCIs6lm5dESABwTVKCtp + rOEaUayqNYRVvsave//nJFcDr2SsyptxhIcF2aJVU0TSyWOuStORdWgZiNpE4H5cQ9gTiq6pujuukl4L + +Bnf8JHQdxuzeFRBlU1opNi7F2CIhjU8fKTQmFzOobfKQDNr0bKySCuBe+JWisOCb326agOSEkkXgJ9J + bGa/0H8h/RkR59qIXMVKU4jfKA4ccR4tCdtJ4L6FYIKs/BuBe67uvNKBlsAc/ksleiGe5VCca7rgMYfZ + ovFfj/O/vMRrfO2iyZ49BZ/DgwmHqa4U3lEvjjQFD1Ts74twnGcUHtJFgquXamrUWcIoZvAnXuAe7hL0 + qIuwr9EoN6aqHMsplaFyAMeE65bk6bbBEQH4uEe1sWMZn8W5DRTkGp8JO1QjBHmDqTFjeTcxQ2hX/BsZ + tnWBCFHLx0IKhGHC/CVuJkItaYLeTzUc6gxqxgSV2kCY5+IKOd0FTas1zFEdJlrB08ytd8VqhY9MbWLE + J0dId9OKHq4RyLqMp4T/u5L3BD79DcwUcqw3cIhqj9feuHGyKcLPxirmCt/SPdzDgrgPSkgwhjZVoexe + Y3i8rRa6CafAr2WyQuN5mBVMFbQB+LjZgAWOCcDHRFW9vhmXzY2kteKVYf7Ko9HRdmco4VX+Q7G8HBA0 + 1KYp1KKDijN/rMLPHcL6wqfcxsKYVKhhOzOYJGwWv9hACcDR3sCW3M/vhEWswyzk53VcGnMvjyteG2Yx + qxjOFXQmixClfM8XLFEQRS29BFJKpblCHfwN2nMpGZRxmAIOEGAQXSxLhb4MZ6HA73seoxndaEMKxexh + n8rHLp37dLcCgsPdwSNYovJ+zWd0vSx5BJ8oFA9rKeZd3iOdVMLUKE4XP8OdQp8u9RaKBChlKlmkUEPF + 6U/NSzzG1RalgY8HWK8whyJCkcbha7cY7OAy+QlI3OGhRgqTVFqudsWNAgrwqKDiVEuYSkopS7B43TVc + KvT7geC+pRRRFi1pVDIzOqRElALaU6Y5T2vqOVDjcpUxhOqYFECmMNtpoil8B+5V8Y0f4dacWQlH2qlz + AZNUIj1A48j64uinQrTQvZ5FKfrwpCkJXMwMw91lJgUQEDZnam2gHUU/oZ/SgIkuzFPNBdS5mNmqve2t + uU7TfVKiAm8jePP0TTm9jNmGF3u4gtkmOstM1wKUs1Of5iaJAI8IH4nyBPHO/IlhBgwPcBNzEybzfcJx + yXVjHRF+F8U7+lRkrUwer3CR7mw8jXvI190BFItpAYxWzOzPZZDmO3TkYcUMrIVCp1AtTXmap3WVxH30 + YS4PadiZJJPnuVq1PB1gKNOjj6oxP1G4Jo/uulIRoAMvMUnYQ6hkRx6vxs1W1kug3eORwx8KikDqZNGG + lfUaYlowU1DRUqYrzVhd7x6ZPE5vYQgfXbmeThRxNGFbfToDmMB9dWbZqdGIoVxIDSVxaxim0IGhjOfW + OkI6nw31Whbb8qShUYd++nAtzTmUcNRyOpfxIHfpkEss+2JmWfkuiabfBG4xdLswa3ie706fBbicBxSX + iVVnHb+PTtfw0Y9x9NIQKsj3fM5atnBEQQgt6cNABtHaUEZXzhEOUEQVtd/8FrQhR7Gfv4wXWXC6fc7P + YCbqLAHUp4otfMY6tik0B7fhfPpzKa1N1MC+YFz02AIBAIQpYCfl5NBb03BI5XvsZQflZNOTVjqjF6aU + AxyjjGrCpJFFC9ppGpdnFcVspogm9Db4VipxioPRdQJr49SeJhbEKVYAFjUE+TjHRNk8co/Ohgd3+Mg2 + VRQyTw6XWX7PFDoayEv14YqpYRLnkALwOFIAHkcKwONIAXgcKQCPIwXgcaQAPI4UgMeRAvA4UgAeRwrA + 40gBeBwpAI8jBeBxpAA8jhSAx5EC8DhSAB5HCsDjSAF4HCkAjyMF4HGkADyOLSuEhCxcWi1gWqOnLFvp + z2c6udyVMmCxAGpYxWds4aiF0fTTnPO4jEG6llwA2M9S1lKgsB2sUXyk04m+DNU9C6qGL1nJd5anTE8u + 41INc55V4mTN3EAI8jEvs8+2dTVbcjujNE+FLmQeSyzeZeQMAS7nfs0iOMVi/qiy6atZWnMHN+h6k2Pn + BlpUBijjEaay18ZlVY8wi3GaFnkNs5xb+dC2xw9BlnM7H2iKbQmTmWbjiwGF5DPR8GqGlgiglIkssS2C + Z1jDWA17fn7EI4Lt2KykjCd4O+FVJUxgWRJS5gvGCXcgUscCAQR5SmWzF2vZwdQES7du5glbF3eNjfdz + CRaRPMUMhWXn7GEr0wzleRYIYFFS3v4I6/ibim9V0h4/wCnyBTt31LJQuKq3HazmXQOhTAugmleSsgvf + GURrZQN8aGD3XDMcjFvT+AwVvJbklHndwO5qpgXwtcrC5vZQwscCnxALkpzksFCY46wSbgxpF8dZqjuM + aQF8muRIqv3nQbYn3ZZ9wr1L3ZQyYkwLQOuWLVayVbDty64kfv8jhKPLY9XHTSkjxrQA9G2/Yg0VMft/ + OG0LwoqpE9acFO5GKsK0AJL/zkFIUOFxwhbxvzphTVB3VdC0AJJd6FL7VzfZ0lCQ3cEex/YNI7IYyrk6 + /ibIXj7RtHmqEfowSNf26qWsYr1N73gWV9FNV8oUsES14ckINgugFzMNLJt6N1P5ynJbUhjPT3VneXew + iCcVt601R29mGtj54G6msMZSO2z9BGQYevzQlKcsXHA1whh+ZiC6fkbwS8ttySLf0MYXzSxPGVsFMMTw + osnZXGuxLamMNrzK7k90D0ZJhPGUaSZcRN8Ytgqgm0Nhlcg28ea00rgBjna6mghrbcrYKgAzWxmY2wZB + KaJmomq1Ne5JGVkN9DhSAB5HCsDjSAF4HCkAjyMF4HGkADyOFIDHkQLwOFIAHkcKwONIAXgcKQCPIwXg + caQAPI4UgMeRAvA4UgAeRwrA40gBeBxbBVDtdOxiCJpaoc/qmNi3gplebBVA8pdrEFNKoeGwhyi12Br3 + pIytAviUfU7HL0oN7xqe4/e+5VO9V7gmZWwVQCWTkr6CkJj5vGHgMxBkAW9abks5D7PX6QQBbJ8cuoPb + GEw3DZMZbrZ9onKI5/mIQTTXPEUsTAlfsdkWa7ZxK1domh18i+EpbVqwfXp4OR9puMrHaPtNAbaxLQn/ + oo1yPtRwlZ9f2CoAWQ30OKYFYKc6G4YtbkoB/ZgWgJm16q3GGVvSdbq7C9MCsH4hh4ZmSyud7u7CtAB6 + Ox2DGLpavpBDYnzCFHBTyogxLYDBTscghjacl/T/7ExngY+bUkaMaQFcTBen4xATmRuTXiS7Tvit708n + pxNEA6YFkMZ/uqgcPJzuSf2/9two9GvEr1yUMiIsaAe4ih87HYsoaUwjI2n/lsoUslX8r+FqpxMkIRYI + wM/DDHA6HlF68liSJJDCgwniHWAKlzidIAmwpCUwk1mMdE12N4yZ5Nr+LzlMZ1TCq7J4hmtckzJKWNQU + nMk0ZtHdJVG9lLcYZWM+kMo1vM5wTbFtzHTy6eaSlInHsh4YP0O4nPV8xncc1j2CxmdxArVgCnexnHXs + oczCnUMb05G+DKG9jlABrmIIa1nJdxzWPRbIbuFY2gUXoB/9AAjpTvSA5VFrxU/5KRDWvYuGCL/hxxGg + P/0Npoy9/XU29cG6qZPRZ4O4jOOmlHGjPZIkIwXgcaQAPI4UgMeRAvA4rhVAhdMGuBZrU8a1Avi30wa4 + FmuHqbtUAAUsdNoEl7KLRZbez4UCCLOJCfIToECIDUzUvTmsOqZbAmdbvKVaDXvZ6qp5xUaZafEc4BoK + 2Gr5vGLTAvg/Siw26WzhXw0iF3PhJ0CSTBqoANzau+40+tOlQQrA30Bm3SSfgO6UaZACyCHLaRNcSlMy + dYZokAK4wGkDXIv+lGmQArjSaQNcio8husM0QAG0ayCTrpJPRwbpDtPgBODnPtKcNsKV+BlroFmnwQng + WoY5bYJLuZErDIRqYAIYzCRXDfF0D1cx3tDDTMbKTBaRws+43/KN3M8GUrmFuw2mTAMRQBqX8CsuctoM + F5JOP+4yUTE2LYA8i7sn4w3MpQd5dGxoXyv629ynmUouPelHB1MpY1oAM22NZENmjtMGaKKhvVYSi5EC + 8DhSAB5HCsDjSAF4HCkAjyMF4HGkADyOFIDHkQLwOFIAHkcKwONIAXgcKQCPIwXgcaQAPI7/zHRCq1bU + lbid2CftPzOUsCHMZpdYQeySHv6c6OFhp+2SJInCmGN/06LI4Q7LVtWWuJvt0aPMKv/x6HJcOznutGWS + JFDFxuixf6O/0dLISTnLnLZNkgQ2szd6nPGZv9XitGjp7x3L16CSuI0wb0WP/eHmC/y9D2QsiTjsYb7T + 9klsZjWfR48ztrZf458YbjnXH4w4vRhTQJCcfRznqZiifva8WVV+GLg0a3nEqYzJHHLaSolNlDGV/dGz + zJ3d3wQ/TAh2eCilKuK8h3HscdpSiQ0c52FWR898oZaTny0+vVnXpoMX+0ujC+8UsYiWLt7pTmKENTzI + lpjz5n+78snF4ehubUNWVl5Y2TPiWcUyVtOU1nI2/llANRuZxUsUx7g12ThwzKOVELO05Nicf88vqbf8 + Vmv60ou2NJarcjRAQlRQyDbWs7deR1/mtq4/er2g9jgmn7+/2Za/nBjptNkSu2myseMNb+yJnMW82qsr + R/w9mFLxw7AcI3DW4gu1eDvvphdjKnp18vY1obs+qVxRfUFNW1kCPBvJ2NX+3qFPPFqn31/hQU9rtOH6 + kt+W9wvKnOCswUfm1ux53d94tjjeR5HHU3afX3hjxRDyyuzbhV2SBDJqAhszPm02v/3Xs63d2kUikUgk + EolEIpFIJA2R/wdOE2BbbcdkRgAAAABJRU5ErkJggigAAACAAAAAAAEAAAEAIAAAAAAAAAABABMLAAAT + CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAICAgAFPT08sPz8/bjMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4A+Pj5xTU1NMnR0dAIA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAImJiQBHR0dEOTk5xzQ0NP4zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk50UVFRVGOjo4AAAAAAAAAAAAAAAAAAAAAAAAAAABs + bGwEPj4+jzQ0NP4zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/z4+PqFdXV0IAAAAAAAAAAAAAAAAZmZmAT09PZ8zMzP/MzMz/zMzM/9iYmL/r6+v/9jY2P/k + 5OT/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5OTk/9ra2v+zs7P/aWlp/zMzM/8zMzP/MzMz/zw8PLJ6enoEAAAAAAAAAABC + QkJqMzMz/zMzM/88PDz/tbW1//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////wcHB/0FBQf8zMzP/MzMz/z8/P34AAAAAWlpaEjY2Nu4zMzP/NjY2/8XFxf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////0tLS/zo6Ov8zMzP/NTU19lFRUR8/ + Pz9xMzMz/zMzM/+Kior///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////m5ub/zMzM/8zMzP/Pj4+hjo6OsAzMzP/NTU1/+Xl5f////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////w8PD/Ozs7/zMzM/85 + OTnVQUFB+zMzM/9TU1P///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////9jY2P/MzMz/zY2Nv01NTX/MzMz/2lpaf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////3p6ev8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ////////////////////////////////////uLi4/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1 + tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1 + tbX/vb29/+Li4v////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////9zc3P+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1 + tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7e3t//MzMz/9/f3//////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////86 + Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NTU1/2lpaf/h4eH///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9DQ0P/p6en//7+/v////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + /////////////////////////////////////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0NDQ//c3Nz///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/iYmJ//////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + ////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/1tbW//+ + /v7///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////52dnf8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/wsLC//////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/83Nzf////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9qamr/////////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/n5+f//////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////+dnZ3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/z8/P//8/Pz///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/OTk5//f39////////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////9hYWH/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9b + W1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1FRUf80NDT/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5SUlP////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////sLCw/1tbW/9b + W1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9b + W1v/W1tb/1tbW/9aWlr/Pz8//zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////8DAwP81NTX/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////z8/P/Z2dn/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////2hoaP8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+UlJT///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////Nzc3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////9zc3P8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////94eHj/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/lJSU//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/2 + 9vb///////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////c + 3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + ///////////////////////////////////////////////x8fH/vLy8/6Wlpf+jo6P/o6Oj/6Ojo/+j + o6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo//9/f3/////////////////eHh4/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5SUlP////////////////////////////////////////////r6+v/I + yMj/qKio/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+j + o6P/o6Oj/6Ojo/+jo6P/o6Oj/6enp//FxcX/+Pj4//////////////////////////////////////// + /////////////////////v7+/9XV1f+tra3/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+j + o6P/o6Oj/6Ojo/+jo6P/0dHR/////////////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85 + OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v////////////////////////////////////////////////////////////////////////////9 + /f3/nJyc/z09Pf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/NDQ0//v7+/////////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////// + //////////////////////////////++vr7/SkpK/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9G + Rkb/t7e3/////////////////////////////////////////////////9vb2/9eXl7/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+ZmZn///////////// + ////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + /////////////////////////////////////v7+/4SEhP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/80NDT/+/v7/////////////////3h4eP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT/////////////////////////////////s7Oz/zU1Nf8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/80NDT/q6ur//////////////////////// + ///////////////a2tr/QEBA/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5mZmf/////////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/OTk5//b29v///////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr///////////////////////////////////////////////////////////////////////C + wsL/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zQ0NP/7+/v/////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP// + /////////////////////////+rq6v89PT3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/86Ojr/5OTk/////////////////////////////f39/1tbW/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/mZmZ//////// + /////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + /////////////////////////////////////////25ubv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NDQ0//v7+/////////////////94 + eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU////////////////////////////oKCg/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+Wlpb///////////// + ///////////////Q0ND/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+ZmZn/////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zk5Of/29vb///////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + ////RERE/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/80NDT/+/v7/////////////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+U + lJT///////////////////////////92dnb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2xsbP///////////////////////////6enp/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5mZmf// + ///////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP/7+/v///////////// + ////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP///////////////////////////2xsbP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////// + ////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/mZmZ/////////////////9zc3P8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/85OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/R0dH/2pqav9ra2v/a2tr/2tra/9r + a2v/a2tr/2tra/9ra2v/a2tr//z8/P////////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/lJSU////////////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/89 + PT3/aGho/21tbf9tbW3/bW1t/21tbf9tbW3/bW1t/21tbf9tbW3/bW1t/21tbf9paWn/Pj4+/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////////////////////+dnZ3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zY2Nv9gYGD/a2tr/2tra/9ra2v/a2tr/2tra/9ra2v/a2tr/2tra/+1 + tbX/////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/2pqav/39/f///////////////////////////////////////////////////////////// + /////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////9s + bGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/SEhI/+bm5v////////////////////////////////// + ///////////////////////////////q6ur/TU1N/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv// + /////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/82Njb/x8fH//////// + ///////////////////////////////////////////////////////////////c3Nz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/OTk5//b29v///////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/xcXF//////////////////////// + ////////////////////////////////////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5SUlP///////////////////////////2xsbP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+T + k5P///////////////////////////////////////////////////////////////////////////+a + mpr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi////////////////////////////nZ2d/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2FhYf////////////////////////////////////////////////// + /////////////////////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + /////////////////////////////////////////////////////////zo6Ov8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM//R0dH///////////////////////////////////////////////////////////// + //////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////////////////////// + ////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5+fn/////////////////////////////////// + /////////////////////////////////////////6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9i + YmL///////////////////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//////// + ////////////////////////////////////////////////////////////////////3Nzc/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + ////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9HR0f////////////////// + /////////////////////////////////////////////////////////3h4eP8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+UlJT///////////////////////////9sbGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/n5+f//////////////////////////////////////////////////////////////////////// + ////pqam/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv///////////////////////////52dnf8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9tbW3///////////////////////////////////////////// + ///////////////////////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////86Ojr/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/0dHR//////////////////////////////////////////////////////// + ////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP////////////////// + /////////2xsbP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+fn5////////////////////////////// + //////////////////////////////////////////////+mpqb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/YmJi////////////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/21tbf// + /////////////////////////////////////////////////////////////////////////9zc3P8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + /////////////////////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//R0dH///////////// + //////////////////////////////////////////////////////////////94eHj/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/lJSU////////////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5+fn/////////////////////////////////////////////////////////////////// + /////////6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////////////////////+d + nZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//////////////////////////////////////// + ////////////////////////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/2 + 9vb///////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ////////////////////////////////////////////////////////////////////Ojo6/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/9HR0f////////////////////////////////////////////////// + /////////////////////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////// + //////////////9sbGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/n5+f//////////////////////// + ////////////////////////////////////////////////////pqam/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/2JiYv///////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9t + bW3////////////////////////////////////////////////////////////////////////////c + 3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/0dHR//////// + ////////////////////////////////////////////////////////////////////eHh4/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5SUlP///////////////////////////2xsbP8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+fn5////////////////////////////////////////////////////////////// + //////////////+mpqb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////////////////////// + ////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/21tbf////////////////////////////////// + /////////////////////////////////////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85 + OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v//////////////////////////////////////////////////////////////////////zo6Ov8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM//R0dH///////////////////////////////////////////// + //////////////////////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////// + ////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5+fn/////////////////// + /////////////////////////////////////////////////////////6ampv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9iYmL///////////////////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/bW1t//////////////////////////////////////////////////////////////////////// + ////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9HR0f// + /////////////////////////////////////////////////////////////////////////3h4eP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////9sbGz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/n5+f//////////////////////////////////////////////////////// + ////////////////////pqam/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv////////////////// + /////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9tbW3///////////////////////////// + ///////////////////////////////////////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/OTk5//b29v///////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////86 + Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/0dHR//////////////////////////////////////// + ////////////////////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP// + /////////////////////////2xsbP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+fn5////////////// + //////////////////////////////////////////////////////////////+mpqb/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/YmJi////////////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/21tbf////////////////////////////////////////////////////////////////// + /////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + /////////////////////////////////////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//R + 0dH///////////////////////////////////////////////////////////////////////////94 + eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU////////////////////////////bGxs/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5+fn/////////////////////////////////////////////////// + /////////////////////////6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////// + //////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//////////////////////// + ////////////////////////////////////////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zk5Of/29vb///////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + ////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9DQ0P////////////////////////////////// + /////////////////////////////////////////3Z2dv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+U + lJT///////////////////////////9sbGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/np6e//////// + ////////////////////////////////////////////////////////////////////paWl/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2JiYv///////////////////////////52dnf8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + ///////////////b29v/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/p6en///////////////////////////////////////////////////////////////////////8 + /Pz/UVFR/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP///////////////////////////2xsbP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/91dXX///////////////////////////////////////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////// + ////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/0lJSf/5+fn///////////// + /////////////////////////////////////////////////////////7Kysv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/85OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/89PT3/qamp/9PT0//U1NT/1NTU/9TU1P/U + 1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/U1NT/y8vL/3R0dP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/lJSU////////////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP+N + jY3/0NDQ/9TU1P/U1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/R0dH/k5OT/zU1Nf8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////////////////////+dnZ3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/21tbf/Jycn/1NTU/9TU1P/U1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/U + 1NT/1NTU/9PT0/+urq7/QEBA/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////9s + bGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv// + /////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/OTk5//b29v///////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////88PDz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5aWlv///////////////////////////25ubv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/ZGRk////////////////////////////n5+f/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/86Ojr/+Pj4//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + /////////////////////////////////////////////////////////1NTU/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys//////////////////////// + ////hYWF/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/97 + e3v///////////////////////////+2trb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0pKSv////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + ////////////////////kJCQ/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zY2Nv/n5+f////////////////////////////CwsL/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/7m5uf///////////////////////////+3t7f86 + Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/h4eH//////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + ///////////////////////////////////////////////////////////////s7Oz/RUVF/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/jIyM//////////////////////// + //////////39/f9lZWX/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9e + Xl7/+/v7/////////////////////////////////5WVlf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0FBQf/n5+f///////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + ///////////////////////////////S0tL/RERE/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/3d3d//5+fn//////////////////////////////////////+3t7f9cXFz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/V1dX/+np6f////////////////////////////////// + /////Pz8/39/f/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9CQkL/zMzM//////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ///////////////////////////////////////////////////////////////////////////////s + 7Oz/kJCQ/1JSUv89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89 + PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/QkJC/2lpaf+6urr//v7+//////////////////////// + //////////////////////////n5+f+mpqb/Xl5e/z8/P/89PT3/PT09/z09Pf89PT3/PT09/z09Pf89 + PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf8/Pz//XFxc/6Kiov/3 + 9/f//////////////////////////////////////////////////v7+/7+/v/9ra2v/Q0ND/z09Pf89 + PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89 + PT3/PT09/z09Pf9RUVH/jY2N/+np6f////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////////////////////////////////39/f/8/Pz//Pz8//z8/P/8 + /Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/+ + /v7///////////////////////////////////////////////////////////////////////////// + /////v7+//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8 + /Pz//Pz8//z8/P/8/Pz//Pz8//7+/v////////////////////////////////////////////////// + /////////////////////////////////////Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8 + /Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//f39//////////////////////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + ///////////////////////////////IyMj/gICA/3Z2dv+lpaX/+Pj4//////////////////////// + /////////////////////////////////////////8rKyv+BgYH/dnZ2/6Ghof/19fX///////////// + ///////////////////////////////+/v7/4eHh/66urv+MjIz/eXl5/3Jycv94eHj/i4uL/66urv/k + 5OT///////////////////////////////////////////////////////////////////////z8/P/p + 6en/2NjY/9jY2P/k5OT/+Pj4////////////////////////////3t7e/4iIiP92dnb/pKSk//j4+P// + ///////////////////////////////////////////////////////////////////////////////x + 8fH/vLy8/5OTk/97e3v/c3Nz/3h4eP+Li4v/sLCw/+Xl5f////////////////////////////////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ////////////////////////////////////////////////////////////////////t7e3/zU1Nf8z + MzP/MzMz/zMzM/9qamr//v7+//////////////////////////////////////////////////////+n + p6f/NTU1/zMzM/8zMzP/MzMz/15eXv/6+vr/////////////////////////////////wcHB/19fX/80 + NDT/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zU1Nf9lZWX/yMjI//////////////////////// + //////////////////////////v7+/+dnZ3/SUlJ/zMzM/8zMzP/MzMz/zMzM/88PDz/b29v/9nZ2f// + /////////+Li4v8/Pz//MzMz/zMzM/8zMzP/cnJy//7+/v////////////////////////////////// + ///////////////////////////////o6Oj/hISE/zs7O/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/NTU1/2lpaf/Pz8////////////////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////9VVVX/MzMz/zMzM/8zMzP/MzMz/zMzM//Q0ND///////////// + ////////////////////////////////////0dHR/zc3N/8zMzP/MzMz/zMzM/8zMzP/MzMz/8fHx/// + ////////////////////9/f3/3t7e/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/80NDT/hoaG//r6+v//////////////////////////////////////hISE/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/RERE//f39///////kZGR/zMzM/8zMzP/MzMz/zMzM/8z + MzP/3d3d////////////////////////////////////////////////////////////vLy8/z8/P/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP+Pj4///Pz8//////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v/////////////////////////////////////////////////////////////////+/v7/zc3N/8z + MzP/MzMz/zMzM/8zMzP/MzMz/6+vr/////////////////////////////////////////////j4+P9U + VFT/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/19fX//////////////////r6+v9sbGz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/f39///////// + /////////////////////////+bm5v82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/83 + Nzf/8PDw//////91dXX/MzMz/zMzM/8zMzP/MzMz/zMzM//CwsL///////////////////////////// + /////////////////////////7W1tf82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9/f3///v7+//////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ///////////////////////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys//////// + ////////////////////////////////////lJSU/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/1hYWP/9 + /f3/////////////////lJSU/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/0xMTP+Hh4f/mZmZ/4eHh/9Q + UFD/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/yMjI////////////////////////////ubm5/zMzM/8z + MzP/MzMz/zMzM/82Njb/iIiI/5ubm/9/f3//ampq/7W1tf///////////3Nzc/8zMzP/MzMz/zMzM/8z + MzP/MzMz/7+/v//////////////////////////////////////////////////a2tr/OTk5/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0RERP9aWlr/S0tL/zQ0NP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+o + qKj//////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////j4+P82 + Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+srKz//////////////////////////////////////9jY2P84 + ODj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/t7e3/////////////////+bm5v85OTn/MzMz/zMzM/8z + MzP/MzMz/zMzM/+Ojo7/+fn5//////////////////z8/P+urq7/Pj4+/zMzM/8zMzP/MzMz/zMzM/+K + ior///////////////////////////+hoaH/MzMz/zMzM/8zMzP/MzMz/3d3d/////////////////// + ////////////////////c3Nz/zMzM/8zMzP/MzMz/zMzM/8zMzP/v7+///////////////////////// + /////////////////////v7+/2lpaf8zMzP/MzMz/zMzM/8zMzP/MzMz/0JCQv+9vb3/+/v7///////+ + /v7/1tbW/1lZWf8zMzP/MzMz/zMzM/8zMzP/MzMz/0BAQP/w8PD///////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + ////////////////////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/6ysrP// + ///////////////////////////////7+/v/XV1d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/15eXv/9 + /f3/////////////////l5eX/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//7+/v////////////////// + ///////////////d3d3/UFBQ/zMzM/8zMzP/MzMz/6Ojo////////////////////////////5eXl/8z + MzP/MzMz/zMzM/8zMzP/lZWV//////////////////////////////////////9zc3P/MzMz/zMzM/8z + MzP/MzMz/zMzM/+/v7/////////////////////////////////////////////b29v/NDQ0/zMzM/8z + MzP/MzMz/zMzM/82Njb/z8/P////////////////////////////8PDw/0tLS/8zMzP/MzMz/zMzM/8z + MzP/MzMz/6Wlpf////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra//////////////////////////////////////////////////////////////////4 + +Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys/////////////////////////////////6CgoP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/84ODj/1tbW//////////////////////9cXFz/MzMz/zMzM/8z + MzP/MzMz/zMzM//Kysr////////////////////////////////////////////u7u7/hISE/2dnZ/+X + l5f/+vr6////////////////////////////lZWV/zMzM/8zMzP/MzMz/zMzM/+ampr///////////// + /////////////////////////3Nzc/8zMzP/MzMz/zMzM/8zMzP/MzMz/7+/v/////////////////// + /////////////////////////5ycnP8zMzP/MzMz/zMzM/8zMzP/MzMz/3Nzc/////////////////// + ////////////////////q6ur/zMzM/8zMzP/MzMz/zMzM/8zMzP/ZmZm//////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////j4+P82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+s + rKz////////////////////////////a2tr/Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5qamv// + ////////////////////+fn5/zw8PP8zMzP/MzMz/zMzM/8zMzP/NDQ0/7S0tP++vr7/vr6+/76+vv++ + vr7/vr6+/76+vv++vr7/vr6+/7+/v//Ly8v/6urq//////////////////////////////////////+V + lZX/MzMz/zMzM/8zMzP/MzMz/5qamv//////////////////////////////////////c3Nz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/vr6+////////////////////////////////////////////dHR0/zMzM/8z + MzP/MzMz/zMzM/8zMzP/sbGx///////////////////////////////////////p6en/MzMz/zMzM/8z + MzP/MzMz/zMzM/9AQED//Pz8////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + ////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/6ysrP//////////////////////7+/v/1JSUv8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9tbW3//f39///////////////////////u7u7/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/81 + NTX/ZmZm/+rq6v///////////////////////////5WVlf8zMzP/MzMz/zMzM/8zMzP/mpqa//////// + //////////////////////////////9zc3P/MzMz/zMzM/8zMzP/MzMz/zMzM/+4uLj///////////// + //////////////////////////////9eXl7/MzMz/zMzM/8zMzP/MzMz/zMzM//Pz8////////////// + //////////////////////////////87Ozv/MzMz/zMzM/8zMzP/MzMz/zY2Nv/w8PD///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ///////////////////////////////////////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8z + MzP/rKys/////////////////+Dg4P9YWFj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/W1tb//Pz8/// + /////////////////////////+np6f8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/fHx8//////////////////////// + ////lZWV/zMzM/8zMzP/MzMz/zMzM/+ampr//////////////////////////////////////3Nzc/8z + MzP/MzMz/zMzM/8zMzP/MzMz/62trf///////////////////////////////////////////1lZWf8z + MzP/MzMz/zMzM/8zMzP/MzMz/9bW1v///////////////////////////////////////////0FBQf8z + MzP/MzMz/zMzM/8zMzP/NDQ0/+zs7P///////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////j4+P82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/9mZmb/iYmJ/4KCgv9lZWX/NjY2/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2JiYv/v7+//////////////////////////////////8/Pz/zQ0NP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9NTU3///////////////////////////+VlZX/MzMz/zMzM/8zMzP/MzMz/5qamv// + ////////////////////////////////////c3Nz/zMzM/8zMzP/MzMz/zMzM/8zMzP/mZmZ//////// + ////////////////////////////////////ZGRk/zMzM/8zMzP/MzMz/zMzM/8zMzP/x8fH//////// + ///////////////////////////////7+/v/NjY2/zMzM/8zMzP/MzMz/zMzM/84ODj/9PT0//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + ////////////////////////////////////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/83Nzf/mpqa/+np6f// + ///////////////////////////////9/f3/RkZG/zMzM/8zMzP/MzMz/zMzM/8zMzP/m5ub/6urq/+r + q6v/q6ur/6urq/+rq6v/q6ur/6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/01NTf////////////////// + /////////5WVlf8zMzP/MzMz/zMzM/8zMzP/mpqa//////////////////////////////////////9z + c3P/MzMz/zMzM/8zMzP/MzMz/zMzM/92dnb///////////////////////////////////////////+A + gID/MzMz/zMzM/8zMzP/MzMz/zMzM/+enp7//////////////////////////////////////9fX1/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0pKSv////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + ///////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5/4qKiv/09PT///////////////////////////9y + cnL/MzMz/zMzM/8zMzP/MzMz/zMzM/+zs7P/////////////////////////////////ysrK/zMzM/8z + MzP/MzMz/zMzM/8zMzP/aWlp////////////////////////////lZWV/zMzM/8zMzP/MzMz/zMzM/+a + mpr//////////////////////////////////////3Nzc/8zMzP/MzMz/zMzM/8zMzP/MzMz/0NDQ//5 + +fn//////////////////////////////////////7CwsP8zMzP/MzMz/zMzM/8zMzP/MzMz/1VVVf/8 + /Pz/////////////////////////////////ioqK/zMzM/8zMzP/MzMz/zMzM/8zMzP/enp6//////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////j4+P82Njb/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/1dXV//r6+v//////////////////////7a2tv8zMzP/MzMz/zMzM/8zMzP/MzMz/1FRUf/z + 8/P///////////////////////v7+/9mZmb/MzMz/zMzM/8zMzP/MzMz/zMzM/+jo6P///////////// + //////////////+VlZX/MzMz/zMzM/8zMzP/MzMz/5qamv////////////////////////////////// + ////c3Nz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5ycnP/////////////////z8/P/0dHR/+7u7v// + ////7+/v/zs7O/8zMzP/MzMz/zMzM/8zMzP/MzMz/5iYmP/+/v7//////////////////////8fHx/84 + ODj/MzMz/zMzM/8zMzP/MzMz/zMzM//BwcH///////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + ////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2VlZf/+/v7///////////// + ////+fn5/05OTv8zMzP/MzMz/zMzM/8zMzP/MzMz/1lZWf/FxcX/8vLy//Pz8//Ozs7/aGho/zMzM/8z + MzP/MzMz/zMzM/8zMzP/Pz8//+/v7////////////////////////////5WVlf8zMzP/MzMz/zMzM/8z + MzP/mpqa//////////////////////////////////////9zc3P/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/NDQ0/2RkZP99fX3/YmJi/zk5Of8zMzP/PDw8/7y8vP//////jIyM/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/3Jycv/CwsL/29vb/8zMzP+NjY3/ODg4/zMzM/8zMzP/MzMz/zMzM/8zMzP/W1tb//39/f// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ///////////////////////////////////////////////////////////////4+Pj/NjY2/zMzM/8z + MzP/MzMz/zMzM/8zMzP/pKSk//Ly8v/y8vL/8vLy//Ly8v/u7u7/4eHh/8XFxf+RkZH/Pz8//zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/8LCwv//////////////////////xMTE/zU1Nf8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/82Njb/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+oqKj///////////// + ////9vb2/3Nzc/88PDz/NjY2/zMzM/8zMzP/MzMz/zMzM/82Njb/OTk5/0ZGRv92dnb/7e3t//////// + /////////3Nzc/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/RUVF//v7+//z8/P/UFBQ/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zs7O//W1tb///////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////j4+P82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+srKz///////////// + ///////////////////////////////c3Nz/Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/f39///////// + ////////////////////paWl/zQ0NP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/hoaG//7+/v////////////////+2trb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+goKD/////////////////fn5+/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/+Pj4///////f39//SUlJ/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/86Ojr/v7+///////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v/////////////////////////////////////////////////////////////////+Pj4/zY2Nv8z + MzP/MzMz/zMzM/8zMzP/MzMz/6ysrP////////////////////////////////////////////////9s + bGz/MzMz/zMzM/8zMzP/MzMz/zMzM/9cXFz/////////////////////////////////vLy8/0ZGRv8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/Ozs7/6SkpP/+/v7///////////// + /////////9zc3P88PDz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NjY2/8nJyf// + //////////////+tra3/MzMz/zMzM/8zMzP/MzMz/0pKSv9dXV3/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/4eHh//////////////////q6ur/bW1t/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/VlZW/9TU1P////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ///////////////////////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys//////// + /////////////////////////////////////////3BwcP8zMzP/MzMz/zMzM/8zMzP/MzMz/1NTU/// + ////////////////////////////////////8vLy/6Kiov9aWlr/NTU1/zMzM/8zMzP/MzMz/zMzM/80 + NDT/SUlJ/46Ojv/m5ub//////////////////////////////////////+fn5/+4uLj/cHBw/zMzM/8z + MzP/MzMz/zMzM/9zc3P/srKy/7S0tP/d3d3///////////////////////j4+P9kZGT/MzMz/zMzM/84 + ODj/urq6//Dw8P9ycnL/NDQ0/zMzM/8zMzP/MzMz/01NTf+oqKj//Pz8///////////////////////+ + /v7/ysrK/3d3d/8+Pj7/MzMz/zMzM/8zMzP/MzMz/zMzM/84ODj/Z2dn/7W1tf/6+vr///////////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////j4+P82 + Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+srKz////////////////////////////////////////////r + 6+v/Pz8//zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////////////////////////////////////// + ///////////////w8PD/0dHR/8HBwf++vr7/ysrK/+Xl5f/+/v7///////////////////////////// + //////////////////////////////+VlZX/MzMz/zMzM/8zMzP/MzMz/5qamv////////////////// + //////////////////////////z8/P/Pz8//wMDA/+jo6P/////////////////k5OT/wsLC/8HBwf/d + 3d3//v7+//////////////////////////////////////////////////v7+//d3d3/xsbG/729vf/D + w8P/19fX//b29v////////////////////////////////////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + ////////////////////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/6urq//9 + /f3//f39//39/f/9/f3//f39//v7+//z8/P/xMTE/1VVVf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+N + jY3///////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////5WVlf8z + MzP/MzMz/zMzM/8zMzP/mpqa//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra//////////////////////////////////////////////////////////////////4 + +Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/Pj4+/0VFRf9FRUX/RUVF/0VFRf9ERET/Pj4+/zQ0NP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NDQ0/9jY2P////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////lpaW/zMzM/8zMzP/MzMz/zMzM/+ampr///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////r6+v82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+C + goL///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////+c + nJz/MzMz/zMzM/8zMzP/MzMz/6Kiov////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////0tLS/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/ampq//f39/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////76+vv8zMzP/MzMz/zMzM/8zMzP/xMTE//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////oaGh/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/PT09/5iYmP/7 + +/v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////f39/4aGhv85OTn/Ozs7/4+Pj//+/v7///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + ///////////////9/f3/sLCw/2dnZ/9PT0//TU1N/01NTf9NTU3/TU1N/01NTf9NTU3/TU1N/01NTf9N + TU3/T09P/1ZWVv9lZWX/gICA/7CwsP/w8PD///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////X19f/29vb///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////fHx8/zMzM/8z + MzP/Ozs7/zMzM/9fX1////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////9wcHD/MzMz/zMzM/89PT3cMzMz/z4+Pv/39/f///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////Pz8/0pKSv8z + MzP/OTk57Dw8PJUzMzP/MzMz/7W1tf////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////Gxsb/MzMz/zMzM/87OzuqS0tLNjQ0NP0zMzP/TExM//Hx8f// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////9/f3/1dXV/8z + MzP/MzMz/0VFRUmNjY0APDw8rTMzM/8zMzP/ZGRk//Hx8f////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////b29v9wcHD/MzMz/zMzM/86OjrAgYGBAgAAAABTU1MYNzc34zMzM/8z + MzP/TExM/7a2tv/39/f///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////r6+v++vr7/U1NT/zMzM/8z + MzP/NjY27E1NTSMAAAAAAAAAAAAAAABKSkoqNzc34jMzM/8zMzP/MzMz/z4+Pv9gYGD/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9iYmL/QUFB/zMzM/8zMzP/MzMz/zY2NutHR0c3AAAAAAAAAAAAAAAAAAAAAAAAAABT + U1MXPDw8rDQ0NP0zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP47 + Ozu5TU1NIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACNjY0AS0tLNTw8PJU9PT3bOzs7/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/Ojo6/0BAQOM8PDycR0dHPo+PjwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////////////////////// + ////////////////////+AAAAAAAAAAAAAAAAAAAH+AAAAAAAAAAAAAAAAAAAAfAAAAAAAAAAAAAAAAA + AAADgAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAHA + AAAAAAAAAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAB/AAAAAAAAAAAAAAAAAAAA////////////////// + //////////////////////////////////////////////8oAAAAQAAAAIAAAAABACAAAAAAAABAAAAT + CwAAEwsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgICAAENDQyYzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQEJCQil0dHQAAAAAAAAAAAAAAAAAPz8/JTc3N8Iz + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/Nzc3yD8/PyoA + AAAAQkJCGzU1NedWVlb/xMTE/+/v7//y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y + 8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y + 8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y + 8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/v + 7+//x8fH/1paWv81NTXsQUFBIDg4OJxKSkr/8PDw//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////09PT/T09P/zc3N6Y4ODjum5ub//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////6Ojo/81NTX0MzMz/7W1tf// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////+9 + vb3/MzMz/zMzM/+1tbX///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////++vr7/MzMz/zMzM/+1 + tbX/////////////////////////////////29vb/9ra2v/a2tr/2tra/9ra2v/a2tr/2tra/9ra2v/a + 2tr/2tra/9ra2v/a2tr/5+fn//////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////k5OT/2tra/9ra2v/a + 2tr/2tra/9ra2v/a2tr/2tra/9ra2v/a2tr/2tra/9ra2v/g4OD//f39//////////////////////// + ////vr6+/zMzM/8zMzP/tbW1/////////////////////////////////zc3N/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9wcHD/9vb2//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////aGho/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/1RUVP/h + 4eH//////////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////83 + Nzf/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5aWlv// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////2hoaP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/ZWVl//////////////////////++vr7/MzMz/zMzM/+1tbX///////////// + ////////////////////Nzc3/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9mZmb///////////////////////////////////////////////////////////// + //////////////////////////////////////////////9oaGj/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zg4OP/8/Pz/////////////////vr6+/zMzM/8z + MzP/tbW1/////////////////////////////////66urv+tra3/ra2t/62trf+tra3/ra2t/62trf+t + ra3/ra2t/62trf+RkZH/NDQ0/zMzM/8zMzP/Y2Nj//////////////////////////////////////// + ////////////////////////////////////////////////////////////////////wsLC/62trf+t + ra3/ra2t/62trf+tra3/ra2t/62trf+tra3/ra2t/6Ojo/9AQED/MzMz/zMzM/82Njb/+/v7//////// + /////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////////////////////// + /////////////////////////////////////////1FRUf8zMzP/MzMz/2NjY/////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////hISE/zMzM/8z + MzP/NjY2//v7+/////////////////++vr7/MzMz/zMzM/+1tbX///////////////////////////// + //////////////////////////////////////////////////////////////9VVVX/MzMz/zMzM/9j + Y2P///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////4iIiP8zMzP/MzMz/zY2Nv/7+/v/////////////////vr6+/zMzM/8zMzP/tbW1//////// + //////////////////////////7+/v+ysrL/cnJy/2tra/9ra2v/a2tr/2tra/9ra2v/a2tr//39/f// + ////VVVV/zMzM/8zMzP/Y2Nj/////////////////+/v7/+Pj4//bGxs/2tra/9ra2v/a2tr/2tra/9r + a2v/a2tr/2tra/9ra2v/bGxs/46Ojv/t7e3//////////////////////87Ozv96enr/a2tr/2tra/9r + a2v/a2tr/2tra/9ra2v/2tra//////+IiIj/MzMz/zMzM/82Njb/+/v7/////////////////76+vv8z + MzP/MzMz/7W1tf////////////////////////////////+enp7/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM//9/f3//////1VVVf8zMzP/MzMz/2NjY/////////////r6+v9WVlb/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/U1NT//j4+P///////////8zMzP82 + Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/8zMzP//////iIiI/zMzM/8zMzP/NjY2//v7+/// + //////////////++vr7/MzMz/zMzM/+1tbX/////////////////////////////////RkZG/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP//f39//////9VVVX/MzMz/zMzM/9jY2P////////////F + xcX/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//A + wMD///////////93d3f/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//MzMz//////4iIiP8z + MzP/MzMz/zY2Nv/7+/v/////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////// + /////////zc3N/8zMzP/MzMz/zMzM/9GRkb/T09P/09PT/9PT0//T09P//39/f//////VVVV/zMzM/8z + MzP/Y2Nj////////////tra2/zMzM/8zMzP/MzMz/zU1Nf9PT0//UFBQ/1BQUP9QUFD/UFBQ/09PT/82 + Njb/MzMz/zMzM/8zMzP/sbGx////////////aGho/zMzM/8zMzP/MzMz/z8/P/9PT0//T09P/09PT/9P + T0//09PT//////+IiIj/MzMz/zMzM/82Njb/+/v7/////////////////76+vv8zMzP/MzMz/7W1tf// + //////////////////////////////83Nzf/MzMz/zMzM/9lZWX//f39//////////////////////// + /////////1VVVf8zMzP/MzMz/2NjY////////////7a2tv8zMzP/MzMz/zMzM/+wsLD///////////// + ////////////////////tLS0/zMzM/8zMzP/MzMz/7Gxsf///////////2hoaP8zMzP/MzMz/z8/P//x + 8fH/////////////////////////////////iIiI/zMzM/8zMzP/NjY2//v7+/////////////////++ + vr7/MzMz/zMzM/+1tbX/////////////////////////////////Nzc3/zMzM/8zMzP/goKC//////// + //////////////////////////////9VVVX/MzMz/zMzM/9jY2P///////////+2trb/MzMz/zMzM/8z + MzP/z8/P/////////////////////////////////9LS0v8zMzP/MzMz/zMzM/+xsbH///////////9o + aGj/MzMz/zMzM/9QUFD//////////////////////////////////////4iIiP8zMzP/MzMz/zY2Nv/7 + +/v/////////////////vr6+/zMzM/8zMzP/tbW1/////////////////////////////////zc3N/8z + MzP/MzMz/4KCgv//////////////////////////////////////VVVV/zMzM/8zMzP/Y2Nj//////// + ////tra2/zMzM/8zMzP/MzMz/8/Pz//////////////////////////////////S0tL/MzMz/zMzM/8z + MzP/sbGx////////////aGho/zMzM/8zMzP/UFBQ//////////////////////////////////////+I + iIj/MzMz/zMzM/82Njb/+/v7/////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////83Nzf/MzMz/zMzM/+CgoL//////////////////////////////////////1VVVf8z + MzP/MzMz/2NjY////////////7a2tv8zMzP/MzMz/zMzM//Pz8////////////////////////////// + ////0tLS/zMzM/8zMzP/MzMz/7Gxsf///////////2hoaP8zMzP/MzMz/1BQUP////////////////// + ////////////////////iIiI/zMzM/8zMzP/NjY2//v7+/////////////////++vr7/MzMz/zMzM/+1 + tbX/////////////////////////////////Nzc3/zMzM/8zMzP/goKC//////////////////////// + //////////////9VVVX/MzMz/zMzM/9jY2P///////////+2trb/MzMz/zMzM/8zMzP/z8/P//////// + /////////////////////////9LS0v8zMzP/MzMz/zMzM/+xsbH///////////9oaGj/MzMz/zMzM/9Q + UFD//////////////////////////////////////4iIiP8zMzP/MzMz/zY2Nv/7+/v///////////// + ////vr6+/zMzM/8zMzP/tbW1/////////////////////////////////zc3N/8zMzP/MzMz/4KCgv// + ////////////////////////////////////VVVV/zMzM/8zMzP/Y2Nj////////////tra2/zMzM/8z + MzP/MzMz/8/Pz//////////////////////////////////S0tL/MzMz/zMzM/8zMzP/sbGx//////// + ////aGho/zMzM/8zMzP/UFBQ//////////////////////////////////////+IiIj/MzMz/zMzM/82 + Njb/+/v7/////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////83 + Nzf/MzMz/zMzM/93d3f//////////////////////////////////v7+/0tLS/8zMzP/MzMz/2NjY/// + /////////7a2tv8zMzP/MzMz/zMzM//ExMT/////////////////////////////////yMjI/zMzM/8z + MzP/MzMz/7Gxsf///////////2hoaP8zMzP/MzMz/0dHR//9/f3///////////////////////////// + ////fX19/zMzM/8zMzP/NjY2//v7+/////////////////++vr7/MzMz/zMzM/+1tbX///////////// + ////////////////////Nzc3/zMzM/8zMzP/NjY2/3h4eP+EhIT/hISE/4SEhP+EhIT/hISE/2lpaf8z + MzP/MzMz/zMzM/9jY2P///////////+2trb/MzMz/zMzM/8zMzP/SkpK/4KCgv+EhIT/hISE/4SEhP+E + hIT/g4OD/0xMTP8zMzP/MzMz/zMzM/+xsbH///////////9oaGj/MzMz/zMzM/8zMzP/Z2dn/4SEhP+E + hIT/hISE/4SEhP+EhIT/enp6/zY2Nv8zMzP/MzMz/zY2Nv/7+/v/////////////////vr6+/zMzM/8z + MzP/tbW1/////////////////////////////////z09Pf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/ampq////////////vLy8/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/t7e3////////////b29v/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/86Ojr//f39//////// + /////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////99fX3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/6qqqv///////////+/v7/9A + QED/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/Pj4+/+zs7P// + /////////6+vr/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/eHh4//////////////////////++vr7/MzMz/zMzM/+1tbX///////////////////////////// + ////9PT0/319ff89PT3/ODg4/zg4OP84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84ODj/RERE/5iYmP/+ + /v7/////////////////0NDQ/1paWv84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84 + ODj/WVlZ/83Nzf/////////////////+/v7/nJyc/0VFRf84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84 + ODj/ODg4/zg4OP89PT3/e3t7//Ly8v//////////////////////vr6+/zMzM/8zMzP/tbW1//////// + //////////////////////////////////////////7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+ + /v7//v7+/////////////////////////////////////////////v7+//7+/v/+/v7//v7+//7+/v/+ + /v7//v7+//7+/v/+/v7//v7+/////////////////////////////////////////////v7+//7+/v/+ + /v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//////////////////////////////////////76+vv8z + MzP/MzMz/7W1tf////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////++vr7/MzMz/zMzM/+1tbX///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////++ + vr7/MzMz/zMzM/+1tbX///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////Hx8f+9 + vb3/5+fn/////////////////////////////////9LS0v/FxcX//Pz8///////////////////////j + 4+P/wcHB/7q6uv/Ozs7/+Pj4//////////////////////////////////n5+f/r6+v/9/f3//////// + ////9/f3/7+/v//n5+f///////////////////////////////////////z8/P/T09P/u7u7/8DAwP/l + 5eX//////////////////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////9dXV3/MzMz/0FBQf/z8/P//////////////////////6urq/8zMzP/MzMz/5SUlP// + /////////9zc3P9iYmL/MzMz/zMzM/8zMzP/MzMz/0BAQP+goKD//v7+/////////////////5SUlP85 + OTn/MzMz/zU1Nf9wcHD//f39/3l5ef8zMzP/Q0ND//b29v///////////////////////////7m5uf9J + SUn/MzMz/zMzM/8zMzP/MzMz/2hoaP/i4uL///////////////////////////++vr7/MzMz/zMzM/+1 + tbX////////////////////////////8/Pz/NTU1/zMzM/8zMzP/1tbW/////////////////+Li4v87 + Ozv/MzMz/zMzM/+YmJj//////+Pj4/9BQUH/MzMz/zMzM/9OTk7/YWFh/zo6Ov8zMzP/MzMz/56env// + /////////+fn5/80NDT/MzMz/0lJSf9gYGD/YmJi//v7+/9UVFT/MzMz/zMzM//g4OD///////////// + /////////7Kysv80NDT/MzMz/zMzM/9BQUH/OTk5/zMzM/8zMzP/RkZG/+np6f////////////////// + ////vr6+/zMzM/8zMzP/tbW1/////////////////////////////Pz8/zQ0NP8zMzP/MzMz/9XV1f// + //////////7+/v9oaGj/MzMz/zMzM/8+Pj7/7e3t//////96enr/MzMz/zMzM/+Li4v//v7+///////q + 6ur/aGho/zMzM/9lZWX////////////Ozs7/MzMz/zMzM//Dw8P/////////////////U1NT/zMzM/8z + MzP/39/f//////////////////b29v9BQUH/MzMz/zQ0NP+zs7P//v7+//T09P9ycnL/MzMz/zMzM/+C + goL//////////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////z8/P80 + NDT/MzMz/zMzM//V1dX///////////+tra3/MzMz/zMzM/8zMzP/qqqq///////+/v7/QEBA/zMzM/8z + MzP/z8/P/97e3v/e3t7/3t7e/9ra2v+oqKj/5OTk////////////ysrK/zMzM/8zMzP/zMzM//////// + /////////1NTU/8zMzP/MzMz/9/f3//////////////////Dw8P/MzMz/zMzM/9iYmL///////////// + ////5OTk/zMzM/8zMzP/Q0ND//7+/v////////////////++vr7/MzMz/zMzM/+1tbX///////////// + ///////////////8/Pz/NDQ0/zMzM/8zMzP/1dXV///////Jycn/Ozs7/zMzM/8zMzP/e3t7//7+/v// + ////9fX1/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/4CAgP///////////8rKyv8z + MzP/MzMz/8zMzP////////////////9TU1P/MzMz/zMzM//Z2dn/////////////////ra2t/zMzM/8z + MzP/g4OD//////////////////////84ODj/MzMz/zQ0NP/39/f/////////////////vr6+/zMzM/8z + MzP/tbW1/////////////////////////////Pz8/zQ0NP8zMzP/MzMz/1VVVf9TU1P/NDQ0/zMzM/8z + MzP/WVlZ//b29v////////////v7+/84ODj/MzMz/zMzM/9ra2v/b29v/29vb/9ubm7/MzMz/zMzM/9A + QED////////////Kysr/MzMz/zMzM//MzMz/////////////////U1NT/zMzM/8zMzP/w8PD//////// + /////////7i4uP8zMzP/MzMz/3Nzc//////////////////09PT/NDQ0/zMzM/86Ojr//Pz8//////// + /////////76+vv8zMzP/MzMz/7W1tf////////////////////////////z8/P80NDT/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9KSkr/zc3N////////////ZGRk/zMzM/8zMzP/vb29//////// + ////ysrK/zMzM/8zMzP/XV1d////////////ysrK/zMzM/8zMzP/zMzM/////////////////1NTU/8z + MzP/MzMz/4ODg////////Pz8/+/v7//n5+f/NTU1/zMzM/88PDz/5OTk////////////oqKi/zMzM/8z + MzP/aGho//////////////////////++vr7/MzMz/zMzM/+1tbX////////////////////////////8 + /Pz/NDQ0/zMzM/8zMzP/f39//5KSkv+SkpL/g4OD/01NTf8zMzP/MzMz/z8/P//v7+///////8PDw/80 + NDT/MzMz/zw8PP+IiIj/i4uL/0BAQP8zMzP/MzMz/7W1tf//////2tra/4GBgf8zMzP/MzMz/4KCgv+u + rq7/+vr6//////9TU1P/MzMz/zMzM/8zMzP/UlJS/0BAQP81NTX/v7+//4GBgf8zMzP/MzMz/0NDQ/+B + gYH/cHBw/zQ0NP8zMzP/NTU1/8vLy///////////////////////vr6+/zMzM/8zMzP/tbW1//////// + /////////////////////Pz8/zQ0NP8zMzP/MzMz/9XV1f/////////////////29vb/Q0ND/zMzM/8z + MzP/tra2////////////paWl/zg4OP8zMzP/MzMz/zMzM/8zMzP/NTU1/5eXl////////////4CAgP8z + MzP/MzMz/zMzM/8zMzP/NDQ0/9ra2v//////ZGRk/zMzM/85OTn/Pj4+/zMzM/8zMzP/MzMz/66urv/3 + 9/f/dXV1/zMzM/8zMzP/MzMz/zMzM/8zMzP/PDw8/7Ozs////////////////////////////76+vv8z + MzP/MzMz/7W1tf////////////////////////////z8/P80NDT/MzMz/zMzM//V1dX///////////// + ////+vr6/0VFRf8zMzP/MzMz/62trf/////////////////l5eX/n5+f/35+fv97e3v/mJiY/9zc3P// + ///////////////5+fn/r6+v/zMzM/8zMzP/sLCw/+Tk5P///////////9bW1v99fX3/tra2/9jY2P+D + g4P/gYGB/7y8vP/+/v7////////////Q0ND/k5OT/3p6ev+AgID/paWl/+vr6/////////////////// + //////////////++vr7/MzMz/zMzM/+1tbX////////////////////////////8/Pz/NDQ0/zMzM/8z + MzP/i4uL/6Ghof+hoaH/mJiY/2BgYP8zMzP/MzMz/zMzM//Z2dn///////////////////////////// + /////////////////////////////////////////8rKyv8zMzP/MzMz/83Nzf////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////// + /////v7+/zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+FhYX///////////// + ///////////////////////////////////////////////////////////////W1tb/MzMz/zMzM//Z + 2dn///////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf// + //////////////////////////////+goKD/R0dH/0BAQP9AQED/QEBA/0BAQP9AQED/SEhI/2VlZf+x + sbH//v7+//////////////////////////////////////////////////////////////////////// + /////v7+/62trf+wsLD///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////++ + vr7/MzMz/zMzM/+1tbX///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////++vr7/MzMz/zMzM/+1 + tbX///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////+9vb3/MzMz/zc3N/alpaX///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////ra2t/zQ0NPo3 + NzeyWlpa//v7+/////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////f39/2FhYf83Nze8Pj4+MTQ0NPh1dXX/6+vr//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////7e3t/3t7e/80NDT6Pj4+OQAAAAA8PDxJNTU16jY2Nv9MTEz/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/TU1N/zY2Nv81NTXtOzs7UAAAAAAAAAAAAAAAAEtLSw09 + PT1cNzc3gDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDc3N4A+Pj5gSEhIEAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAP//////////wAAAAAAAAAOAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAHAAAAAAAAAA///////////KAAAADAAAABg + AAAAAQAgAAAAAAAAJAAAEwsAABMLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA9PT0lNzc3kTMzM68z + MzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68z + MzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68z + MzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzY2NpQ8PDwoAAAAADs7OzM6 + OjrvkpKS/8DAwP/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/C + wsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/C + wsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wcHB/5WVlf87 + OzvxOzs7ODY2NsGtra3///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////+0tLT/NjY2yTs7O/zv7+////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////z8/P/Ozs7/jo6Ov/09PT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////01NTf9KSkr/SkpK/0pKSv9KSkr/SkpK/0pKSv9K + Skr/SkpK/11dXf/MzMz///////////////////////////////////////////////////////////// + ////////////////////m5ub/0pKSv9KSkr/SkpK/0pKSv9KSkr/SkpK/0pKSv9KSkr/Tk5O/5CQkP/8 + /Pz////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9ISEj/+vr6//////////////////////////////////////// + ////////////////////////////////////jo6O/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+2trb////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////15eXv9b + W1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9YWFj/NTU1/zMzM/80NDT/7+/v//////////////////////// + ////////////////////////////////////////////////////pKSk/1tbW/9bW1v/W1tb/1tbW/9b + W1v/W1tb/1tbW/9DQ0P/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + ////////////////////////////////////////////////////dHR0/zMzM/80NDT/7+/v//////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////MzMz/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/0 + 9PT////////////////////////////6+vr/8/Pz//Pz8//z8/P/8/Pz//b29v//////gICA/zMzM/80 + NDT/7+/v/////////////Pz8//T09P/z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//29vb///////////// + //////////7+/v/09PT/8/Pz//Pz8//z8/P/8/Pz//39/f/Z2dn/MzMz/zMzM/+YmJj////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////8HBwf9HR0f/NjY2/zY2Nv82Njb/NjY2/2dnZ/// + ////gICA/zMzM/80NDT/7+/v///////e3t7/VVVV/zY2Nv82Njb/NjY2/zY2Nv82Njb/NjY2/zY2Nv88 + PDz/kJCQ////////////8/Pz/2pqav84ODj/NjY2/zY2Nv82Njb/NjY2/9nZ2f/Z2dn/MzMz/zMzM/+Y + mJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////0pKSv8zMzP/MzMz/zMzM/8z + MzP/MzMz/2VlZf//////gICA/zMzM/80NDT/7+/v//////92dnb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/9jY2P//////oqKi/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9nZ2f/Z + 2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8z + MzP/NjY2/3V1df97e3v/e3t7/5ubm///////gICA/zMzM/80NDT/7+/v//////9iYmL/MzMz/zMzM/9o + aGj/fHx8/3x8fP98fHz/e3t7/0ZGRv8zMzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/WVlZ/3t7e/97 + e3v/e3t7/+bm5v/Z2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////////zY2Nv8zMzP/ampq////////////////////////////gICA/zMzM/80NDT/7+/v//////9i + YmL/MzMz/0FBQf/7+/v//////////////////////6ampv8zMzP/MzMz/8TExP//////jo6O/zMzM/8z + MzP/3d3d///////////////////////Z2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////////zY2Nv8zMzP/bm5u////////////////////////////gICA/zMzM/80 + NDT/7+/v//////9iYmL/MzMz/0NDQ//+/v7//////////////////////6urq/8zMzP/MzMz/8TExP// + ////jo6O/zMzM/8zMzP/4uLi///////////////////////Z2dn/MzMz/zMzM/+YmJj////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8zMzP/bm5u//////////////////////// + ////gICA/zMzM/80NDT/7+/v//////9iYmL/MzMz/0NDQ//+/v7//////////////////////6urq/8z + MzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/4uLi///////////////////////Z2dn/MzMz/zMzM/+Y + mJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8zMzP/bm5u//////// + ////////////////////gICA/zMzM/80NDT/7+/v//////9iYmL/MzMz/0NDQ//+/v7///////////// + /////////6urq/8zMzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/4uLi///////////////////////Z + 2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8z + MzP/aGho////////////////////////////enp6/zMzM/80NDT/7+/v//////9iYmL/MzMz/0BAQP/7 + +/v//////////////////////6Wlpf8zMzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/29vb//////// + ///////////////S0tL/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////////zY2Nv8zMzP/NDQ0/2lpaf9vb2//b29v/29vb/9ra2v/Nzc3/zMzM/80NDT/7+/v//////9i + YmL/MzMz/zMzM/9dXV3/b29v/29vb/9vb2//b29v/0FBQf8zMzP/MzMz/8TExP//////jo6O/zMzM/8z + MzP/UFBQ/29vb/9vb2//b29v/29vb/9OTk7/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////////01NTf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9D + Q0P/+Pj4//////95eXn/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NDQ0/9vb2/// + ////paWl/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+wsLD////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////8nJyf9NTU3/Nzc3/zc3N/83Nzf/Nzc3/zc3N/83 + Nzf/Nzc3/0hISP+9vb3////////////j4+P/Xl5e/zc3N/83Nzf/Nzc3/zc3N/83Nzf/Nzc3/zc3N/8/ + Pz//m5ub////////////9vb2/3R0dP85OTn/Nzc3/zc3N/83Nzf/Nzc3/zc3N/83Nzf/OTk5/3t7e//4 + +Pj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////////////////v7+//7+/v/+ + /v7//v7+//7+/v/+/v7//v7+//////////////////////////////////7+/v/+/v7//v7+//7+/v/+ + /v7//v7+//7+/v/////////////////////////////////+/v7//v7+//7+/v/+/v7//v7+//7+/v/+ + /v7//v7+///////////////////////4+Pj/PDw8/zo6Ov/09PT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zo6Ov/09PT///////////////////////7+/v/6+vr////////////////////////////5 + +fn///////////////////////7+/v/39/f//Pz8//////////////////////////////////////// + //////////7+/v/6+vr//////////////////////////////////v7+//b29v/9/f3///////////// + ///////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////2xsbP9ERET/2dnZ//////// + /////////6ampv8+Pj7/lJSU///////6+vr/mJiY/01NTf88PDz/QUFB/3Z2dv/j4+P////////////g + 4OD/bm5u/1hYWP90dHT/6+vr/39/f/9ERET/3Nzc//////////////////v7+/+bm5v/TU1N/zs7O/9F + RUX/goKC/+/v7//////////////////4+Pj/PDw8/zo6Ov/09PT//////////////////f39/zQ0NP8z + MzP/ra2t////////////2tra/zg4OP8zMzP/ioqK//////9+fn7/MzMz/0ZGRv+Hh4f/ZmZm/zQ0NP9M + TEz/+Pj4//////+Dg4P/MzMz/29vb/+BgYH/5eXl/0tLS/8zMzP/tLS0/////////////////4GBgf8z + MzP/Pj4+/3BwcP9JSUn/MzMz/1lZWf/4+Pj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////Pz8/zQ0NP8zMzP/ra2t///////7+/v/YGBg/zMzM/9AQED/5+fn/+Xl5f82Njb/MzMz/9bW1v// + /////v7+/6mpqf9vb2//9/f3//////9ycnL/MzMz/9fX1////////////0tLS/8zMzP/tLS0//////// + ////5ubm/zQ0NP80NDT/y8vL///////s7Oz/QUFB/zMzM/+5ubn////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////Pz8/zQ0NP8zMzP/ra2t//39/f+Pj4//MzMz/zU1Nf+4uLj//////8fHx/8z + MzP/MzMz/01NTf9OTk7/Tk5O/09PT/9wcHD/9fX1//////9xcXH/MzMz/9nZ2f///////////0tLS/8z + MzP/sLCw////////////w8PD/zMzM/9AQED/+fn5////////////Z2dn/zMzM/+VlZX////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////Pz8/zQ0NP8zMzP/RkZG/0ZGRv8zMzP/MzMz/2pqav/x + 8fH//////9LS0v8zMzP/MzMz/4uLi/+Tk5P/jo6O/zMzM/8zMzP/2NjY//////9xcXH/MzMz/9nZ2f// + /////////0tLS/8zMzP/mZmZ////////////z8/P/zMzM/84ODj/7u7u///////+/v7/V1dX/zMzM/+h + oaH////////////4+Pj/PDw8/zo6Ov/09PT//////////////////Pz8/zQ0NP8zMzP/QEBA/0lJSf9G + Rkb/NjY2/zMzM/9NTU3/6enp//j4+P9LS0v/MzMz/4yMjP/f39//lZWV/zMzM/9FRUX/9vb2//b29v9q + amr/MzMz/8bGxv/5+fn//////0tLS/8zMzP/S0tL/6+vr/+SkpL/z8/P/0lJSf8zMzP/enp6/9PT0/+b + m5v/NDQ0/zg4OP/e3t7////////////4+Pj/PDw8/zo6Ov/09PT//////////////////Pz8/zQ0NP8z + MzP/rKys//39/f/8/Pz/4ODg/zw8PP8zMzP/nJyc///////Ly8v/QUFB/zMzM/8zMzP/MzMz/z09Pf/C + wsL//////3R0dP8zMzP/MzMz/zQ0NP+Ghob//////1VVVf8zMzP/PDw8/zMzM/8zMzP/jIyM/83Nzf9D + Q0P/MzMz/zMzM/8zMzP/ODg4/62trf/////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////Pz8/zQ0NP8zMzP/ra2t////////////6+vr/z09Pf8zMzP/kpKS////////////8PDw/7Kysv+b + m5v/ra2t/+zs7P////////////X19f9oaGj/MzMz/8LCwv/39/f//////9HR0f+oqKj/5eXl/6CgoP+z + s7P/+Pj4///////y8vL/tLS0/5ubm/+rq6v/5ubm///////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////f39/zU1Nf8zMzP/RkZG/1NTU/9RUVH/PT09/zMzM/83Nzf/0tLS//////// + //////////////////////////////////////////////90dHT/MzMz/9vb2/////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////3l5ef8+Pj7/PT09/z09Pf89PT3/QkJC/2FhYf/B + wcH////////////////////////////////////////////////////////////FxcX/i4uL//r6+v// + //////////////////////////////////////////////////////////////////////////////// + ///////////////4+Pj/PDw8/zo6Ov/09PT///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zs7O/7x8fH///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////19fX/Ozs7/zY2NtC/v7////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////FxcX/NjY21zo6OkpDQ0P5srKy/+Dg4P/h4eH/4eHh/+Hh4f/h + 4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h + 4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h + 4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4ODg/7W1tf9FRUX7OTk5UHFxcQA6OjpCNjY2uTQ0NN8z + MzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98z + MzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98z + MzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfNDQ03zc3N7w6OjpGa2trAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAP///////wAAgAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////8AACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAABMLAAAT + CwAAAAAAAAAAAAAAAAAARERECjMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAz + MzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAz + MzMgMzMzIDMzMyBDQ0MKAAAAADc3N0pjY2PwkpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+S + kpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+S + kpL/kpKS/5KSkv+SkpL/kpKS/2VlZfE3NzdOWVlZ4vv7+/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////Pz8/1tbW+Z0dHT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////eHh4/3R0dP////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////94eHj/dHR0//////// + /////////4iIiP+Hh4f/h4eH/4eHh/+Hh4f/h4eH/6Kiov/9/f3///////////////////////////// + ////////////////////0tLS/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/iIiI/8zMzP///////////3h4eP90 + dHT/////////////////NTU1/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/7+/v/////////////////// + //////////////////////////////+0tLT/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/QUFB//7+/v// + ////eHh4/3R0dP/////////////////W1tb/1tbW/9bW1v/W1tb/1tbW/4WFhf8zMzP/sbGx//////// + //////////////////////////////////////////Dw8P/W1tb/1tbW/9bW1v/W1tb/09PT/0pKSv81 + NTX//f39//////94eHj/dHR0/////////////////+zs7P+3t7f/tbW1/7W1tf/a2tr/qqqq/zMzM/+x + sbH//////9/f3/+1tbX/tbW1/7W1tf+1tbX/tbW1/97e3v///////////9HR0f+1tbX/tbW1/7W1tf/2 + 9vb/XV1d/zU1Nf/9/f3//////3h4eP90dHT/////////////////UlJS/zMzM/8zMzP/MzMz/5iYmP+q + qqr/MzMz/7Gxsf/v7+//PDw8/zMzM/8zMzP/MzMz/zMzM/8zMzP/Ozs7/+7u7v/Q0ND/NDQ0/zMzM/8z + MzP/MzMz/+Xl5f9dXV3/NTU1//39/f//////eHh4/3R0dP////////////////81NTX/QEBA/6SkpP+n + p6f/09PT/6qqqv8zMzP/sbGx/9ra2v8zMzP/U1NT/6enp/+np6f/p6en/1RUVP8zMzP/2NjY/7S0tP8z + MzP/aGho/6enp/+np6f/9PT0/11dXf81NTX//f39//////94eHj/dHR0/////////////////zU1Nf9b + W1v/////////////////qqqq/zMzM/+xsbH/2tra/zMzM/+BgYH/////////////////g4OD/zMzM//Y + 2Nj/tLS0/zMzM/+np6f/////////////////XV1d/zU1Nf/9/f3//////3h4eP90dHT///////////// + ////NTU1/1tbW/////////////////+qqqr/MzMz/7Gxsf/a2tr/MzMz/4GBgf////////////////+D + g4P/MzMz/9jY2P+0tLT/MzMz/6enp/////////////////9dXV3/NTU1//39/f//////eHh4/3R0dP// + //////////////81NTX/WFhY/////////////////6enp/8zMzP/sbGx/9ra2v8zMzP/fn5+//////// + /////////4CAgP8zMzP/2NjY/7S0tP8zMzP/paWl/////////////////1tbW/81NTX//f39//////94 + eHj/dHR0/////////////////zY2Nv80NDT/WVlZ/1tbW/9bW1v/QUFB/zMzM/+zs7P/3Nzc/zMzM/85 + OTn/W1tb/1tbW/9bW1v/OTk5/zMzM//Z2dn/tbW1/zMzM/9AQED/W1tb/1tbW/9ZWVn/NDQ0/zY2Nv/9 + /f3//////3h4eP90dHT/////////////////iIiI/zc3N/81NTX/NTU1/zU1Nf81NTX/UVFR/+np6f/7 + +/v/Z2dn/zY2Nv81NTX/NTU1/zU1Nf82Njb/ZmZm//r6+v/r6+v/UlJS/zU1Nf81NTX/NTU1/zU1Nf83 + Nzf/hoaG////////////eHh4/3R0dP////////////////////////////7+/v/+/v7//v7+//7+/v// + /////////////////////v7+//7+/v/+/v7//v7+//7+/v///////////////////////v7+//7+/v/+ + /v7//v7+//////////////////////94eHj/dHR0//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3h4eP90dHT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////eHh4/3R0dP////////////////+Q + kJD/xsbG////////////rKys/6Kiov//////z8/P/4KCgv97e3v/tra2////////////sbGx/5OTk//b + 29v/mZmZ/8jIyP///////////+3t7f+Tk5P/eHh4/6CgoP/4+Pj///////////94eHj/dHR0//////// + /////f39/zQ0NP+EhIT//////9LS0v81NTX/fX19/9fX1/83Nzf/g4OD/6Ghof9AQED/wMDA/+3t7f8z + MzP/m5ub/9fX1/9DQ0P/iYmJ///////9/f3/VlZW/1NTU/+bm5v/Q0ND/3l5ef///////////3h4eP90 + dHT////////////9/f3/NDQ0/4SEhP/y8vL/U1NT/0VFRf/q6ur/mZmZ/zMzM/+FhYX/iYmJ/3p6ev/Y + 2Nj/5OTk/zMzM//m5ub//////0NDQ/+Hh4f//////9zc3P8zMzP/ubm5//////+UlJT/Nzc3//39/f// + ////eHh4/3R0dP////////////39/f80NDT/PDw8/zs7O/8zMzP/c3Nz//Pz8/+lpaX/MzMz/6ampv+q + qqr/MzMz/6enp//k5OT/MzMz/+bm5v//////Q0ND/2tra//+/v7/4+Pj/zMzM/+kpKT//////39/f/9C + QkL//v7+//////94eHj/dHR0/////////////f39/zQ0NP9vb2//ycnJ/7Gxsf83Nzf/hoaG//Dw8P9R + UVH/S0tL/0xMTP9NTU3/7Ozs/4SEhP8zMzP/ZmZm//X19f9HR0f/Nzc3/z4+Pv91dXX/iIiI/zc3N/9W + Vlb/NTU1/6ysrP///////////3h4eP90dHT////////////9/f3/NDQ0/3Fxcf/Q0ND/vLy8/zg4OP97 + e3v///////j4+P/Hx8f/xMTE//b29v//////3Nzc/zMzM//Y2Nj//////9TU1P/j4+P/wcHB/+7u7v// + ////2NjY/76+vv/k5OT/////////////////eHh4/3R0dP////////////////9VVVX/OTk5/zk5Of88 + PDz/X19f/+Dg4P/////////////////////////////////19fX/cXFx//X19f////////////////// + //////////////////////////////////////////////94eHj/dHR0//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////3h4eP90dHT///////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////eHh4/3R0dP// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////94 + eHj/X19f6v7+/v////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////v7+/2FhYe03NzdcdHR0+qampv+np6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+n + p6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+n + p6f/p6en/6enp/92dnb7Nzc3YQAAAAA+Pj4aNTU1QDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNANTU1QEBAQBwAAAAAgAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAEoAAAAEAAAACAAAAABACAAAAAAAAAEAAAT + CwAAEwsAAAAAAAAAAAAAWFhYUYeHh4+IiIiPiIiIj4iIiI+IiIiPiIiIj4iIiI+IiIiPiIiIj4iIiI+I + iIiPiIiIj4iIiI+IiIiPWVlZUrS0tPj///////////////////////////////////////////////// + /////////////////////////7a2tvm6urr//////8PDw//Dw8P/w8PD/+fn5/////////////////// + ////9PT0/8PDw//Dw8P/w8PD//Ly8v+8vLz/urq6//////+FhYX/hISE/3BwcP91dXX///////////// + /////////+jo6P+EhIT/hISE/2FhYf+cnJz/vLy8/7q6uv//////ioqK/3R0dP+ysrL/cnJy/8LCwv90 + dHT/dHR0/4CAgP/v7+//e3t7/3R0dP+lpaX/mZmZ/7y8vP+6urr//////0FBQf/S0tL/ycnJ/3Jycv+H + h4f/n5+f/9PT0/9PT0//xsbG/11dXf/T09P/q6ur/5mZmf+8vLz/urq6//////9HR0f//////9TU1P9y + cnL/h4eH/7+/v///////Wlpa/8bGxv9tbW3//////62trf+ZmZn/vLy8/7q6uv//////SkpK/0hISP9C + QkL/iIiI/5ycnP9AQED/SEhI/0JCQv/d3d3/Pz8//0hISP8+Pj7/rq6u/7y8vP+6urr///////////// + //////////////////////////////////////////////////////////////+8vLz/urq6///////V + 1dX//////9PT0//z8/P/v7+//+3t7f/s7Oz/29vb/9jY2P//////4ODg/8XFxf/9/f3/vLy8/7q6uv/+ + /v7/XFxc/8XFxf94eHj/dnZ2/4yMjP+VlZX/jo6O/9bW1v9mZmb/9vb2/2VlZf+cnJz/q6ur/7y8vP+6 + urr//v7+/0RERP96enr/iYmJ/4aGhv96enr/hYWF/3R0dP/Q0ND/S0tL/6Wlpf9mZmb/goKC/7u7u/+8 + vLz/urq6//7+/v9NTU3/gICA/3x8fP/9/f3/4uLi//39/f+dnZ3/8/Pz/+3t7f/r6+v/9fX1/+jo6P// + ////vLy8/7q6uv////////////////////////////////////////////////////////////////// + /////////7y8vP+2trb6//////////////////////////////////////////////////////////// + //////////////+3t7f7YWFhXJCQkJ+QkJCfkJCQn5CQkJ+QkJCfkJCQn5CQkJ+QkJCfkJCQn5CQkJ+Q + kJCfkJCQn5CQkJ+QkJCfYmJiXgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + + + \ No newline at end of file diff --git a/src/RetroGOG/frmMain.Designer.cs b/src/RetroGOG/frmMain.Designer.cs new file mode 100644 index 0000000..2dddf09 --- /dev/null +++ b/src/RetroGOG/frmMain.Designer.cs @@ -0,0 +1,197 @@ +namespace RetroGOG +{ + partial class frmMain + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain)); + this.btnNext = new System.Windows.Forms.Button(); + this.pictureBox1 = new System.Windows.Forms.PictureBox(); + this.pictureBox2 = new System.Windows.Forms.PictureBox(); + this.pictureBox3 = new System.Windows.Forms.PictureBox(); + this.btnCancel = new System.Windows.Forms.Button(); + this.btnAbout = new System.Windows.Forms.Button(); + this.lblWelcom = new System.Windows.Forms.Label(); + this.lblExplain = new System.Windows.Forms.Label(); + this.lblExplain2 = new System.Windows.Forms.Label(); + this.lblExplain3 = new System.Windows.Forms.Label(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit(); + this.SuspendLayout(); + // + // btnNext + // + this.btnNext.Location = new System.Drawing.Point(462, 343); + this.btnNext.Name = "btnNext"; + this.btnNext.Size = new System.Drawing.Size(75, 23); + this.btnNext.TabIndex = 0; + this.btnNext.Text = "&Next > >"; + this.btnNext.UseVisualStyleBackColor = true; + this.btnNext.Click += new System.EventHandler(this.btnNext_Click); + // + // pictureBox1 + // + this.pictureBox1.Image = global::RetroGOG.Properties.Resources.retroarch; + this.pictureBox1.InitialImage = global::RetroGOG.Properties.Resources.retroarch; + this.pictureBox1.Location = new System.Drawing.Point(12, 131); + this.pictureBox1.Name = "pictureBox1"; + this.pictureBox1.Size = new System.Drawing.Size(193, 192); + this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; + this.pictureBox1.TabIndex = 1; + this.pictureBox1.TabStop = false; + // + // pictureBox2 + // + this.pictureBox2.Image = global::RetroGOG.Properties.Resources.galaxy_logo; + this.pictureBox2.Location = new System.Drawing.Point(425, 131); + this.pictureBox2.Name = "pictureBox2"; + this.pictureBox2.Size = new System.Drawing.Size(193, 192); + this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; + this.pictureBox2.TabIndex = 2; + this.pictureBox2.TabStop = false; + // + // pictureBox3 + // + this.pictureBox3.BackColor = System.Drawing.Color.Transparent; + this.pictureBox3.Image = global::RetroGOG.Properties.Resources.arrow; + this.pictureBox3.Location = new System.Drawing.Point(211, 131); + this.pictureBox3.Name = "pictureBox3"; + this.pictureBox3.Size = new System.Drawing.Size(208, 134); + this.pictureBox3.TabIndex = 3; + this.pictureBox3.TabStop = false; + // + // btnCancel + // + this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.btnCancel.Location = new System.Drawing.Point(543, 343); + this.btnCancel.Name = "btnCancel"; + this.btnCancel.Size = new System.Drawing.Size(75, 23); + this.btnCancel.TabIndex = 4; + this.btnCancel.Text = "&Cancel"; + this.btnCancel.UseVisualStyleBackColor = true; + this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); + // + // btnAbout + // + this.btnAbout.Location = new System.Drawing.Point(12, 343); + this.btnAbout.Name = "btnAbout"; + this.btnAbout.Size = new System.Drawing.Size(75, 23); + this.btnAbout.TabIndex = 5; + this.btnAbout.Text = "&About"; + this.btnAbout.UseVisualStyleBackColor = true; + this.btnAbout.Click += new System.EventHandler(this.btnAbout_Click); + // + // lblWelcom + // + this.lblWelcom.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.lblWelcom.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblWelcom.Location = new System.Drawing.Point(-2, 9); + this.lblWelcom.Name = "lblWelcom"; + this.lblWelcom.Size = new System.Drawing.Size(630, 24); + this.lblWelcom.TabIndex = 6; + this.lblWelcom.Text = "Welcome to the RetroGOG Installation Wizard"; + this.lblWelcom.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // lblExplain + // + this.lblExplain.AutoSize = true; + this.lblExplain.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblExplain.Location = new System.Drawing.Point(12, 45); + this.lblExplain.Name = "lblExplain"; + this.lblExplain.Size = new System.Drawing.Size(616, 18); + this.lblExplain.TabIndex = 7; + this.lblExplain.Text = "This wizard will guide you through the download, installation, and configuration " + + "of RetroGOG."; + // + // lblExplain2 + // + this.lblExplain2.AutoSize = true; + this.lblExplain2.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblExplain2.Location = new System.Drawing.Point(12, 63); + this.lblExplain2.Name = "lblExplain2"; + this.lblExplain2.Size = new System.Drawing.Size(536, 18); + this.lblExplain2.TabIndex = 8; + this.lblExplain2.Text = "RetroGOG allows you to play your Retroarch games directly in GOG Galaxy 2.0."; + // + // lblExplain3 + // + this.lblExplain3.AutoSize = true; + this.lblExplain3.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblExplain3.Location = new System.Drawing.Point(12, 91); + this.lblExplain3.Name = "lblExplain3"; + this.lblExplain3.Size = new System.Drawing.Size(158, 18); + this.lblExplain3.TabIndex = 9; + this.lblExplain3.Text = "To begin, press \"Next\"."; + // + // frmMain + // + this.AcceptButton = this.btnNext; + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.CancelButton = this.btnCancel; + this.ClientSize = new System.Drawing.Size(630, 378); + this.Controls.Add(this.lblExplain3); + this.Controls.Add(this.lblExplain2); + this.Controls.Add(this.lblExplain); + this.Controls.Add(this.lblWelcom); + this.Controls.Add(this.btnAbout); + this.Controls.Add(this.btnCancel); + this.Controls.Add(this.pictureBox3); + this.Controls.Add(this.pictureBox2); + this.Controls.Add(this.pictureBox1); + this.Controls.Add(this.btnNext); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.Name = "frmMain"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "RetroGOG"; + this.Load += new System.EventHandler(this.frmMain_Load); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button btnNext; + private System.Windows.Forms.PictureBox pictureBox1; + private System.Windows.Forms.PictureBox pictureBox2; + private System.Windows.Forms.PictureBox pictureBox3; + private System.Windows.Forms.Button btnCancel; + private System.Windows.Forms.Button btnAbout; + private System.Windows.Forms.Label lblWelcom; + private System.Windows.Forms.Label lblExplain; + private System.Windows.Forms.Label lblExplain2; + private System.Windows.Forms.Label lblExplain3; + } +} \ No newline at end of file diff --git a/src/RetroGOG/frmMain.cs b/src/RetroGOG/frmMain.cs new file mode 100644 index 0000000..d737ba5 --- /dev/null +++ b/src/RetroGOG/frmMain.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace RetroGOG +{ + public partial class frmMain : Form + { + public frmMain() + { + InitializeComponent(); + } + + private void frmMain_Load(object sender, EventArgs e) + { + + } + + private void btnCancel_Click(object sender, EventArgs e) + { + if (MessageBox.Show("Are you sure you want to exit the wizard? Any unsaved progress will be lost.", "RetroGOG", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes) + { + this.Close(); + } + } + + private void btnAbout_Click(object sender, EventArgs e) + { + Form frmAbout = new frmAbout(); + frmAbout.Show(); + } + + private void btnNext_Click(object sender, EventArgs e) + { + this.Hide(); + Form frmDependencies = new frmDependencies(); + frmDependencies.Closed += (s, args) => this.Close(); + frmDependencies.Show(); + } + } +} diff --git a/src/RetroGOG/frmMain.resx b/src/RetroGOG/frmMain.resx new file mode 100644 index 0000000..accb675 --- /dev/null +++ b/src/RetroGOG/frmMain.resx @@ -0,0 +1,1889 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + + AAABAAYAAAAAAAEAIADdFwAAZgAAAICAAAABACAAKAgBAEMYAABAQAAAAQAgAChCAABrIAEAMDAAAAEA + IACoJQAAk2IBACAgAAABACAAqBAAADuIAQAQEAAAAQAgAGgEAADjmAEAiVBORw0KGgoAAAANSUhEUgAA + AQAAAAEACAQAAAD2e2DtAAAXpElEQVR42u2deYAUxb3HPzOzB7ssuxzLfQmIXBpFWSCiiIhBIhoFTEzU + FzXmqVEQiOgDESV4LA/QKGh8JmqMmngkwovhKYgcigcgdxS5WZBjuZY92JOZeX8sM8zudPX0Od1L12f+ + 6a7q6vlV9ber6y6QSCQSiUQikUgk3sKn7PwCG5sfG3pyWOpgeh2nirDTdkoMkE4O2ceKFmYszV1y7oHJ + ig9RQQBz2Nj34PiTI6uaOx0BiVWkVTb6uNXcgUsnBOv7xAng7k4780tHnUp32mSJ1fiDWcvbP/Tmurqu + gdiTfF/2LTv/eTIvlOK0sRLrCfuruhbffhHDPl8T8zGIyQEmpG7LL5wQ9um/taQh0Wx+jzteKI6cRR/3 + A6lbXz76y7qPP5VudKcdmUhVNEQqOMx2tlNRzz17aZ/R807UHp9+sjN9nz5T+EDs48/lJobTtu43QtLg + CFHEMv5GQR3Xph/0HPXCKYiWAXJu2z/zzONP5VZmMoBs/E7bLzGJj0x6M5pmbKQm6lrZI5h29yeLOS2A + X5+zc0EwI+LZjHzGkOq05RIL8XM+g1jLiahLxYDyFd8UgB/msPvp6mYRj2b8nh86ba/EBs5jLl2iZ8HU + wjnTG0EAWvc7ODt0+lOQSj4XO22pxCaakMciqk6f1bQ9+e+t3/h/z6Fxp9Iil/xCvv1nNV2YGD0O+4on + PJbi/7bFyZERp1zudNpCic2M4ILocXleQR//0aFV0e//TTR22j6JzQS4LXoc9B+6wV9+deQ0jeFOWydJ + AgNpFT2uGOJPuyJy0oW2TtsmSQKZXHjmJM8fOi9yfK5s9fMIPaNHJxv7i6In7Zy2S5IkzuT0YfxV0ZNM + p+2SJInYJ+0/0zUs2/29gl9wLPEgUgAeRwrA40gBeBwpAI8jBeBxpAA8jhSAx5EC8DhSAB5HCsDjSAF4 + HCkAjyMF4HGkADyOFIDHkQLwOFIAHkcKwONIAXgcKQCPIwXgcSxaEO4YK/mWw1QS0vSnAdJpTDYtaEd3 + 2iKXJXQKCwRQzWv8lZMm7tCK/vyYvq5ZluYkRUAujZw2JAmYFkCYOfzD5D0O8y8W0oM7uNLxb9JJXmYx + x/DRhhv5BWnmb+lqTKf3Ot63xJAw3zGZSRSZv5UJyhnHWxwhRJD9zOOhmJW1zk5MC2C+hSuJh1jB7exw + MDneY2Od85XMd9CaZGBaABssNmg/D7DLmbQgzNI4t+UO2ZIsTAqgyoYsu5AplDmSGJUcjXPb64glycO0 + AOzYSmIHLzqSGNVUxrmdJGjgTg0HpwvdAuY78hkIKrRihDjldGLYim07A6TTUcE1SDUVlCYsW9fwNlOS + nhhhxWYsLU1bDRfbBNCJNxTdQwSp4Qjf8AEbVD4gyxlHltOp4wFsE4BP5dYZZNON6/iAWXFr2Uco4lv6 + O506HsDBMoCP63lQaECYb50zzUM4vDvQSBawWeD3vea7lLGTPRzkBOWESKUxLehAVzonLXrlrGATZWTR + iytpEuOznzXs4gSQTQd60Vtzj0cx2ymgkBNUEiKVJuTSnq50tvStdVgAAa4UCqA4Yegw+1nCp2ylWqE0 + 4SeHPH7EQNs7ddYzjYPRsxf4HQMAKGAuK+vUInw042rGcI7KJjwhdvMxK9nJKYVYBcghj6FcSgZW4Pj+ + YOLVSdVL3yE28he+VKmkhShiMYtpx83coLoIXhmLWcsxxXaASsaeXkCzET0YSae4K77nt5TEnB9jMq/R + mc+ZFifiMMd5h/cZxb2KRdxTfMVbrFWJe5DjLGIRLbmBMbQwnf6OC0BcIVRT+CHm8onGGvoBnmEBExko + 8D/K/Sr9D8GYxu7P+TuzuKTeFX+s8/gBSniTq3hYQU6ROL/DDubESWAHz7JGY7XzCH/kfX7FKJOP0PGG + oN1Cn5ZCny+4nUW6Gmh2MYF5ghCv6Oh+KuG5eg+olM8VrlvCZOHjr2Utr9Y5D/MP7mSVrlaHY8xigkLz + tR4cFkA5Hwv9uim6hplvKNI1/JkpVCn4bNV1nwP1+in2KpZVSilNeKcPKY+xbjb5MedaCfMld7Jdd7gz + OCqAKuYIy/pp9FF0/xczDbfOL+VxhU+OvjWSc+p9mgoN94YcjeYRIebwjuH7HGCsiYZzxwQQ4it+wz+F + /l3prOC6gVmm2uaX1Mt4AX6po8UxlbvqVeMqNYetT2b06/2myTFVR3mQYwbD2lYIrOFAnNspqinhGPvZ + xkYOq2p+jII2y5iumk0GSAGCKhIJ8zoDuKiOW3de5XXWU0yYijibfGTgw08WbbmAa+laz994T0Hf0+0F + G3jJdJ/qXp4m39DDtE0Au7neROhu/FjB9TX2Ca7305eR9KY5PorZyTKWCd7Nap7n5XrR7sp0AI4xKm5w + ayYfWVTjrktTfoMPqGAW1cKrMriIvrQlQDE7WM33QqmsYLFimiXC8WqgEulMVhiMWcjfBdfn8BDDottd + NKUzQ9nK7wTFu018yeVJikmAwQyhNVXsYzMbKDztfi5Tqd2p40NhIdTHcH5Np5gmo0qW8xxHFK8O8z8M + MbDkvwsFEGBSvUy6lvcFQ88zmE3fONcezOU+Qfn43SQJIIXJXBf9lN1MJbvZSAXn0e/0TIhq/ioI62Ms + t9b7DDbiGn7AeEGRbz+LuFG3jY63A9Qnk2ncoOBeyYeCEHcrPH6A5kwVDOr+msNJicsoflIngRvRi5u5 + g0HRiTBr2CMIezO3KT6cdjxLriDMewbKEi4TwHn8gWsVfb6JaW2PpRWjhXfrI9gGs4avkxCXjJgN2kQs + Fri349fC3oL23CPw22GgOugiAbTit7wiqP3DKoG6h6kW0X4kcE9GV/OFCXdhC/GlwGcM2SrhRtBe5/3E + uEIAafTlMf7Bz4UPM8wmgU9/Qiq/CwWhRLUJKxmY8IoCwZjqRgxTDZcu9F+v20oXFAKb8t8JN6yuFD6y + 5/iDSrgwPsWcI3FXs3kuSHjFDkGu1ilh6+QA/iy4Y0jnO+0CAZzgUWYkkEAlxwU+uzGCHYPZ69M14RWi + ZvCeCUP2ELiXUEJTXVbaJoBzmA2EqaGYfWxihUr3SCHjeYLBKncrsXiOXnO7oh2liYYGZlGXVuLeiSY0 + VqwUV1HqFgGkcU70OI9RlPIKbwsbacv5L/JVJGBm8rkSibNns+RquEbUrJ2jIWy2YpoEFfs71UhaIbAJ + 45mh0lJVzWOsE/paOzsnIwnbZGerDPpKFCstb6XyNSHdfRNJrQVczXSV+falPCIs6lm5dESABwTVKCtp + rOEaUayqNYRVvsave//nJFcDr2SsyptxhIcF2aJVU0TSyWOuStORdWgZiNpE4H5cQ9gTiq6pujuukl4L + +Bnf8JHQdxuzeFRBlU1opNi7F2CIhjU8fKTQmFzOobfKQDNr0bKySCuBe+JWisOCb326agOSEkkXgJ9J + bGa/0H8h/RkR59qIXMVKU4jfKA4ccR4tCdtJ4L6FYIKs/BuBe67uvNKBlsAc/ksleiGe5VCca7rgMYfZ + ovFfj/O/vMRrfO2iyZ49BZ/DgwmHqa4U3lEvjjQFD1Ts74twnGcUHtJFgquXamrUWcIoZvAnXuAe7hL0 + qIuwr9EoN6aqHMsplaFyAMeE65bk6bbBEQH4uEe1sWMZn8W5DRTkGp8JO1QjBHmDqTFjeTcxQ2hX/BsZ + tnWBCFHLx0IKhGHC/CVuJkItaYLeTzUc6gxqxgSV2kCY5+IKOd0FTas1zFEdJlrB08ytd8VqhY9MbWLE + J0dId9OKHq4RyLqMp4T/u5L3BD79DcwUcqw3cIhqj9feuHGyKcLPxirmCt/SPdzDgrgPSkgwhjZVoexe + Y3i8rRa6CafAr2WyQuN5mBVMFbQB+LjZgAWOCcDHRFW9vhmXzY2kteKVYf7Ko9HRdmco4VX+Q7G8HBA0 + 1KYp1KKDijN/rMLPHcL6wqfcxsKYVKhhOzOYJGwWv9hACcDR3sCW3M/vhEWswyzk53VcGnMvjyteG2Yx + qxjOFXQmixClfM8XLFEQRS29BFJKpblCHfwN2nMpGZRxmAIOEGAQXSxLhb4MZ6HA73seoxndaEMKxexh + n8rHLp37dLcCgsPdwSNYovJ+zWd0vSx5BJ8oFA9rKeZd3iOdVMLUKE4XP8OdQp8u9RaKBChlKlmkUEPF + 6U/NSzzG1RalgY8HWK8whyJCkcbha7cY7OAy+QlI3OGhRgqTVFqudsWNAgrwqKDiVEuYSkopS7B43TVc + KvT7geC+pRRRFi1pVDIzOqRElALaU6Y5T2vqOVDjcpUxhOqYFECmMNtpoil8B+5V8Y0f4dacWQlH2qlz + AZNUIj1A48j64uinQrTQvZ5FKfrwpCkJXMwMw91lJgUQEDZnam2gHUU/oZ/SgIkuzFPNBdS5mNmqve2t + uU7TfVKiAm8jePP0TTm9jNmGF3u4gtkmOstM1wKUs1Of5iaJAI8IH4nyBPHO/IlhBgwPcBNzEybzfcJx + yXVjHRF+F8U7+lRkrUwer3CR7mw8jXvI190BFItpAYxWzOzPZZDmO3TkYcUMrIVCp1AtTXmap3WVxH30 + YS4PadiZJJPnuVq1PB1gKNOjj6oxP1G4Jo/uulIRoAMvMUnYQ6hkRx6vxs1W1kug3eORwx8KikDqZNGG + lfUaYlowU1DRUqYrzVhd7x6ZPE5vYQgfXbmeThRxNGFbfToDmMB9dWbZqdGIoVxIDSVxaxim0IGhjOfW + OkI6nw31Whbb8qShUYd++nAtzTmUcNRyOpfxIHfpkEss+2JmWfkuiabfBG4xdLswa3ie706fBbicBxSX + iVVnHb+PTtfw0Y9x9NIQKsj3fM5atnBEQQgt6cNABtHaUEZXzhEOUEQVtd/8FrQhR7Gfv4wXWXC6fc7P + YCbqLAHUp4otfMY6tik0B7fhfPpzKa1N1MC+YFz02AIBAIQpYCfl5NBb03BI5XvsZQflZNOTVjqjF6aU + AxyjjGrCpJFFC9ppGpdnFcVspogm9Db4VipxioPRdQJr49SeJhbEKVYAFjUE+TjHRNk8co/Ohgd3+Mg2 + VRQyTw6XWX7PFDoayEv14YqpYRLnkALwOFIAHkcKwONIAXgcKQCPIwXgcaQAPI4UgMeRAvA4UgAeRwrA + 40gBeBwpAI8jBeBxpAA8jhSAx5EC8DhSAB5HCsDjSAF4HCkAjyMF4HGkADyOLSuEhCxcWi1gWqOnLFvp + z2c6udyVMmCxAGpYxWds4aiF0fTTnPO4jEG6llwA2M9S1lKgsB2sUXyk04m+DNU9C6qGL1nJd5anTE8u + 41INc55V4mTN3EAI8jEvs8+2dTVbcjujNE+FLmQeSyzeZeQMAS7nfs0iOMVi/qiy6atZWnMHN+h6k2Pn + BlpUBijjEaay18ZlVY8wi3GaFnkNs5xb+dC2xw9BlnM7H2iKbQmTmWbjiwGF5DPR8GqGlgiglIkssS2C + Z1jDWA17fn7EI4Lt2KykjCd4O+FVJUxgWRJS5gvGCXcgUscCAQR5SmWzF2vZwdQES7du5glbF3eNjfdz + CRaRPMUMhWXn7GEr0wzleRYIYFFS3v4I6/ibim9V0h4/wCnyBTt31LJQuKq3HazmXQOhTAugmleSsgvf + GURrZQN8aGD3XDMcjFvT+AwVvJbklHndwO5qpgXwtcrC5vZQwscCnxALkpzksFCY46wSbgxpF8dZqjuM + aQF8muRIqv3nQbYn3ZZ9wr1L3ZQyYkwLQOuWLVayVbDty64kfv8jhKPLY9XHTSkjxrQA9G2/Yg0VMft/ + OG0LwoqpE9acFO5GKsK0AJL/zkFIUOFxwhbxvzphTVB3VdC0AJJd6FL7VzfZ0lCQ3cEex/YNI7IYyrk6 + /ibIXj7RtHmqEfowSNf26qWsYr1N73gWV9FNV8oUsES14ckINgugFzMNLJt6N1P5ynJbUhjPT3VneXew + iCcVt601R29mGtj54G6msMZSO2z9BGQYevzQlKcsXHA1whh+ZiC6fkbwS8ttySLf0MYXzSxPGVsFMMTw + osnZXGuxLamMNrzK7k90D0ZJhPGUaSZcRN8Ytgqgm0Nhlcg28ea00rgBjna6mghrbcrYKgAzWxmY2wZB + KaJmomq1Ne5JGVkN9DhSAB5HCsDjSAF4HCkAjyMF4HGkADyOFIDHkQLwOFIAHkcKwONIAXgcKQCPIwXg + caQAPI4UgMeRAvA4UgAeRwrA40gBeBxbBVDtdOxiCJpaoc/qmNi3gplebBVA8pdrEFNKoeGwhyi12Br3 + pIytAviUfU7HL0oN7xqe4/e+5VO9V7gmZWwVQCWTkr6CkJj5vGHgMxBkAW9abks5D7PX6QQBbJ8cuoPb + GEw3DZMZbrZ9onKI5/mIQTTXPEUsTAlfsdkWa7ZxK1domh18i+EpbVqwfXp4OR9puMrHaPtNAbaxLQn/ + oo1yPtRwlZ9f2CoAWQ30OKYFYKc6G4YtbkoB/ZgWgJm16q3GGVvSdbq7C9MCsH4hh4ZmSyud7u7CtAB6 + Ox2DGLpavpBDYnzCFHBTyogxLYDBTscghjacl/T/7ExngY+bUkaMaQFcTBen4xATmRuTXiS7Tvit708n + pxNEA6YFkMZ/uqgcPJzuSf2/9two9GvEr1yUMiIsaAe4ih87HYsoaUwjI2n/lsoUslX8r+FqpxMkIRYI + wM/DDHA6HlF68liSJJDCgwniHWAKlzidIAmwpCUwk1mMdE12N4yZ5Nr+LzlMZ1TCq7J4hmtckzJKWNQU + nMk0ZtHdJVG9lLcYZWM+kMo1vM5wTbFtzHTy6eaSlInHsh4YP0O4nPV8xncc1j2CxmdxArVgCnexnHXs + oczCnUMb05G+DKG9jlABrmIIa1nJdxzWPRbIbuFY2gUXoB/9AAjpTvSA5VFrxU/5KRDWvYuGCL/hxxGg + P/0Npoy9/XU29cG6qZPRZ4O4jOOmlHGjPZIkIwXgcaQAPI4UgMeRAvA4rhVAhdMGuBZrU8a1Avi30wa4 + FmuHqbtUAAUsdNoEl7KLRZbez4UCCLOJCfIToECIDUzUvTmsOqZbAmdbvKVaDXvZ6qp5xUaZafEc4BoK + 2Gr5vGLTAvg/Siw26WzhXw0iF3PhJ0CSTBqoANzau+40+tOlQQrA30Bm3SSfgO6UaZACyCHLaRNcSlMy + dYZokAK4wGkDXIv+lGmQArjSaQNcio8husM0QAG0ayCTrpJPRwbpDtPgBODnPtKcNsKV+BlroFmnwQng + WoY5bYJLuZErDIRqYAIYzCRXDfF0D1cx3tDDTMbKTBaRws+43/KN3M8GUrmFuw2mTAMRQBqX8CsuctoM + F5JOP+4yUTE2LYA8i7sn4w3MpQd5dGxoXyv629ynmUouPelHB1MpY1oAM22NZENmjtMGaKKhvVYSi5EC + 8DhSAB5HCsDjSAF4HCkAjyMF4HGkADyOFIDHkQLwOFIAHkcKwONIAXgcKQCPIwXgcaQAPI7/zHRCq1bU + lbid2CftPzOUsCHMZpdYQeySHv6c6OFhp+2SJInCmGN/06LI4Q7LVtWWuJvt0aPMKv/x6HJcOznutGWS + JFDFxuixf6O/0dLISTnLnLZNkgQ2szd6nPGZv9XitGjp7x3L16CSuI0wb0WP/eHmC/y9D2QsiTjsYb7T + 9klsZjWfR48ztrZf458YbjnXH4w4vRhTQJCcfRznqZiifva8WVV+GLg0a3nEqYzJHHLaSolNlDGV/dGz + zJ3d3wQ/TAh2eCilKuK8h3HscdpSiQ0c52FWR898oZaTny0+vVnXpoMX+0ujC+8UsYiWLt7pTmKENTzI + lpjz5n+78snF4ehubUNWVl5Y2TPiWcUyVtOU1nI2/llANRuZxUsUx7g12ThwzKOVELO05Nicf88vqbf8 + Vmv60ou2NJarcjRAQlRQyDbWs7deR1/mtq4/er2g9jgmn7+/2Za/nBjptNkSu2myseMNb+yJnMW82qsr + R/w9mFLxw7AcI3DW4gu1eDvvphdjKnp18vY1obs+qVxRfUFNW1kCPBvJ2NX+3qFPPFqn31/hQU9rtOH6 + kt+W9wvKnOCswUfm1ux53d94tjjeR5HHU3afX3hjxRDyyuzbhV2SBDJqAhszPm02v/3Xs63d2kUikUgk + EolEIpFIJA2R/wdOE2BbbcdkRgAAAABJRU5ErkJggigAAACAAAAAAAEAAAEAIAAAAAAAAAABABMLAAAT + CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAICAgAFPT08sPz8/bjMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4A+Pj5xTU1NMnR0dAIA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAImJiQBHR0dEOTk5xzQ0NP4zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk50UVFRVGOjo4AAAAAAAAAAAAAAAAAAAAAAAAAAABs + bGwEPj4+jzQ0NP4zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/z4+PqFdXV0IAAAAAAAAAAAAAAAAZmZmAT09PZ8zMzP/MzMz/zMzM/9iYmL/r6+v/9jY2P/k + 5OT/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5OTk/9ra2v+zs7P/aWlp/zMzM/8zMzP/MzMz/zw8PLJ6enoEAAAAAAAAAABC + QkJqMzMz/zMzM/88PDz/tbW1//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////wcHB/0FBQf8zMzP/MzMz/z8/P34AAAAAWlpaEjY2Nu4zMzP/NjY2/8XFxf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////0tLS/zo6Ov8zMzP/NTU19lFRUR8/ + Pz9xMzMz/zMzM/+Kior///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////m5ub/zMzM/8zMzP/Pj4+hjo6OsAzMzP/NTU1/+Xl5f////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////w8PD/Ozs7/zMzM/85 + OTnVQUFB+zMzM/9TU1P///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////9jY2P/MzMz/zY2Nv01NTX/MzMz/2lpaf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////3p6ev8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ////////////////////////////////////uLi4/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1 + tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1 + tbX/vb29/+Li4v////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////9zc3P+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1 + tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7e3t//MzMz/9/f3//////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////86 + Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NTU1/2lpaf/h4eH///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9DQ0P/p6en//7+/v////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + /////////////////////////////////////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0NDQ//c3Nz///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/iYmJ//////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + ////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/1tbW//+ + /v7///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////52dnf8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/wsLC//////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/83Nzf////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9qamr/////////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/n5+f//////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////+dnZ3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/z8/P//8/Pz///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/OTk5//f39////////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////9hYWH/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9b + W1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1FRUf80NDT/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5SUlP////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////sLCw/1tbW/9b + W1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9b + W1v/W1tb/1tbW/9aWlr/Pz8//zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////8DAwP81NTX/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////z8/P/Z2dn/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////2hoaP8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+UlJT///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////Nzc3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////9zc3P8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////94eHj/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/lJSU//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/2 + 9vb///////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////c + 3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + ///////////////////////////////////////////////x8fH/vLy8/6Wlpf+jo6P/o6Oj/6Ojo/+j + o6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo//9/f3/////////////////eHh4/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5SUlP////////////////////////////////////////////r6+v/I + yMj/qKio/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+j + o6P/o6Oj/6Ojo/+jo6P/o6Oj/6enp//FxcX/+Pj4//////////////////////////////////////// + /////////////////////v7+/9XV1f+tra3/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+j + o6P/o6Oj/6Ojo/+jo6P/0dHR/////////////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85 + OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v////////////////////////////////////////////////////////////////////////////9 + /f3/nJyc/z09Pf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/NDQ0//v7+/////////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////// + //////////////////////////////++vr7/SkpK/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9G + Rkb/t7e3/////////////////////////////////////////////////9vb2/9eXl7/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+ZmZn///////////// + ////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + /////////////////////////////////////v7+/4SEhP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/80NDT/+/v7/////////////////3h4eP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT/////////////////////////////////s7Oz/zU1Nf8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/80NDT/q6ur//////////////////////// + ///////////////a2tr/QEBA/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5mZmf/////////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/OTk5//b29v///////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr///////////////////////////////////////////////////////////////////////C + wsL/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zQ0NP/7+/v/////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP// + /////////////////////////+rq6v89PT3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/86Ojr/5OTk/////////////////////////////f39/1tbW/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/mZmZ//////// + /////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + /////////////////////////////////////////25ubv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NDQ0//v7+/////////////////94 + eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU////////////////////////////oKCg/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+Wlpb///////////// + ///////////////Q0ND/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+ZmZn/////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zk5Of/29vb///////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + ////RERE/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/80NDT/+/v7/////////////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+U + lJT///////////////////////////92dnb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2xsbP///////////////////////////6enp/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5mZmf// + ///////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP/7+/v///////////// + ////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP///////////////////////////2xsbP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////// + ////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/mZmZ/////////////////9zc3P8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/85OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/R0dH/2pqav9ra2v/a2tr/2tra/9r + a2v/a2tr/2tra/9ra2v/a2tr//z8/P////////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/lJSU////////////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/89 + PT3/aGho/21tbf9tbW3/bW1t/21tbf9tbW3/bW1t/21tbf9tbW3/bW1t/21tbf9paWn/Pj4+/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////////////////////+dnZ3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zY2Nv9gYGD/a2tr/2tra/9ra2v/a2tr/2tra/9ra2v/a2tr/2tra/+1 + tbX/////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/2pqav/39/f///////////////////////////////////////////////////////////// + /////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////9s + bGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/SEhI/+bm5v////////////////////////////////// + ///////////////////////////////q6ur/TU1N/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv// + /////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/82Njb/x8fH//////// + ///////////////////////////////////////////////////////////////c3Nz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/OTk5//b29v///////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/xcXF//////////////////////// + ////////////////////////////////////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5SUlP///////////////////////////2xsbP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+T + k5P///////////////////////////////////////////////////////////////////////////+a + mpr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi////////////////////////////nZ2d/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2FhYf////////////////////////////////////////////////// + /////////////////////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + /////////////////////////////////////////////////////////zo6Ov8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM//R0dH///////////////////////////////////////////////////////////// + //////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////////////////////// + ////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5+fn/////////////////////////////////// + /////////////////////////////////////////6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9i + YmL///////////////////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//////// + ////////////////////////////////////////////////////////////////////3Nzc/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + ////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9HR0f////////////////// + /////////////////////////////////////////////////////////3h4eP8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+UlJT///////////////////////////9sbGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/n5+f//////////////////////////////////////////////////////////////////////// + ////pqam/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv///////////////////////////52dnf8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9tbW3///////////////////////////////////////////// + ///////////////////////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////86Ojr/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/0dHR//////////////////////////////////////////////////////// + ////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP////////////////// + /////////2xsbP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+fn5////////////////////////////// + //////////////////////////////////////////////+mpqb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/YmJi////////////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/21tbf// + /////////////////////////////////////////////////////////////////////////9zc3P8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + /////////////////////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//R0dH///////////// + //////////////////////////////////////////////////////////////94eHj/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/lJSU////////////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5+fn/////////////////////////////////////////////////////////////////// + /////////6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////////////////////+d + nZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//////////////////////////////////////// + ////////////////////////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/2 + 9vb///////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ////////////////////////////////////////////////////////////////////Ojo6/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/9HR0f////////////////////////////////////////////////// + /////////////////////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////// + //////////////9sbGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/n5+f//////////////////////// + ////////////////////////////////////////////////////pqam/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/2JiYv///////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9t + bW3////////////////////////////////////////////////////////////////////////////c + 3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/0dHR//////// + ////////////////////////////////////////////////////////////////////eHh4/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5SUlP///////////////////////////2xsbP8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+fn5////////////////////////////////////////////////////////////// + //////////////+mpqb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////////////////////// + ////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/21tbf////////////////////////////////// + /////////////////////////////////////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85 + OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v//////////////////////////////////////////////////////////////////////zo6Ov8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM//R0dH///////////////////////////////////////////// + //////////////////////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////// + ////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5+fn/////////////////// + /////////////////////////////////////////////////////////6ampv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9iYmL///////////////////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/bW1t//////////////////////////////////////////////////////////////////////// + ////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9HR0f// + /////////////////////////////////////////////////////////////////////////3h4eP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////9sbGz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/n5+f//////////////////////////////////////////////////////// + ////////////////////pqam/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv////////////////// + /////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9tbW3///////////////////////////// + ///////////////////////////////////////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/OTk5//b29v///////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////86 + Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/0dHR//////////////////////////////////////// + ////////////////////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP// + /////////////////////////2xsbP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+fn5////////////// + //////////////////////////////////////////////////////////////+mpqb/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/YmJi////////////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/21tbf////////////////////////////////////////////////////////////////// + /////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + /////////////////////////////////////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//R + 0dH///////////////////////////////////////////////////////////////////////////94 + eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU////////////////////////////bGxs/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5+fn/////////////////////////////////////////////////// + /////////////////////////6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////// + //////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//////////////////////// + ////////////////////////////////////////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zk5Of/29vb///////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + ////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9DQ0P////////////////////////////////// + /////////////////////////////////////////3Z2dv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+U + lJT///////////////////////////9sbGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/np6e//////// + ////////////////////////////////////////////////////////////////////paWl/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2JiYv///////////////////////////52dnf8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + ///////////////b29v/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/p6en///////////////////////////////////////////////////////////////////////8 + /Pz/UVFR/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP///////////////////////////2xsbP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/91dXX///////////////////////////////////////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////// + ////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/0lJSf/5+fn///////////// + /////////////////////////////////////////////////////////7Kysv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/85OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/89PT3/qamp/9PT0//U1NT/1NTU/9TU1P/U + 1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/U1NT/y8vL/3R0dP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/lJSU////////////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP+N + jY3/0NDQ/9TU1P/U1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/R0dH/k5OT/zU1Nf8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////////////////////+dnZ3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/21tbf/Jycn/1NTU/9TU1P/U1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/U + 1NT/1NTU/9PT0/+urq7/QEBA/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////9s + bGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv// + /////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/OTk5//b29v///////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////88PDz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5aWlv///////////////////////////25ubv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/ZGRk////////////////////////////n5+f/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/86Ojr/+Pj4//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + /////////////////////////////////////////////////////////1NTU/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys//////////////////////// + ////hYWF/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/97 + e3v///////////////////////////+2trb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0pKSv////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + ////////////////////kJCQ/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zY2Nv/n5+f////////////////////////////CwsL/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/7m5uf///////////////////////////+3t7f86 + Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/h4eH//////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + ///////////////////////////////////////////////////////////////s7Oz/RUVF/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/jIyM//////////////////////// + //////////39/f9lZWX/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9e + Xl7/+/v7/////////////////////////////////5WVlf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0FBQf/n5+f///////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + ///////////////////////////////S0tL/RERE/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/3d3d//5+fn//////////////////////////////////////+3t7f9cXFz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/V1dX/+np6f////////////////////////////////// + /////Pz8/39/f/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9CQkL/zMzM//////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ///////////////////////////////////////////////////////////////////////////////s + 7Oz/kJCQ/1JSUv89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89 + PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/QkJC/2lpaf+6urr//v7+//////////////////////// + //////////////////////////n5+f+mpqb/Xl5e/z8/P/89PT3/PT09/z09Pf89PT3/PT09/z09Pf89 + PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf8/Pz//XFxc/6Kiov/3 + 9/f//////////////////////////////////////////////////v7+/7+/v/9ra2v/Q0ND/z09Pf89 + PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89 + PT3/PT09/z09Pf9RUVH/jY2N/+np6f////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////////////////////////////////39/f/8/Pz//Pz8//z8/P/8 + /Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/+ + /v7///////////////////////////////////////////////////////////////////////////// + /////v7+//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8 + /Pz//Pz8//z8/P/8/Pz//Pz8//7+/v////////////////////////////////////////////////// + /////////////////////////////////////Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8 + /Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//f39//////////////////////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + ///////////////////////////////IyMj/gICA/3Z2dv+lpaX/+Pj4//////////////////////// + /////////////////////////////////////////8rKyv+BgYH/dnZ2/6Ghof/19fX///////////// + ///////////////////////////////+/v7/4eHh/66urv+MjIz/eXl5/3Jycv94eHj/i4uL/66urv/k + 5OT///////////////////////////////////////////////////////////////////////z8/P/p + 6en/2NjY/9jY2P/k5OT/+Pj4////////////////////////////3t7e/4iIiP92dnb/pKSk//j4+P// + ///////////////////////////////////////////////////////////////////////////////x + 8fH/vLy8/5OTk/97e3v/c3Nz/3h4eP+Li4v/sLCw/+Xl5f////////////////////////////////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ////////////////////////////////////////////////////////////////////t7e3/zU1Nf8z + MzP/MzMz/zMzM/9qamr//v7+//////////////////////////////////////////////////////+n + p6f/NTU1/zMzM/8zMzP/MzMz/15eXv/6+vr/////////////////////////////////wcHB/19fX/80 + NDT/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zU1Nf9lZWX/yMjI//////////////////////// + //////////////////////////v7+/+dnZ3/SUlJ/zMzM/8zMzP/MzMz/zMzM/88PDz/b29v/9nZ2f// + /////////+Li4v8/Pz//MzMz/zMzM/8zMzP/cnJy//7+/v////////////////////////////////// + ///////////////////////////////o6Oj/hISE/zs7O/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/NTU1/2lpaf/Pz8////////////////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////9VVVX/MzMz/zMzM/8zMzP/MzMz/zMzM//Q0ND///////////// + ////////////////////////////////////0dHR/zc3N/8zMzP/MzMz/zMzM/8zMzP/MzMz/8fHx/// + ////////////////////9/f3/3t7e/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/80NDT/hoaG//r6+v//////////////////////////////////////hISE/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/RERE//f39///////kZGR/zMzM/8zMzP/MzMz/zMzM/8z + MzP/3d3d////////////////////////////////////////////////////////////vLy8/z8/P/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP+Pj4///Pz8//////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v/////////////////////////////////////////////////////////////////+/v7/zc3N/8z + MzP/MzMz/zMzM/8zMzP/MzMz/6+vr/////////////////////////////////////////////j4+P9U + VFT/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/19fX//////////////////r6+v9sbGz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/f39///////// + /////////////////////////+bm5v82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/83 + Nzf/8PDw//////91dXX/MzMz/zMzM/8zMzP/MzMz/zMzM//CwsL///////////////////////////// + /////////////////////////7W1tf82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9/f3///v7+//////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ///////////////////////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys//////// + ////////////////////////////////////lJSU/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/1hYWP/9 + /f3/////////////////lJSU/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/0xMTP+Hh4f/mZmZ/4eHh/9Q + UFD/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/yMjI////////////////////////////ubm5/zMzM/8z + MzP/MzMz/zMzM/82Njb/iIiI/5ubm/9/f3//ampq/7W1tf///////////3Nzc/8zMzP/MzMz/zMzM/8z + MzP/MzMz/7+/v//////////////////////////////////////////////////a2tr/OTk5/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0RERP9aWlr/S0tL/zQ0NP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+o + qKj//////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////j4+P82 + Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+srKz//////////////////////////////////////9jY2P84 + ODj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/t7e3/////////////////+bm5v85OTn/MzMz/zMzM/8z + MzP/MzMz/zMzM/+Ojo7/+fn5//////////////////z8/P+urq7/Pj4+/zMzM/8zMzP/MzMz/zMzM/+K + ior///////////////////////////+hoaH/MzMz/zMzM/8zMzP/MzMz/3d3d/////////////////// + ////////////////////c3Nz/zMzM/8zMzP/MzMz/zMzM/8zMzP/v7+///////////////////////// + /////////////////////v7+/2lpaf8zMzP/MzMz/zMzM/8zMzP/MzMz/0JCQv+9vb3/+/v7///////+ + /v7/1tbW/1lZWf8zMzP/MzMz/zMzM/8zMzP/MzMz/0BAQP/w8PD///////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + ////////////////////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/6ysrP// + ///////////////////////////////7+/v/XV1d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/15eXv/9 + /f3/////////////////l5eX/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//7+/v////////////////// + ///////////////d3d3/UFBQ/zMzM/8zMzP/MzMz/6Ojo////////////////////////////5eXl/8z + MzP/MzMz/zMzM/8zMzP/lZWV//////////////////////////////////////9zc3P/MzMz/zMzM/8z + MzP/MzMz/zMzM/+/v7/////////////////////////////////////////////b29v/NDQ0/zMzM/8z + MzP/MzMz/zMzM/82Njb/z8/P////////////////////////////8PDw/0tLS/8zMzP/MzMz/zMzM/8z + MzP/MzMz/6Wlpf////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra//////////////////////////////////////////////////////////////////4 + +Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys/////////////////////////////////6CgoP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/84ODj/1tbW//////////////////////9cXFz/MzMz/zMzM/8z + MzP/MzMz/zMzM//Kysr////////////////////////////////////////////u7u7/hISE/2dnZ/+X + l5f/+vr6////////////////////////////lZWV/zMzM/8zMzP/MzMz/zMzM/+ampr///////////// + /////////////////////////3Nzc/8zMzP/MzMz/zMzM/8zMzP/MzMz/7+/v/////////////////// + /////////////////////////5ycnP8zMzP/MzMz/zMzM/8zMzP/MzMz/3Nzc/////////////////// + ////////////////////q6ur/zMzM/8zMzP/MzMz/zMzM/8zMzP/ZmZm//////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////j4+P82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+s + rKz////////////////////////////a2tr/Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5qamv// + ////////////////////+fn5/zw8PP8zMzP/MzMz/zMzM/8zMzP/NDQ0/7S0tP++vr7/vr6+/76+vv++ + vr7/vr6+/76+vv++vr7/vr6+/7+/v//Ly8v/6urq//////////////////////////////////////+V + lZX/MzMz/zMzM/8zMzP/MzMz/5qamv//////////////////////////////////////c3Nz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/vr6+////////////////////////////////////////////dHR0/zMzM/8z + MzP/MzMz/zMzM/8zMzP/sbGx///////////////////////////////////////p6en/MzMz/zMzM/8z + MzP/MzMz/zMzM/9AQED//Pz8////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + ////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/6ysrP//////////////////////7+/v/1JSUv8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9tbW3//f39///////////////////////u7u7/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/81 + NTX/ZmZm/+rq6v///////////////////////////5WVlf8zMzP/MzMz/zMzM/8zMzP/mpqa//////// + //////////////////////////////9zc3P/MzMz/zMzM/8zMzP/MzMz/zMzM/+4uLj///////////// + //////////////////////////////9eXl7/MzMz/zMzM/8zMzP/MzMz/zMzM//Pz8////////////// + //////////////////////////////87Ozv/MzMz/zMzM/8zMzP/MzMz/zY2Nv/w8PD///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ///////////////////////////////////////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8z + MzP/rKys/////////////////+Dg4P9YWFj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/W1tb//Pz8/// + /////////////////////////+np6f8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/fHx8//////////////////////// + ////lZWV/zMzM/8zMzP/MzMz/zMzM/+ampr//////////////////////////////////////3Nzc/8z + MzP/MzMz/zMzM/8zMzP/MzMz/62trf///////////////////////////////////////////1lZWf8z + MzP/MzMz/zMzM/8zMzP/MzMz/9bW1v///////////////////////////////////////////0FBQf8z + MzP/MzMz/zMzM/8zMzP/NDQ0/+zs7P///////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////j4+P82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/9mZmb/iYmJ/4KCgv9lZWX/NjY2/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2JiYv/v7+//////////////////////////////////8/Pz/zQ0NP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9NTU3///////////////////////////+VlZX/MzMz/zMzM/8zMzP/MzMz/5qamv// + ////////////////////////////////////c3Nz/zMzM/8zMzP/MzMz/zMzM/8zMzP/mZmZ//////// + ////////////////////////////////////ZGRk/zMzM/8zMzP/MzMz/zMzM/8zMzP/x8fH//////// + ///////////////////////////////7+/v/NjY2/zMzM/8zMzP/MzMz/zMzM/84ODj/9PT0//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + ////////////////////////////////////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/83Nzf/mpqa/+np6f// + ///////////////////////////////9/f3/RkZG/zMzM/8zMzP/MzMz/zMzM/8zMzP/m5ub/6urq/+r + q6v/q6ur/6urq/+rq6v/q6ur/6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/01NTf////////////////// + /////////5WVlf8zMzP/MzMz/zMzM/8zMzP/mpqa//////////////////////////////////////9z + c3P/MzMz/zMzM/8zMzP/MzMz/zMzM/92dnb///////////////////////////////////////////+A + gID/MzMz/zMzM/8zMzP/MzMz/zMzM/+enp7//////////////////////////////////////9fX1/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0pKSv////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + ///////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5/4qKiv/09PT///////////////////////////9y + cnL/MzMz/zMzM/8zMzP/MzMz/zMzM/+zs7P/////////////////////////////////ysrK/zMzM/8z + MzP/MzMz/zMzM/8zMzP/aWlp////////////////////////////lZWV/zMzM/8zMzP/MzMz/zMzM/+a + mpr//////////////////////////////////////3Nzc/8zMzP/MzMz/zMzM/8zMzP/MzMz/0NDQ//5 + +fn//////////////////////////////////////7CwsP8zMzP/MzMz/zMzM/8zMzP/MzMz/1VVVf/8 + /Pz/////////////////////////////////ioqK/zMzM/8zMzP/MzMz/zMzM/8zMzP/enp6//////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////j4+P82Njb/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/1dXV//r6+v//////////////////////7a2tv8zMzP/MzMz/zMzM/8zMzP/MzMz/1FRUf/z + 8/P///////////////////////v7+/9mZmb/MzMz/zMzM/8zMzP/MzMz/zMzM/+jo6P///////////// + //////////////+VlZX/MzMz/zMzM/8zMzP/MzMz/5qamv////////////////////////////////// + ////c3Nz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5ycnP/////////////////z8/P/0dHR/+7u7v// + ////7+/v/zs7O/8zMzP/MzMz/zMzM/8zMzP/MzMz/5iYmP/+/v7//////////////////////8fHx/84 + ODj/MzMz/zMzM/8zMzP/MzMz/zMzM//BwcH///////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + ////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2VlZf/+/v7///////////// + ////+fn5/05OTv8zMzP/MzMz/zMzM/8zMzP/MzMz/1lZWf/FxcX/8vLy//Pz8//Ozs7/aGho/zMzM/8z + MzP/MzMz/zMzM/8zMzP/Pz8//+/v7////////////////////////////5WVlf8zMzP/MzMz/zMzM/8z + MzP/mpqa//////////////////////////////////////9zc3P/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/NDQ0/2RkZP99fX3/YmJi/zk5Of8zMzP/PDw8/7y8vP//////jIyM/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/3Jycv/CwsL/29vb/8zMzP+NjY3/ODg4/zMzM/8zMzP/MzMz/zMzM/8zMzP/W1tb//39/f// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ///////////////////////////////////////////////////////////////4+Pj/NjY2/zMzM/8z + MzP/MzMz/zMzM/8zMzP/pKSk//Ly8v/y8vL/8vLy//Ly8v/u7u7/4eHh/8XFxf+RkZH/Pz8//zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/8LCwv//////////////////////xMTE/zU1Nf8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/82Njb/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+oqKj///////////// + ////9vb2/3Nzc/88PDz/NjY2/zMzM/8zMzP/MzMz/zMzM/82Njb/OTk5/0ZGRv92dnb/7e3t//////// + /////////3Nzc/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/RUVF//v7+//z8/P/UFBQ/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zs7O//W1tb///////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////j4+P82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+srKz///////////// + ///////////////////////////////c3Nz/Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/f39///////// + ////////////////////paWl/zQ0NP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/hoaG//7+/v////////////////+2trb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+goKD/////////////////fn5+/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/+Pj4///////f39//SUlJ/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/86Ojr/v7+///////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v/////////////////////////////////////////////////////////////////+Pj4/zY2Nv8z + MzP/MzMz/zMzM/8zMzP/MzMz/6ysrP////////////////////////////////////////////////9s + bGz/MzMz/zMzM/8zMzP/MzMz/zMzM/9cXFz/////////////////////////////////vLy8/0ZGRv8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/Ozs7/6SkpP/+/v7///////////// + /////////9zc3P88PDz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NjY2/8nJyf// + //////////////+tra3/MzMz/zMzM/8zMzP/MzMz/0pKSv9dXV3/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/4eHh//////////////////q6ur/bW1t/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/VlZW/9TU1P////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ///////////////////////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys//////// + /////////////////////////////////////////3BwcP8zMzP/MzMz/zMzM/8zMzP/MzMz/1NTU/// + ////////////////////////////////////8vLy/6Kiov9aWlr/NTU1/zMzM/8zMzP/MzMz/zMzM/80 + NDT/SUlJ/46Ojv/m5ub//////////////////////////////////////+fn5/+4uLj/cHBw/zMzM/8z + MzP/MzMz/zMzM/9zc3P/srKy/7S0tP/d3d3///////////////////////j4+P9kZGT/MzMz/zMzM/84 + ODj/urq6//Dw8P9ycnL/NDQ0/zMzM/8zMzP/MzMz/01NTf+oqKj//Pz8///////////////////////+ + /v7/ysrK/3d3d/8+Pj7/MzMz/zMzM/8zMzP/MzMz/zMzM/84ODj/Z2dn/7W1tf/6+vr///////////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////j4+P82 + Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+srKz////////////////////////////////////////////r + 6+v/Pz8//zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////////////////////////////////////// + ///////////////w8PD/0dHR/8HBwf++vr7/ysrK/+Xl5f/+/v7///////////////////////////// + //////////////////////////////+VlZX/MzMz/zMzM/8zMzP/MzMz/5qamv////////////////// + //////////////////////////z8/P/Pz8//wMDA/+jo6P/////////////////k5OT/wsLC/8HBwf/d + 3d3//v7+//////////////////////////////////////////////////v7+//d3d3/xsbG/729vf/D + w8P/19fX//b29v////////////////////////////////////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + ////////////////////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/6urq//9 + /f3//f39//39/f/9/f3//f39//v7+//z8/P/xMTE/1VVVf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+N + jY3///////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////5WVlf8z + MzP/MzMz/zMzM/8zMzP/mpqa//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra//////////////////////////////////////////////////////////////////4 + +Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/Pj4+/0VFRf9FRUX/RUVF/0VFRf9ERET/Pj4+/zQ0NP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NDQ0/9jY2P////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////lpaW/zMzM/8zMzP/MzMz/zMzM/+ampr///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////r6+v82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+C + goL///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////+c + nJz/MzMz/zMzM/8zMzP/MzMz/6Kiov////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////0tLS/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/ampq//f39/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////76+vv8zMzP/MzMz/zMzM/8zMzP/xMTE//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////oaGh/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/PT09/5iYmP/7 + +/v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////f39/4aGhv85OTn/Ozs7/4+Pj//+/v7///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + ///////////////9/f3/sLCw/2dnZ/9PT0//TU1N/01NTf9NTU3/TU1N/01NTf9NTU3/TU1N/01NTf9N + TU3/T09P/1ZWVv9lZWX/gICA/7CwsP/w8PD///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////X19f/29vb///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////fHx8/zMzM/8z + MzP/Ozs7/zMzM/9fX1////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////9wcHD/MzMz/zMzM/89PT3cMzMz/z4+Pv/39/f///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////Pz8/0pKSv8z + MzP/OTk57Dw8PJUzMzP/MzMz/7W1tf////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////Gxsb/MzMz/zMzM/87OzuqS0tLNjQ0NP0zMzP/TExM//Hx8f// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////9/f3/1dXV/8z + MzP/MzMz/0VFRUmNjY0APDw8rTMzM/8zMzP/ZGRk//Hx8f////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////b29v9wcHD/MzMz/zMzM/86OjrAgYGBAgAAAABTU1MYNzc34zMzM/8z + MzP/TExM/7a2tv/39/f///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////r6+v++vr7/U1NT/zMzM/8z + MzP/NjY27E1NTSMAAAAAAAAAAAAAAABKSkoqNzc34jMzM/8zMzP/MzMz/z4+Pv9gYGD/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9iYmL/QUFB/zMzM/8zMzP/MzMz/zY2NutHR0c3AAAAAAAAAAAAAAAAAAAAAAAAAABT + U1MXPDw8rDQ0NP0zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP47 + Ozu5TU1NIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACNjY0AS0tLNTw8PJU9PT3bOzs7/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/Ojo6/0BAQOM8PDycR0dHPo+PjwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////////////////////// + ////////////////////+AAAAAAAAAAAAAAAAAAAH+AAAAAAAAAAAAAAAAAAAAfAAAAAAAAAAAAAAAAA + AAADgAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAHA + AAAAAAAAAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAB/AAAAAAAAAAAAAAAAAAAA////////////////// + //////////////////////////////////////////////8oAAAAQAAAAIAAAAABACAAAAAAAABAAAAT + CwAAEwsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgICAAENDQyYzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQEJCQil0dHQAAAAAAAAAAAAAAAAAPz8/JTc3N8Iz + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/Nzc3yD8/PyoA + AAAAQkJCGzU1NedWVlb/xMTE/+/v7//y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y + 8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y + 8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y + 8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/v + 7+//x8fH/1paWv81NTXsQUFBIDg4OJxKSkr/8PDw//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////09PT/T09P/zc3N6Y4ODjum5ub//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////6Ojo/81NTX0MzMz/7W1tf// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////+9 + vb3/MzMz/zMzM/+1tbX///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////++vr7/MzMz/zMzM/+1 + tbX/////////////////////////////////29vb/9ra2v/a2tr/2tra/9ra2v/a2tr/2tra/9ra2v/a + 2tr/2tra/9ra2v/a2tr/5+fn//////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////k5OT/2tra/9ra2v/a + 2tr/2tra/9ra2v/a2tr/2tra/9ra2v/a2tr/2tra/9ra2v/g4OD//f39//////////////////////// + ////vr6+/zMzM/8zMzP/tbW1/////////////////////////////////zc3N/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9wcHD/9vb2//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////aGho/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/1RUVP/h + 4eH//////////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////83 + Nzf/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5aWlv// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////2hoaP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/ZWVl//////////////////////++vr7/MzMz/zMzM/+1tbX///////////// + ////////////////////Nzc3/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9mZmb///////////////////////////////////////////////////////////// + //////////////////////////////////////////////9oaGj/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zg4OP/8/Pz/////////////////vr6+/zMzM/8z + MzP/tbW1/////////////////////////////////66urv+tra3/ra2t/62trf+tra3/ra2t/62trf+t + ra3/ra2t/62trf+RkZH/NDQ0/zMzM/8zMzP/Y2Nj//////////////////////////////////////// + ////////////////////////////////////////////////////////////////////wsLC/62trf+t + ra3/ra2t/62trf+tra3/ra2t/62trf+tra3/ra2t/6Ojo/9AQED/MzMz/zMzM/82Njb/+/v7//////// + /////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////////////////////// + /////////////////////////////////////////1FRUf8zMzP/MzMz/2NjY/////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////hISE/zMzM/8z + MzP/NjY2//v7+/////////////////++vr7/MzMz/zMzM/+1tbX///////////////////////////// + //////////////////////////////////////////////////////////////9VVVX/MzMz/zMzM/9j + Y2P///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////4iIiP8zMzP/MzMz/zY2Nv/7+/v/////////////////vr6+/zMzM/8zMzP/tbW1//////// + //////////////////////////7+/v+ysrL/cnJy/2tra/9ra2v/a2tr/2tra/9ra2v/a2tr//39/f// + ////VVVV/zMzM/8zMzP/Y2Nj/////////////////+/v7/+Pj4//bGxs/2tra/9ra2v/a2tr/2tra/9r + a2v/a2tr/2tra/9ra2v/bGxs/46Ojv/t7e3//////////////////////87Ozv96enr/a2tr/2tra/9r + a2v/a2tr/2tra/9ra2v/2tra//////+IiIj/MzMz/zMzM/82Njb/+/v7/////////////////76+vv8z + MzP/MzMz/7W1tf////////////////////////////////+enp7/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM//9/f3//////1VVVf8zMzP/MzMz/2NjY/////////////r6+v9WVlb/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/U1NT//j4+P///////////8zMzP82 + Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/8zMzP//////iIiI/zMzM/8zMzP/NjY2//v7+/// + //////////////++vr7/MzMz/zMzM/+1tbX/////////////////////////////////RkZG/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP//f39//////9VVVX/MzMz/zMzM/9jY2P////////////F + xcX/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//A + wMD///////////93d3f/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//MzMz//////4iIiP8z + MzP/MzMz/zY2Nv/7+/v/////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////// + /////////zc3N/8zMzP/MzMz/zMzM/9GRkb/T09P/09PT/9PT0//T09P//39/f//////VVVV/zMzM/8z + MzP/Y2Nj////////////tra2/zMzM/8zMzP/MzMz/zU1Nf9PT0//UFBQ/1BQUP9QUFD/UFBQ/09PT/82 + Njb/MzMz/zMzM/8zMzP/sbGx////////////aGho/zMzM/8zMzP/MzMz/z8/P/9PT0//T09P/09PT/9P + T0//09PT//////+IiIj/MzMz/zMzM/82Njb/+/v7/////////////////76+vv8zMzP/MzMz/7W1tf// + //////////////////////////////83Nzf/MzMz/zMzM/9lZWX//f39//////////////////////// + /////////1VVVf8zMzP/MzMz/2NjY////////////7a2tv8zMzP/MzMz/zMzM/+wsLD///////////// + ////////////////////tLS0/zMzM/8zMzP/MzMz/7Gxsf///////////2hoaP8zMzP/MzMz/z8/P//x + 8fH/////////////////////////////////iIiI/zMzM/8zMzP/NjY2//v7+/////////////////++ + vr7/MzMz/zMzM/+1tbX/////////////////////////////////Nzc3/zMzM/8zMzP/goKC//////// + //////////////////////////////9VVVX/MzMz/zMzM/9jY2P///////////+2trb/MzMz/zMzM/8z + MzP/z8/P/////////////////////////////////9LS0v8zMzP/MzMz/zMzM/+xsbH///////////9o + aGj/MzMz/zMzM/9QUFD//////////////////////////////////////4iIiP8zMzP/MzMz/zY2Nv/7 + +/v/////////////////vr6+/zMzM/8zMzP/tbW1/////////////////////////////////zc3N/8z + MzP/MzMz/4KCgv//////////////////////////////////////VVVV/zMzM/8zMzP/Y2Nj//////// + ////tra2/zMzM/8zMzP/MzMz/8/Pz//////////////////////////////////S0tL/MzMz/zMzM/8z + MzP/sbGx////////////aGho/zMzM/8zMzP/UFBQ//////////////////////////////////////+I + iIj/MzMz/zMzM/82Njb/+/v7/////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////83Nzf/MzMz/zMzM/+CgoL//////////////////////////////////////1VVVf8z + MzP/MzMz/2NjY////////////7a2tv8zMzP/MzMz/zMzM//Pz8////////////////////////////// + ////0tLS/zMzM/8zMzP/MzMz/7Gxsf///////////2hoaP8zMzP/MzMz/1BQUP////////////////// + ////////////////////iIiI/zMzM/8zMzP/NjY2//v7+/////////////////++vr7/MzMz/zMzM/+1 + tbX/////////////////////////////////Nzc3/zMzM/8zMzP/goKC//////////////////////// + //////////////9VVVX/MzMz/zMzM/9jY2P///////////+2trb/MzMz/zMzM/8zMzP/z8/P//////// + /////////////////////////9LS0v8zMzP/MzMz/zMzM/+xsbH///////////9oaGj/MzMz/zMzM/9Q + UFD//////////////////////////////////////4iIiP8zMzP/MzMz/zY2Nv/7+/v///////////// + ////vr6+/zMzM/8zMzP/tbW1/////////////////////////////////zc3N/8zMzP/MzMz/4KCgv// + ////////////////////////////////////VVVV/zMzM/8zMzP/Y2Nj////////////tra2/zMzM/8z + MzP/MzMz/8/Pz//////////////////////////////////S0tL/MzMz/zMzM/8zMzP/sbGx//////// + ////aGho/zMzM/8zMzP/UFBQ//////////////////////////////////////+IiIj/MzMz/zMzM/82 + Njb/+/v7/////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////83 + Nzf/MzMz/zMzM/93d3f//////////////////////////////////v7+/0tLS/8zMzP/MzMz/2NjY/// + /////////7a2tv8zMzP/MzMz/zMzM//ExMT/////////////////////////////////yMjI/zMzM/8z + MzP/MzMz/7Gxsf///////////2hoaP8zMzP/MzMz/0dHR//9/f3///////////////////////////// + ////fX19/zMzM/8zMzP/NjY2//v7+/////////////////++vr7/MzMz/zMzM/+1tbX///////////// + ////////////////////Nzc3/zMzM/8zMzP/NjY2/3h4eP+EhIT/hISE/4SEhP+EhIT/hISE/2lpaf8z + MzP/MzMz/zMzM/9jY2P///////////+2trb/MzMz/zMzM/8zMzP/SkpK/4KCgv+EhIT/hISE/4SEhP+E + hIT/g4OD/0xMTP8zMzP/MzMz/zMzM/+xsbH///////////9oaGj/MzMz/zMzM/8zMzP/Z2dn/4SEhP+E + hIT/hISE/4SEhP+EhIT/enp6/zY2Nv8zMzP/MzMz/zY2Nv/7+/v/////////////////vr6+/zMzM/8z + MzP/tbW1/////////////////////////////////z09Pf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/ampq////////////vLy8/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/t7e3////////////b29v/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/86Ojr//f39//////// + /////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////99fX3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/6qqqv///////////+/v7/9A + QED/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/Pj4+/+zs7P// + /////////6+vr/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/eHh4//////////////////////++vr7/MzMz/zMzM/+1tbX///////////////////////////// + ////9PT0/319ff89PT3/ODg4/zg4OP84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84ODj/RERE/5iYmP/+ + /v7/////////////////0NDQ/1paWv84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84 + ODj/WVlZ/83Nzf/////////////////+/v7/nJyc/0VFRf84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84 + ODj/ODg4/zg4OP89PT3/e3t7//Ly8v//////////////////////vr6+/zMzM/8zMzP/tbW1//////// + //////////////////////////////////////////7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+ + /v7//v7+/////////////////////////////////////////////v7+//7+/v/+/v7//v7+//7+/v/+ + /v7//v7+//7+/v/+/v7//v7+/////////////////////////////////////////////v7+//7+/v/+ + /v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//////////////////////////////////////76+vv8z + MzP/MzMz/7W1tf////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////++vr7/MzMz/zMzM/+1tbX///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////++ + vr7/MzMz/zMzM/+1tbX///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////Hx8f+9 + vb3/5+fn/////////////////////////////////9LS0v/FxcX//Pz8///////////////////////j + 4+P/wcHB/7q6uv/Ozs7/+Pj4//////////////////////////////////n5+f/r6+v/9/f3//////// + ////9/f3/7+/v//n5+f///////////////////////////////////////z8/P/T09P/u7u7/8DAwP/l + 5eX//////////////////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////9dXV3/MzMz/0FBQf/z8/P//////////////////////6urq/8zMzP/MzMz/5SUlP// + /////////9zc3P9iYmL/MzMz/zMzM/8zMzP/MzMz/0BAQP+goKD//v7+/////////////////5SUlP85 + OTn/MzMz/zU1Nf9wcHD//f39/3l5ef8zMzP/Q0ND//b29v///////////////////////////7m5uf9J + SUn/MzMz/zMzM/8zMzP/MzMz/2hoaP/i4uL///////////////////////////++vr7/MzMz/zMzM/+1 + tbX////////////////////////////8/Pz/NTU1/zMzM/8zMzP/1tbW/////////////////+Li4v87 + Ozv/MzMz/zMzM/+YmJj//////+Pj4/9BQUH/MzMz/zMzM/9OTk7/YWFh/zo6Ov8zMzP/MzMz/56env// + /////////+fn5/80NDT/MzMz/0lJSf9gYGD/YmJi//v7+/9UVFT/MzMz/zMzM//g4OD///////////// + /////////7Kysv80NDT/MzMz/zMzM/9BQUH/OTk5/zMzM/8zMzP/RkZG/+np6f////////////////// + ////vr6+/zMzM/8zMzP/tbW1/////////////////////////////Pz8/zQ0NP8zMzP/MzMz/9XV1f// + //////////7+/v9oaGj/MzMz/zMzM/8+Pj7/7e3t//////96enr/MzMz/zMzM/+Li4v//v7+///////q + 6ur/aGho/zMzM/9lZWX////////////Ozs7/MzMz/zMzM//Dw8P/////////////////U1NT/zMzM/8z + MzP/39/f//////////////////b29v9BQUH/MzMz/zQ0NP+zs7P//v7+//T09P9ycnL/MzMz/zMzM/+C + goL//////////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////z8/P80 + NDT/MzMz/zMzM//V1dX///////////+tra3/MzMz/zMzM/8zMzP/qqqq///////+/v7/QEBA/zMzM/8z + MzP/z8/P/97e3v/e3t7/3t7e/9ra2v+oqKj/5OTk////////////ysrK/zMzM/8zMzP/zMzM//////// + /////////1NTU/8zMzP/MzMz/9/f3//////////////////Dw8P/MzMz/zMzM/9iYmL///////////// + ////5OTk/zMzM/8zMzP/Q0ND//7+/v////////////////++vr7/MzMz/zMzM/+1tbX///////////// + ///////////////8/Pz/NDQ0/zMzM/8zMzP/1dXV///////Jycn/Ozs7/zMzM/8zMzP/e3t7//7+/v// + ////9fX1/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/4CAgP///////////8rKyv8z + MzP/MzMz/8zMzP////////////////9TU1P/MzMz/zMzM//Z2dn/////////////////ra2t/zMzM/8z + MzP/g4OD//////////////////////84ODj/MzMz/zQ0NP/39/f/////////////////vr6+/zMzM/8z + MzP/tbW1/////////////////////////////Pz8/zQ0NP8zMzP/MzMz/1VVVf9TU1P/NDQ0/zMzM/8z + MzP/WVlZ//b29v////////////v7+/84ODj/MzMz/zMzM/9ra2v/b29v/29vb/9ubm7/MzMz/zMzM/9A + QED////////////Kysr/MzMz/zMzM//MzMz/////////////////U1NT/zMzM/8zMzP/w8PD//////// + /////////7i4uP8zMzP/MzMz/3Nzc//////////////////09PT/NDQ0/zMzM/86Ojr//Pz8//////// + /////////76+vv8zMzP/MzMz/7W1tf////////////////////////////z8/P80NDT/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9KSkr/zc3N////////////ZGRk/zMzM/8zMzP/vb29//////// + ////ysrK/zMzM/8zMzP/XV1d////////////ysrK/zMzM/8zMzP/zMzM/////////////////1NTU/8z + MzP/MzMz/4ODg////////Pz8/+/v7//n5+f/NTU1/zMzM/88PDz/5OTk////////////oqKi/zMzM/8z + MzP/aGho//////////////////////++vr7/MzMz/zMzM/+1tbX////////////////////////////8 + /Pz/NDQ0/zMzM/8zMzP/f39//5KSkv+SkpL/g4OD/01NTf8zMzP/MzMz/z8/P//v7+///////8PDw/80 + NDT/MzMz/zw8PP+IiIj/i4uL/0BAQP8zMzP/MzMz/7W1tf//////2tra/4GBgf8zMzP/MzMz/4KCgv+u + rq7/+vr6//////9TU1P/MzMz/zMzM/8zMzP/UlJS/0BAQP81NTX/v7+//4GBgf8zMzP/MzMz/0NDQ/+B + gYH/cHBw/zQ0NP8zMzP/NTU1/8vLy///////////////////////vr6+/zMzM/8zMzP/tbW1//////// + /////////////////////Pz8/zQ0NP8zMzP/MzMz/9XV1f/////////////////29vb/Q0ND/zMzM/8z + MzP/tra2////////////paWl/zg4OP8zMzP/MzMz/zMzM/8zMzP/NTU1/5eXl////////////4CAgP8z + MzP/MzMz/zMzM/8zMzP/NDQ0/9ra2v//////ZGRk/zMzM/85OTn/Pj4+/zMzM/8zMzP/MzMz/66urv/3 + 9/f/dXV1/zMzM/8zMzP/MzMz/zMzM/8zMzP/PDw8/7Ozs////////////////////////////76+vv8z + MzP/MzMz/7W1tf////////////////////////////z8/P80NDT/MzMz/zMzM//V1dX///////////// + ////+vr6/0VFRf8zMzP/MzMz/62trf/////////////////l5eX/n5+f/35+fv97e3v/mJiY/9zc3P// + ///////////////5+fn/r6+v/zMzM/8zMzP/sLCw/+Tk5P///////////9bW1v99fX3/tra2/9jY2P+D + g4P/gYGB/7y8vP/+/v7////////////Q0ND/k5OT/3p6ev+AgID/paWl/+vr6/////////////////// + //////////////++vr7/MzMz/zMzM/+1tbX////////////////////////////8/Pz/NDQ0/zMzM/8z + MzP/i4uL/6Ghof+hoaH/mJiY/2BgYP8zMzP/MzMz/zMzM//Z2dn///////////////////////////// + /////////////////////////////////////////8rKyv8zMzP/MzMz/83Nzf////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////// + /////v7+/zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+FhYX///////////// + ///////////////////////////////////////////////////////////////W1tb/MzMz/zMzM//Z + 2dn///////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf// + //////////////////////////////+goKD/R0dH/0BAQP9AQED/QEBA/0BAQP9AQED/SEhI/2VlZf+x + sbH//v7+//////////////////////////////////////////////////////////////////////// + /////v7+/62trf+wsLD///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////++ + vr7/MzMz/zMzM/+1tbX///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////++vr7/MzMz/zMzM/+1 + tbX///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////+9vb3/MzMz/zc3N/alpaX///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////ra2t/zQ0NPo3 + NzeyWlpa//v7+/////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////f39/2FhYf83Nze8Pj4+MTQ0NPh1dXX/6+vr//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////7e3t/3t7e/80NDT6Pj4+OQAAAAA8PDxJNTU16jY2Nv9MTEz/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/TU1N/zY2Nv81NTXtOzs7UAAAAAAAAAAAAAAAAEtLSw09 + PT1cNzc3gDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDc3N4A+Pj5gSEhIEAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAP//////////wAAAAAAAAAOAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAHAAAAAAAAAA///////////KAAAADAAAABg + AAAAAQAgAAAAAAAAJAAAEwsAABMLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA9PT0lNzc3kTMzM68z + MzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68z + MzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68z + MzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzY2NpQ8PDwoAAAAADs7OzM6 + OjrvkpKS/8DAwP/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/C + wsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/C + wsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wcHB/5WVlf87 + OzvxOzs7ODY2NsGtra3///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////+0tLT/NjY2yTs7O/zv7+////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////z8/P/Ozs7/jo6Ov/09PT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////01NTf9KSkr/SkpK/0pKSv9KSkr/SkpK/0pKSv9K + Skr/SkpK/11dXf/MzMz///////////////////////////////////////////////////////////// + ////////////////////m5ub/0pKSv9KSkr/SkpK/0pKSv9KSkr/SkpK/0pKSv9KSkr/Tk5O/5CQkP/8 + /Pz////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9ISEj/+vr6//////////////////////////////////////// + ////////////////////////////////////jo6O/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+2trb////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////15eXv9b + W1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9YWFj/NTU1/zMzM/80NDT/7+/v//////////////////////// + ////////////////////////////////////////////////////pKSk/1tbW/9bW1v/W1tb/1tbW/9b + W1v/W1tb/1tbW/9DQ0P/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + ////////////////////////////////////////////////////dHR0/zMzM/80NDT/7+/v//////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////MzMz/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/0 + 9PT////////////////////////////6+vr/8/Pz//Pz8//z8/P/8/Pz//b29v//////gICA/zMzM/80 + NDT/7+/v/////////////Pz8//T09P/z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//29vb///////////// + //////////7+/v/09PT/8/Pz//Pz8//z8/P/8/Pz//39/f/Z2dn/MzMz/zMzM/+YmJj////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////8HBwf9HR0f/NjY2/zY2Nv82Njb/NjY2/2dnZ/// + ////gICA/zMzM/80NDT/7+/v///////e3t7/VVVV/zY2Nv82Njb/NjY2/zY2Nv82Njb/NjY2/zY2Nv88 + PDz/kJCQ////////////8/Pz/2pqav84ODj/NjY2/zY2Nv82Njb/NjY2/9nZ2f/Z2dn/MzMz/zMzM/+Y + mJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////0pKSv8zMzP/MzMz/zMzM/8z + MzP/MzMz/2VlZf//////gICA/zMzM/80NDT/7+/v//////92dnb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/9jY2P//////oqKi/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9nZ2f/Z + 2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8z + MzP/NjY2/3V1df97e3v/e3t7/5ubm///////gICA/zMzM/80NDT/7+/v//////9iYmL/MzMz/zMzM/9o + aGj/fHx8/3x8fP98fHz/e3t7/0ZGRv8zMzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/WVlZ/3t7e/97 + e3v/e3t7/+bm5v/Z2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////////zY2Nv8zMzP/ampq////////////////////////////gICA/zMzM/80NDT/7+/v//////9i + YmL/MzMz/0FBQf/7+/v//////////////////////6ampv8zMzP/MzMz/8TExP//////jo6O/zMzM/8z + MzP/3d3d///////////////////////Z2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////////zY2Nv8zMzP/bm5u////////////////////////////gICA/zMzM/80 + NDT/7+/v//////9iYmL/MzMz/0NDQ//+/v7//////////////////////6urq/8zMzP/MzMz/8TExP// + ////jo6O/zMzM/8zMzP/4uLi///////////////////////Z2dn/MzMz/zMzM/+YmJj////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8zMzP/bm5u//////////////////////// + ////gICA/zMzM/80NDT/7+/v//////9iYmL/MzMz/0NDQ//+/v7//////////////////////6urq/8z + MzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/4uLi///////////////////////Z2dn/MzMz/zMzM/+Y + mJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8zMzP/bm5u//////// + ////////////////////gICA/zMzM/80NDT/7+/v//////9iYmL/MzMz/0NDQ//+/v7///////////// + /////////6urq/8zMzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/4uLi///////////////////////Z + 2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8z + MzP/aGho////////////////////////////enp6/zMzM/80NDT/7+/v//////9iYmL/MzMz/0BAQP/7 + +/v//////////////////////6Wlpf8zMzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/29vb//////// + ///////////////S0tL/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////////zY2Nv8zMzP/NDQ0/2lpaf9vb2//b29v/29vb/9ra2v/Nzc3/zMzM/80NDT/7+/v//////9i + YmL/MzMz/zMzM/9dXV3/b29v/29vb/9vb2//b29v/0FBQf8zMzP/MzMz/8TExP//////jo6O/zMzM/8z + MzP/UFBQ/29vb/9vb2//b29v/29vb/9OTk7/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////////01NTf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9D + Q0P/+Pj4//////95eXn/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NDQ0/9vb2/// + ////paWl/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+wsLD////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////8nJyf9NTU3/Nzc3/zc3N/83Nzf/Nzc3/zc3N/83 + Nzf/Nzc3/0hISP+9vb3////////////j4+P/Xl5e/zc3N/83Nzf/Nzc3/zc3N/83Nzf/Nzc3/zc3N/8/ + Pz//m5ub////////////9vb2/3R0dP85OTn/Nzc3/zc3N/83Nzf/Nzc3/zc3N/83Nzf/OTk5/3t7e//4 + +Pj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////////////////v7+//7+/v/+ + /v7//v7+//7+/v/+/v7//v7+//////////////////////////////////7+/v/+/v7//v7+//7+/v/+ + /v7//v7+//7+/v/////////////////////////////////+/v7//v7+//7+/v/+/v7//v7+//7+/v/+ + /v7//v7+///////////////////////4+Pj/PDw8/zo6Ov/09PT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zo6Ov/09PT///////////////////////7+/v/6+vr////////////////////////////5 + +fn///////////////////////7+/v/39/f//Pz8//////////////////////////////////////// + //////////7+/v/6+vr//////////////////////////////////v7+//b29v/9/f3///////////// + ///////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////2xsbP9ERET/2dnZ//////// + /////////6ampv8+Pj7/lJSU///////6+vr/mJiY/01NTf88PDz/QUFB/3Z2dv/j4+P////////////g + 4OD/bm5u/1hYWP90dHT/6+vr/39/f/9ERET/3Nzc//////////////////v7+/+bm5v/TU1N/zs7O/9F + RUX/goKC/+/v7//////////////////4+Pj/PDw8/zo6Ov/09PT//////////////////f39/zQ0NP8z + MzP/ra2t////////////2tra/zg4OP8zMzP/ioqK//////9+fn7/MzMz/0ZGRv+Hh4f/ZmZm/zQ0NP9M + TEz/+Pj4//////+Dg4P/MzMz/29vb/+BgYH/5eXl/0tLS/8zMzP/tLS0/////////////////4GBgf8z + MzP/Pj4+/3BwcP9JSUn/MzMz/1lZWf/4+Pj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////Pz8/zQ0NP8zMzP/ra2t///////7+/v/YGBg/zMzM/9AQED/5+fn/+Xl5f82Njb/MzMz/9bW1v// + /////v7+/6mpqf9vb2//9/f3//////9ycnL/MzMz/9fX1////////////0tLS/8zMzP/tLS0//////// + ////5ubm/zQ0NP80NDT/y8vL///////s7Oz/QUFB/zMzM/+5ubn////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////Pz8/zQ0NP8zMzP/ra2t//39/f+Pj4//MzMz/zU1Nf+4uLj//////8fHx/8z + MzP/MzMz/01NTf9OTk7/Tk5O/09PT/9wcHD/9fX1//////9xcXH/MzMz/9nZ2f///////////0tLS/8z + MzP/sLCw////////////w8PD/zMzM/9AQED/+fn5////////////Z2dn/zMzM/+VlZX////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////Pz8/zQ0NP8zMzP/RkZG/0ZGRv8zMzP/MzMz/2pqav/x + 8fH//////9LS0v8zMzP/MzMz/4uLi/+Tk5P/jo6O/zMzM/8zMzP/2NjY//////9xcXH/MzMz/9nZ2f// + /////////0tLS/8zMzP/mZmZ////////////z8/P/zMzM/84ODj/7u7u///////+/v7/V1dX/zMzM/+h + oaH////////////4+Pj/PDw8/zo6Ov/09PT//////////////////Pz8/zQ0NP8zMzP/QEBA/0lJSf9G + Rkb/NjY2/zMzM/9NTU3/6enp//j4+P9LS0v/MzMz/4yMjP/f39//lZWV/zMzM/9FRUX/9vb2//b29v9q + amr/MzMz/8bGxv/5+fn//////0tLS/8zMzP/S0tL/6+vr/+SkpL/z8/P/0lJSf8zMzP/enp6/9PT0/+b + m5v/NDQ0/zg4OP/e3t7////////////4+Pj/PDw8/zo6Ov/09PT//////////////////Pz8/zQ0NP8z + MzP/rKys//39/f/8/Pz/4ODg/zw8PP8zMzP/nJyc///////Ly8v/QUFB/zMzM/8zMzP/MzMz/z09Pf/C + wsL//////3R0dP8zMzP/MzMz/zQ0NP+Ghob//////1VVVf8zMzP/PDw8/zMzM/8zMzP/jIyM/83Nzf9D + Q0P/MzMz/zMzM/8zMzP/ODg4/62trf/////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////Pz8/zQ0NP8zMzP/ra2t////////////6+vr/z09Pf8zMzP/kpKS////////////8PDw/7Kysv+b + m5v/ra2t/+zs7P////////////X19f9oaGj/MzMz/8LCwv/39/f//////9HR0f+oqKj/5eXl/6CgoP+z + s7P/+Pj4///////y8vL/tLS0/5ubm/+rq6v/5ubm///////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////f39/zU1Nf8zMzP/RkZG/1NTU/9RUVH/PT09/zMzM/83Nzf/0tLS//////// + //////////////////////////////////////////////90dHT/MzMz/9vb2/////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////3l5ef8+Pj7/PT09/z09Pf89PT3/QkJC/2FhYf/B + wcH////////////////////////////////////////////////////////////FxcX/i4uL//r6+v// + //////////////////////////////////////////////////////////////////////////////// + ///////////////4+Pj/PDw8/zo6Ov/09PT///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zs7O/7x8fH///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////19fX/Ozs7/zY2NtC/v7////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////FxcX/NjY21zo6OkpDQ0P5srKy/+Dg4P/h4eH/4eHh/+Hh4f/h + 4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h + 4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h + 4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4ODg/7W1tf9FRUX7OTk5UHFxcQA6OjpCNjY2uTQ0NN8z + MzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98z + MzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98z + MzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfNDQ03zc3N7w6OjpGa2trAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAP///////wAAgAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////8AACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAABMLAAAT + CwAAAAAAAAAAAAAAAAAARERECjMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAz + MzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAz + MzMgMzMzIDMzMyBDQ0MKAAAAADc3N0pjY2PwkpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+S + kpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+S + kpL/kpKS/5KSkv+SkpL/kpKS/2VlZfE3NzdOWVlZ4vv7+/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////Pz8/1tbW+Z0dHT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////eHh4/3R0dP////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////94eHj/dHR0//////// + /////////4iIiP+Hh4f/h4eH/4eHh/+Hh4f/h4eH/6Kiov/9/f3///////////////////////////// + ////////////////////0tLS/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/iIiI/8zMzP///////////3h4eP90 + dHT/////////////////NTU1/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/7+/v/////////////////// + //////////////////////////////+0tLT/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/QUFB//7+/v// + ////eHh4/3R0dP/////////////////W1tb/1tbW/9bW1v/W1tb/1tbW/4WFhf8zMzP/sbGx//////// + //////////////////////////////////////////Dw8P/W1tb/1tbW/9bW1v/W1tb/09PT/0pKSv81 + NTX//f39//////94eHj/dHR0/////////////////+zs7P+3t7f/tbW1/7W1tf/a2tr/qqqq/zMzM/+x + sbH//////9/f3/+1tbX/tbW1/7W1tf+1tbX/tbW1/97e3v///////////9HR0f+1tbX/tbW1/7W1tf/2 + 9vb/XV1d/zU1Nf/9/f3//////3h4eP90dHT/////////////////UlJS/zMzM/8zMzP/MzMz/5iYmP+q + qqr/MzMz/7Gxsf/v7+//PDw8/zMzM/8zMzP/MzMz/zMzM/8zMzP/Ozs7/+7u7v/Q0ND/NDQ0/zMzM/8z + MzP/MzMz/+Xl5f9dXV3/NTU1//39/f//////eHh4/3R0dP////////////////81NTX/QEBA/6SkpP+n + p6f/09PT/6qqqv8zMzP/sbGx/9ra2v8zMzP/U1NT/6enp/+np6f/p6en/1RUVP8zMzP/2NjY/7S0tP8z + MzP/aGho/6enp/+np6f/9PT0/11dXf81NTX//f39//////94eHj/dHR0/////////////////zU1Nf9b + W1v/////////////////qqqq/zMzM/+xsbH/2tra/zMzM/+BgYH/////////////////g4OD/zMzM//Y + 2Nj/tLS0/zMzM/+np6f/////////////////XV1d/zU1Nf/9/f3//////3h4eP90dHT///////////// + ////NTU1/1tbW/////////////////+qqqr/MzMz/7Gxsf/a2tr/MzMz/4GBgf////////////////+D + g4P/MzMz/9jY2P+0tLT/MzMz/6enp/////////////////9dXV3/NTU1//39/f//////eHh4/3R0dP// + //////////////81NTX/WFhY/////////////////6enp/8zMzP/sbGx/9ra2v8zMzP/fn5+//////// + /////////4CAgP8zMzP/2NjY/7S0tP8zMzP/paWl/////////////////1tbW/81NTX//f39//////94 + eHj/dHR0/////////////////zY2Nv80NDT/WVlZ/1tbW/9bW1v/QUFB/zMzM/+zs7P/3Nzc/zMzM/85 + OTn/W1tb/1tbW/9bW1v/OTk5/zMzM//Z2dn/tbW1/zMzM/9AQED/W1tb/1tbW/9ZWVn/NDQ0/zY2Nv/9 + /f3//////3h4eP90dHT/////////////////iIiI/zc3N/81NTX/NTU1/zU1Nf81NTX/UVFR/+np6f/7 + +/v/Z2dn/zY2Nv81NTX/NTU1/zU1Nf82Njb/ZmZm//r6+v/r6+v/UlJS/zU1Nf81NTX/NTU1/zU1Nf83 + Nzf/hoaG////////////eHh4/3R0dP////////////////////////////7+/v/+/v7//v7+//7+/v// + /////////////////////v7+//7+/v/+/v7//v7+//7+/v///////////////////////v7+//7+/v/+ + /v7//v7+//////////////////////94eHj/dHR0//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3h4eP90dHT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////eHh4/3R0dP////////////////+Q + kJD/xsbG////////////rKys/6Kiov//////z8/P/4KCgv97e3v/tra2////////////sbGx/5OTk//b + 29v/mZmZ/8jIyP///////////+3t7f+Tk5P/eHh4/6CgoP/4+Pj///////////94eHj/dHR0//////// + /////f39/zQ0NP+EhIT//////9LS0v81NTX/fX19/9fX1/83Nzf/g4OD/6Ghof9AQED/wMDA/+3t7f8z + MzP/m5ub/9fX1/9DQ0P/iYmJ///////9/f3/VlZW/1NTU/+bm5v/Q0ND/3l5ef///////////3h4eP90 + dHT////////////9/f3/NDQ0/4SEhP/y8vL/U1NT/0VFRf/q6ur/mZmZ/zMzM/+FhYX/iYmJ/3p6ev/Y + 2Nj/5OTk/zMzM//m5ub//////0NDQ/+Hh4f//////9zc3P8zMzP/ubm5//////+UlJT/Nzc3//39/f// + ////eHh4/3R0dP////////////39/f80NDT/PDw8/zs7O/8zMzP/c3Nz//Pz8/+lpaX/MzMz/6ampv+q + qqr/MzMz/6enp//k5OT/MzMz/+bm5v//////Q0ND/2tra//+/v7/4+Pj/zMzM/+kpKT//////39/f/9C + QkL//v7+//////94eHj/dHR0/////////////f39/zQ0NP9vb2//ycnJ/7Gxsf83Nzf/hoaG//Dw8P9R + UVH/S0tL/0xMTP9NTU3/7Ozs/4SEhP8zMzP/ZmZm//X19f9HR0f/Nzc3/z4+Pv91dXX/iIiI/zc3N/9W + Vlb/NTU1/6ysrP///////////3h4eP90dHT////////////9/f3/NDQ0/3Fxcf/Q0ND/vLy8/zg4OP97 + e3v///////j4+P/Hx8f/xMTE//b29v//////3Nzc/zMzM//Y2Nj//////9TU1P/j4+P/wcHB/+7u7v// + ////2NjY/76+vv/k5OT/////////////////eHh4/3R0dP////////////////9VVVX/OTk5/zk5Of88 + PDz/X19f/+Dg4P/////////////////////////////////19fX/cXFx//X19f////////////////// + //////////////////////////////////////////////94eHj/dHR0//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////3h4eP90dHT///////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////eHh4/3R0dP// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////94 + eHj/X19f6v7+/v////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////v7+/2FhYe03NzdcdHR0+qampv+np6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+n + p6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+n + p6f/p6en/6enp/92dnb7Nzc3YQAAAAA+Pj4aNTU1QDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNANTU1QEBAQBwAAAAAgAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAEoAAAAEAAAACAAAAABACAAAAAAAAAEAAAT + CwAAEwsAAAAAAAAAAAAAWFhYUYeHh4+IiIiPiIiIj4iIiI+IiIiPiIiIj4iIiI+IiIiPiIiIj4iIiI+I + iIiPiIiIj4iIiI+IiIiPWVlZUrS0tPj///////////////////////////////////////////////// + /////////////////////////7a2tvm6urr//////8PDw//Dw8P/w8PD/+fn5/////////////////// + ////9PT0/8PDw//Dw8P/w8PD//Ly8v+8vLz/urq6//////+FhYX/hISE/3BwcP91dXX///////////// + /////////+jo6P+EhIT/hISE/2FhYf+cnJz/vLy8/7q6uv//////ioqK/3R0dP+ysrL/cnJy/8LCwv90 + dHT/dHR0/4CAgP/v7+//e3t7/3R0dP+lpaX/mZmZ/7y8vP+6urr//////0FBQf/S0tL/ycnJ/3Jycv+H + h4f/n5+f/9PT0/9PT0//xsbG/11dXf/T09P/q6ur/5mZmf+8vLz/urq6//////9HR0f//////9TU1P9y + cnL/h4eH/7+/v///////Wlpa/8bGxv9tbW3//////62trf+ZmZn/vLy8/7q6uv//////SkpK/0hISP9C + QkL/iIiI/5ycnP9AQED/SEhI/0JCQv/d3d3/Pz8//0hISP8+Pj7/rq6u/7y8vP+6urr///////////// + //////////////////////////////////////////////////////////////+8vLz/urq6///////V + 1dX//////9PT0//z8/P/v7+//+3t7f/s7Oz/29vb/9jY2P//////4ODg/8XFxf/9/f3/vLy8/7q6uv/+ + /v7/XFxc/8XFxf94eHj/dnZ2/4yMjP+VlZX/jo6O/9bW1v9mZmb/9vb2/2VlZf+cnJz/q6ur/7y8vP+6 + urr//v7+/0RERP96enr/iYmJ/4aGhv96enr/hYWF/3R0dP/Q0ND/S0tL/6Wlpf9mZmb/goKC/7u7u/+8 + vLz/urq6//7+/v9NTU3/gICA/3x8fP/9/f3/4uLi//39/f+dnZ3/8/Pz/+3t7f/r6+v/9fX1/+jo6P// + ////vLy8/7q6uv////////////////////////////////////////////////////////////////// + /////////7y8vP+2trb6//////////////////////////////////////////////////////////// + //////////////+3t7f7YWFhXJCQkJ+QkJCfkJCQn5CQkJ+QkJCfkJCQn5CQkJ+QkJCfkJCQn5CQkJ+Q + kJCfkJCQn5CQkJ+QkJCfYmJiXgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + + + \ No newline at end of file diff --git a/src/RetroGOG/frmPluginSelect.Designer.cs b/src/RetroGOG/frmPluginSelect.Designer.cs new file mode 100644 index 0000000..71b970e --- /dev/null +++ b/src/RetroGOG/frmPluginSelect.Designer.cs @@ -0,0 +1,182 @@ +namespace RetroGOG +{ + partial class frmPluginSelect + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmPluginSelect)); + this.btnBack = new System.Windows.Forms.Button(); + this.btnAbout = new System.Windows.Forms.Button(); + this.btnCancel = new System.Windows.Forms.Button(); + this.btnNext = new System.Windows.Forms.Button(); + this.chbPlaylists = new System.Windows.Forms.CheckedListBox(); + this.lblNoPlaylists = new System.Windows.Forms.Label(); + this.lblRALink = new System.Windows.Forms.LinkLabel(); + this.lblExplain = new System.Windows.Forms.Label(); + this.tmrCheck = new System.Windows.Forms.Timer(this.components); + this.barProgress = new System.Windows.Forms.ProgressBar(); + this.SuspendLayout(); + // + // btnBack + // + this.btnBack.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.btnBack.Location = new System.Drawing.Point(93, 343); + this.btnBack.Name = "btnBack"; + this.btnBack.Size = new System.Drawing.Size(75, 23); + this.btnBack.TabIndex = 13; + this.btnBack.Text = "< < &Back"; + this.btnBack.UseVisualStyleBackColor = true; + this.btnBack.Click += new System.EventHandler(this.btnBack_Click); + // + // btnAbout + // + this.btnAbout.Location = new System.Drawing.Point(12, 343); + this.btnAbout.Name = "btnAbout"; + this.btnAbout.Size = new System.Drawing.Size(75, 23); + this.btnAbout.TabIndex = 12; + this.btnAbout.Text = "&About"; + this.btnAbout.UseVisualStyleBackColor = true; + this.btnAbout.Click += new System.EventHandler(this.btnAbout_Click); + // + // btnCancel + // + this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.btnCancel.Location = new System.Drawing.Point(543, 343); + this.btnCancel.Name = "btnCancel"; + this.btnCancel.Size = new System.Drawing.Size(75, 23); + this.btnCancel.TabIndex = 11; + this.btnCancel.Text = "&Cancel"; + this.btnCancel.UseVisualStyleBackColor = true; + this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); + // + // btnNext + // + this.btnNext.Enabled = false; + this.btnNext.Location = new System.Drawing.Point(462, 343); + this.btnNext.Name = "btnNext"; + this.btnNext.Size = new System.Drawing.Size(75, 23); + this.btnNext.TabIndex = 10; + this.btnNext.Text = "&Next > >"; + this.btnNext.UseVisualStyleBackColor = true; + this.btnNext.Click += new System.EventHandler(this.btnNext_Click); + // + // chbPlaylists + // + this.chbPlaylists.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.chbPlaylists.FormattingEnabled = true; + this.chbPlaylists.Location = new System.Drawing.Point(12, 37); + this.chbPlaylists.Name = "chbPlaylists"; + this.chbPlaylists.Size = new System.Drawing.Size(606, 270); + this.chbPlaylists.TabIndex = 16; + // + // lblNoPlaylists + // + this.lblNoPlaylists.AutoSize = true; + this.lblNoPlaylists.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblNoPlaylists.Location = new System.Drawing.Point(12, 9); + this.lblNoPlaylists.Name = "lblNoPlaylists"; + this.lblNoPlaylists.Size = new System.Drawing.Size(446, 18); + this.lblNoPlaylists.TabIndex = 17; + this.lblNoPlaylists.Text = "No Playlists found in Retroarch directory! Please read instructions "; + this.lblNoPlaylists.Visible = false; + // + // lblRALink + // + this.lblRALink.AutoSize = true; + this.lblRALink.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblRALink.Location = new System.Drawing.Point(455, 9); + this.lblRALink.Name = "lblRALink"; + this.lblRALink.Size = new System.Drawing.Size(50, 18); + this.lblRALink.TabIndex = 18; + this.lblRALink.TabStop = true; + this.lblRALink.Text = "HERE"; + this.lblRALink.Visible = false; + this.lblRALink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lblRALink_LinkClicked); + // + // lblExplain + // + this.lblExplain.AutoSize = true; + this.lblExplain.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblExplain.Location = new System.Drawing.Point(12, 9); + this.lblExplain.Name = "lblExplain"; + this.lblExplain.Size = new System.Drawing.Size(454, 18); + this.lblExplain.TabIndex = 19; + this.lblExplain.Text = "Please select which systems you would like RetroGOG to configure"; + // + // tmrCheck + // + this.tmrCheck.Tick += new System.EventHandler(this.tmrCheck_Tick); + // + // barProgress + // + this.barProgress.Location = new System.Drawing.Point(12, 314); + this.barProgress.Name = "barProgress"; + this.barProgress.Size = new System.Drawing.Size(606, 23); + this.barProgress.TabIndex = 20; + this.barProgress.Visible = false; + // + // frmPluginSelect + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(630, 378); + this.Controls.Add(this.barProgress); + this.Controls.Add(this.lblExplain); + this.Controls.Add(this.lblRALink); + this.Controls.Add(this.lblNoPlaylists); + this.Controls.Add(this.chbPlaylists); + this.Controls.Add(this.btnBack); + this.Controls.Add(this.btnAbout); + this.Controls.Add(this.btnCancel); + this.Controls.Add(this.btnNext); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.Name = "frmPluginSelect"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "RetroGOG"; + this.Load += new System.EventHandler(this.frmPluginSelect_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button btnBack; + private System.Windows.Forms.Button btnAbout; + private System.Windows.Forms.Button btnCancel; + private System.Windows.Forms.Button btnNext; + private System.Windows.Forms.CheckedListBox chbPlaylists; + private System.Windows.Forms.Label lblNoPlaylists; + private System.Windows.Forms.LinkLabel lblRALink; + private System.Windows.Forms.Label lblExplain; + private System.Windows.Forms.Timer tmrCheck; + private System.Windows.Forms.ProgressBar barProgress; + } +} \ No newline at end of file diff --git a/src/RetroGOG/frmPluginSelect.cs b/src/RetroGOG/frmPluginSelect.cs new file mode 100644 index 0000000..d91b16d --- /dev/null +++ b/src/RetroGOG/frmPluginSelect.cs @@ -0,0 +1,210 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace RetroGOG +{ + public partial class frmPluginSelect : Form + { + IDictionary plugin_codes = new Dictionary(); + IDictionary core_codes = new Dictionary(); + + public frmPluginSelect() + { + InitializeComponent(); + } + + private void btnCancel_Click(object sender, EventArgs e) + { + if (MessageBox.Show("Are you sure you want to exit the wizard? Any unsaved progress will be lost.", "RetroGOG", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes) + { + this.Close(); + } + } + + private void btnBack_Click(object sender, EventArgs e) + { + this.Hide(); + Form frmDependencies = new frmDependencies(); + frmDependencies.Closed += (s, args) => this.Close(); + frmDependencies.Show(); + } + + private void frmPluginSelect_Load(object sender, EventArgs e) + { + // Build dictionaries + plugin_codes.Add("The 3DO Company - 3DO", "3do_9d81c0ec-5646-4b1a-b809-e7e61e1d3577"); + plugin_codes.Add("Nintendo - Nintendo 3DS", "3ds_f6acd3ed-2c31-47d6-bae4-07b6714c1e55"); + plugin_codes.Add("Atari - 2600", "atari_830528d9-e621-48e9-8ed4-e03a4853843e"); + plugin_codes.Add("Sega - Dreamcast", "dc_5d181ffd-48dc-4330-aa58-6f646e76a5c8"); + plugin_codes.Add("Nintendo - Game Boy", "gb_4345afe1-a2c3-4c58-93d3-373c53a90a92"); + plugin_codes.Add("Nintendo - Game Boy Advance", "gba_16a78ef5-fba6-4629-b83c-ef47adab5aab"); + plugin_codes.Add("Nintendo - Game Boy Color", "gbc_9b53fc85-af7c-4ce2-af31-0d95234d783a"); + plugin_codes.Add("Atari - Jaguar", "jaguar_b9773549-9c20-4729-b23d-f683762ce73a"); + plugin_codes.Add("Nintendo - Nintendo 64", "n64_a3824d31-c2d3-4a1a-b321-7d0764da5513"); + plugin_codes.Add("Nintendo - GameCube", "ncube_602422b9-ced5-476e-911a-7fa0adf0f7f7"); + plugin_codes.Add("Nintendo - Nintendo DS", "nds_4704ed29-f516-4fd8-8477-ddbcdb7cedfc"); + plugin_codes.Add("Nintendo - Nintendo Entertainment System", "nes_e2c630e1-3cbe-4dbd-9235-5e6a2d2955ad"); + plugin_codes.Add("Nintendo - Wii", "nwii_2d0e97ac-0406-4e5f-a85b-ab5b1a042cba"); + plugin_codes.Add("NEC - PC Engine - TurboGrafx 16", "pce_c0ffd4b8-41c3-46b8-b0f7-5f4e4bafc68a"); + plugin_codes.Add("Sony - PlayStation", "ps1_ff02c67d-5962-4e79-a3a3-928814edb270"); + plugin_codes.Add("Sony - PlayStation 2", "ps2_50ad79eb-393c-4f95-98ce-59f095ae47ea"); + plugin_codes.Add("Sony - PlayStation Portable", "psp_05487532-ba29-411b-b799-784262d275bd"); + plugin_codes.Add("Sega - Saturn", "saturn_bd6ec091-8ee0-440a-9e26-71bbf21c05af"); + plugin_codes.Add("Sega - Mega-CD - Sega CD", "segacd_ec7197bf-a4e4-4b86-81b9-38ea7d56f3b2"); + plugin_codes.Add("Sega - Mega Drive - Genesis", "segag_e3ac94e7-945e-459d-bc1e-676cff8173f9"); + plugin_codes.Add("Sega - Master System - Mark III", "sms_c6689bfb-7ba4-4d24-98e3-bd2dc339926b"); + plugin_codes.Add("Nintendo - Super Nintendo Entertainment System", "snes_bc831044-f772-4391-8c22-529f42cb9799"); + + core_codes.Add("The 3DO Company - 3DO", "opera_libretro.dll"); + core_codes.Add("Nintendo - Nintendo 3DS", "citra_libretro.dll"); + core_codes.Add("Atari - 2600", "stella_libretro.dll"); + core_codes.Add("Sega - Dreamcast", "flycast_libretro.dll"); + core_codes.Add("Nintendo - Game Boy", "mgba_libretro.dll"); + core_codes.Add("Nintendo - Game Boy Advance", "mgba_libretro.dll"); + core_codes.Add("Nintendo - Game Boy Color", "mgba_libretro.dll"); + core_codes.Add("Atari - Jaguar", "virtualjaguar_libretro.dll"); + core_codes.Add("Nintendo - Nintendo 64", "mupen64plus_next_libretro.dll"); + core_codes.Add("Nintendo - GameCube", "dolphin_libretro.dll"); + core_codes.Add("Nintendo - Nintendo DS", "desmume_libretro.dll"); + core_codes.Add("Nintendo - Nintendo Entertainment System", "mesen_libretro.dll"); + core_codes.Add("Nintendo - Wii", "dolphin_libretro.dll"); + core_codes.Add("NEC - PC Engine - TurboGrafx 16", "mednafen_pce_fast_libretro.dll"); + core_codes.Add("Sony - PlayStation", "pcsx_rearmed_libretro.dll"); + core_codes.Add("Sony - PlayStation 2", "play_libretro.dll"); + core_codes.Add("Sony - PlayStation Portable", "ppsspp_libretro.dll"); + core_codes.Add("Sega - Saturn", "mednafen_saturn_libretro.dll"); + core_codes.Add("Sega - Mega-CD - Sega CD", "genesis_plus_gx_libretro.dll"); + core_codes.Add("Sega - Mega Drive - Genesis", "genesis_plus_gx_libretro.dll"); + core_codes.Add("Sega - Master System - Mark III", "genesis_plus_gx_libretro.dll"); + core_codes.Add("Nintendo - Super Nintendo Entertainment System", "snes9x_libretro.dll"); + + tmrCheck.Enabled = true; + string playlistpath = Globals.RAPath.Replace("retroarch.exe", "playlists\\"); + string[] strPlaylists = Directory.GetFiles(playlistpath); + if (strPlaylists.Count() > 0) + { + foreach (string name in strPlaylists) + { + if (name.Substring(Math.Max(0, name.Length - 4)) == ".lpl") + { + string playlist_name = name.Replace(playlistpath, "").Replace(".lpl", ""); + if (plugin_codes.ContainsKey(playlist_name)) + { + chbPlaylists.Items.Add(playlist_name, true); + } + } + } + } + else + { + chbPlaylists.Visible = false; + lblExplain.Visible = false; + lblNoPlaylists.Visible = true; + lblRALink.Visible = true; + btnNext.Enabled = false; + } + } + + private void lblRALink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) + { + System.Diagnostics.Process.Start("https://docs.libretro.com/guides/import-content/"); + } + + private void tmrCheck_Tick(object sender, EventArgs e) + { + if (chbPlaylists.CheckedItems.Count == 0) + { + btnNext.Enabled = false; + } + else + { + btnNext.Enabled = true; + } + + if (barProgress.Value == barProgress.Maximum) + { + tmrCheck.Enabled = false; + this.Hide(); + Form frmComplete = new frmComplete(); + frmComplete.Closed += (s, args) => this.Close(); + frmComplete.Show(); + } + } + + private void btnAbout_Click(object sender, EventArgs e) + { + Form frmAbout = new frmAbout(); + frmAbout.Show(); + } + + private void btnNext_Click(object sender, EventArgs e) + { + chbPlaylists.Enabled = false; + btnNext.Enabled = false; + barProgress.Visible = true; + barProgress.Value = 0; + barProgress.Maximum = chbPlaylists.CheckedItems.Count; + + // Download latest galaxy API for plugins + using (var client = new WebClient()) + { + client.Headers.Add("user-agent", "RetroGOG"); + client.DownloadFile("https://raw.githubusercontent.com/jshackles/RetroGOG/master/galaxy_api.zip", Globals.GOGPluginPath + "\\galaxy_api.zip"); + } + + foreach (string item in chbPlaylists.CheckedItems) + { + if (plugin_codes.ContainsKey(item)) + { + // Create Plugin directory + Directory.CreateDirectory(Globals.GOGPluginPath + "\\" + plugin_codes[item] + "\\"); + + using (var client = new WebClient()) + { + // Download Plugin from Github + client.Headers.Add("user-agent", "RetroGOG"); + client.DownloadFile("https://raw.githubusercontent.com/jshackles/RetroGOG/master/plugins/" + plugin_codes[item] + "/manifest.json", Globals.GOGPluginPath + "\\" + plugin_codes[item] + "\\" + "manifest.json"); + client.DownloadFile("https://raw.githubusercontent.com/jshackles/RetroGOG/master/plugins/" + plugin_codes[item] + "/plugin.py", Globals.GOGPluginPath + "\\" + plugin_codes[item] + "\\" + "plugin.py"); + client.DownloadFile("https://raw.githubusercontent.com/jshackles/RetroGOG/master/plugins/" + plugin_codes[item] + "/version.py", Globals.GOGPluginPath + "\\" + plugin_codes[item] + "\\" + "version.py"); + + // Download Galaxy API and decompress + if (Directory.Exists(Globals.GOGPluginPath + "\\" + plugin_codes[item] + "\\galaxy\\")) + { + Directory.Delete(Globals.GOGPluginPath + "\\" + plugin_codes[item] + "\\galaxy\\", true); + } + System.IO.Compression.ZipFile.ExtractToDirectory(Globals.GOGPluginPath + "\\galaxy_api.zip", Globals.GOGPluginPath + "\\" + plugin_codes[item] + "\\galaxy\\"); + + // Write user_config.py file + string[] lines = new string[3]; + lines[0] = "# This file automatically generated by RetroGOG"; + lines[1] = "emu_path = \"" + Globals.RAPath.Replace("\\", "/").Replace("retroarch.exe", "") + "\""; + if (File.Exists(Globals.RAPath.Replace("retroarch.exe", "cores\\") + core_codes[item])) + { + lines[2] = "core = \"" + core_codes[item] + "\""; + } + else + { + Form frmCoreSelect = new frmCoreSelect(); + frmCoreSelect.Text = item; + frmCoreSelect.ShowDialog(this); + lines[2] = "core = \"" + Globals.TempCore + "\""; + } + System.IO.File.WriteAllLines(Globals.GOGPluginPath + "\\" + plugin_codes[item] + "\\" + "user_config.py", lines); + + barProgress.Value = barProgress.Value + 1; + } + } + } + } + } +} diff --git a/src/RetroGOG/frmPluginSelect.resx b/src/RetroGOG/frmPluginSelect.resx new file mode 100644 index 0000000..466a7bf --- /dev/null +++ b/src/RetroGOG/frmPluginSelect.resx @@ -0,0 +1,1892 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + + + AAABAAYAAAAAAAEAIADdFwAAZgAAAICAAAABACAAKAgBAEMYAABAQAAAAQAgAChCAABrIAEAMDAAAAEA + IACoJQAAk2IBACAgAAABACAAqBAAADuIAQAQEAAAAQAgAGgEAADjmAEAiVBORw0KGgoAAAANSUhEUgAA + AQAAAAEACAQAAAD2e2DtAAAXpElEQVR42u2deYAUxb3HPzOzB7ssuxzLfQmIXBpFWSCiiIhBIhoFTEzU + FzXmqVEQiOgDESV4LA/QKGh8JmqMmngkwovhKYgcigcgdxS5WZBjuZY92JOZeX8sM8zudPX0Od1L12f+ + 6a7q6vlV9ber6y6QSCQSiUQikUgk3sKn7PwCG5sfG3pyWOpgeh2nirDTdkoMkE4O2ceKFmYszV1y7oHJ + ig9RQQBz2Nj34PiTI6uaOx0BiVWkVTb6uNXcgUsnBOv7xAng7k4780tHnUp32mSJ1fiDWcvbP/Tmurqu + gdiTfF/2LTv/eTIvlOK0sRLrCfuruhbffhHDPl8T8zGIyQEmpG7LL5wQ9um/taQh0Wx+jzteKI6cRR/3 + A6lbXz76y7qPP5VudKcdmUhVNEQqOMx2tlNRzz17aZ/R807UHp9+sjN9nz5T+EDs48/lJobTtu43QtLg + CFHEMv5GQR3Xph/0HPXCKYiWAXJu2z/zzONP5VZmMoBs/E7bLzGJj0x6M5pmbKQm6lrZI5h29yeLOS2A + X5+zc0EwI+LZjHzGkOq05RIL8XM+g1jLiahLxYDyFd8UgB/msPvp6mYRj2b8nh86ba/EBs5jLl2iZ8HU + wjnTG0EAWvc7ODt0+lOQSj4XO22pxCaakMciqk6f1bQ9+e+t3/h/z6Fxp9Iil/xCvv1nNV2YGD0O+4on + PJbi/7bFyZERp1zudNpCic2M4ILocXleQR//0aFV0e//TTR22j6JzQS4LXoc9B+6wV9+deQ0jeFOWydJ + AgNpFT2uGOJPuyJy0oW2TtsmSQKZXHjmJM8fOi9yfK5s9fMIPaNHJxv7i6In7Zy2S5IkzuT0YfxV0ZNM + p+2SJInYJ+0/0zUs2/29gl9wLPEgUgAeRwrA40gBeBwpAI8jBeBxpAA8jhSAx5EC8DhSAB5HCsDjSAF4 + HCkAjyMF4HGkADyOFIDHkQLwOFIAHkcKwONIAXgcKQCPIwXgcSxaEO4YK/mWw1QS0vSnAdJpTDYtaEd3 + 2iKXJXQKCwRQzWv8lZMm7tCK/vyYvq5ZluYkRUAujZw2JAmYFkCYOfzD5D0O8y8W0oM7uNLxb9JJXmYx + x/DRhhv5BWnmb+lqTKf3Ot63xJAw3zGZSRSZv5UJyhnHWxwhRJD9zOOhmJW1zk5MC2C+hSuJh1jB7exw + MDneY2Od85XMd9CaZGBaABssNmg/D7DLmbQgzNI4t+UO2ZIsTAqgyoYsu5AplDmSGJUcjXPb64glycO0 + AOzYSmIHLzqSGNVUxrmdJGjgTg0HpwvdAuY78hkIKrRihDjldGLYim07A6TTUcE1SDUVlCYsW9fwNlOS + nhhhxWYsLU1bDRfbBNCJNxTdQwSp4Qjf8AEbVD4gyxlHltOp4wFsE4BP5dYZZNON6/iAWXFr2Uco4lv6 + O506HsDBMoCP63lQaECYb50zzUM4vDvQSBawWeD3vea7lLGTPRzkBOWESKUxLehAVzonLXrlrGATZWTR + iytpEuOznzXs4gSQTQd60Vtzj0cx2ymgkBNUEiKVJuTSnq50tvStdVgAAa4UCqA4Yegw+1nCp2ylWqE0 + 4SeHPH7EQNs7ddYzjYPRsxf4HQMAKGAuK+vUInw042rGcI7KJjwhdvMxK9nJKYVYBcghj6FcSgZW4Pj+ + YOLVSdVL3yE28he+VKmkhShiMYtpx83coLoIXhmLWcsxxXaASsaeXkCzET0YSae4K77nt5TEnB9jMq/R + mc+ZFifiMMd5h/cZxb2KRdxTfMVbrFWJe5DjLGIRLbmBMbQwnf6OC0BcIVRT+CHm8onGGvoBnmEBExko + 8D/K/Sr9D8GYxu7P+TuzuKTeFX+s8/gBSniTq3hYQU6ROL/DDubESWAHz7JGY7XzCH/kfX7FKJOP0PGG + oN1Cn5ZCny+4nUW6Gmh2MYF5ghCv6Oh+KuG5eg+olM8VrlvCZOHjr2Utr9Y5D/MP7mSVrlaHY8xigkLz + tR4cFkA5Hwv9uim6hplvKNI1/JkpVCn4bNV1nwP1+in2KpZVSilNeKcPKY+xbjb5MedaCfMld7Jdd7gz + OCqAKuYIy/pp9FF0/xczDbfOL+VxhU+OvjWSc+p9mgoN94YcjeYRIebwjuH7HGCsiYZzxwQQ4it+wz+F + /l3prOC6gVmm2uaX1Mt4AX6po8UxlbvqVeMqNYetT2b06/2myTFVR3mQYwbD2lYIrOFAnNspqinhGPvZ + xkYOq2p+jII2y5iumk0GSAGCKhIJ8zoDuKiOW3de5XXWU0yYijibfGTgw08WbbmAa+laz994T0Hf0+0F + G3jJdJ/qXp4m39DDtE0Au7neROhu/FjB9TX2Ca7305eR9KY5PorZyTKWCd7Nap7n5XrR7sp0AI4xKm5w + ayYfWVTjrktTfoMPqGAW1cKrMriIvrQlQDE7WM33QqmsYLFimiXC8WqgEulMVhiMWcjfBdfn8BDDottd + NKUzQ9nK7wTFu018yeVJikmAwQyhNVXsYzMbKDztfi5Tqd2p40NhIdTHcH5Np5gmo0qW8xxHFK8O8z8M + MbDkvwsFEGBSvUy6lvcFQ88zmE3fONcezOU+Qfn43SQJIIXJXBf9lN1MJbvZSAXn0e/0TIhq/ioI62Ms + t9b7DDbiGn7AeEGRbz+LuFG3jY63A9Qnk2ncoOBeyYeCEHcrPH6A5kwVDOr+msNJicsoflIngRvRi5u5 + g0HRiTBr2CMIezO3KT6cdjxLriDMewbKEi4TwHn8gWsVfb6JaW2PpRWjhXfrI9gGs4avkxCXjJgN2kQs + Fri349fC3oL23CPw22GgOugiAbTit7wiqP3DKoG6h6kW0X4kcE9GV/OFCXdhC/GlwGcM2SrhRtBe5/3E + uEIAafTlMf7Bz4UPM8wmgU9/Qiq/CwWhRLUJKxmY8IoCwZjqRgxTDZcu9F+v20oXFAKb8t8JN6yuFD6y + 5/iDSrgwPsWcI3FXs3kuSHjFDkGu1ilh6+QA/iy4Y0jnO+0CAZzgUWYkkEAlxwU+uzGCHYPZ69M14RWi + ZvCeCUP2ELiXUEJTXVbaJoBzmA2EqaGYfWxihUr3SCHjeYLBKncrsXiOXnO7oh2liYYGZlGXVuLeiSY0 + VqwUV1HqFgGkcU70OI9RlPIKbwsbacv5L/JVJGBm8rkSibNns+RquEbUrJ2jIWy2YpoEFfs71UhaIbAJ + 45mh0lJVzWOsE/paOzsnIwnbZGerDPpKFCstb6XyNSHdfRNJrQVczXSV+falPCIs6lm5dESABwTVKCtp + rOEaUayqNYRVvsave//nJFcDr2SsyptxhIcF2aJVU0TSyWOuStORdWgZiNpE4H5cQ9gTiq6pujuukl4L + +Bnf8JHQdxuzeFRBlU1opNi7F2CIhjU8fKTQmFzOobfKQDNr0bKySCuBe+JWisOCb326agOSEkkXgJ9J + bGa/0H8h/RkR59qIXMVKU4jfKA4ccR4tCdtJ4L6FYIKs/BuBe67uvNKBlsAc/ksleiGe5VCca7rgMYfZ + ovFfj/O/vMRrfO2iyZ49BZ/DgwmHqa4U3lEvjjQFD1Ts74twnGcUHtJFgquXamrUWcIoZvAnXuAe7hL0 + qIuwr9EoN6aqHMsplaFyAMeE65bk6bbBEQH4uEe1sWMZn8W5DRTkGp8JO1QjBHmDqTFjeTcxQ2hX/BsZ + tnWBCFHLx0IKhGHC/CVuJkItaYLeTzUc6gxqxgSV2kCY5+IKOd0FTas1zFEdJlrB08ytd8VqhY9MbWLE + J0dId9OKHq4RyLqMp4T/u5L3BD79DcwUcqw3cIhqj9feuHGyKcLPxirmCt/SPdzDgrgPSkgwhjZVoexe + Y3i8rRa6CafAr2WyQuN5mBVMFbQB+LjZgAWOCcDHRFW9vhmXzY2kteKVYf7Ko9HRdmco4VX+Q7G8HBA0 + 1KYp1KKDijN/rMLPHcL6wqfcxsKYVKhhOzOYJGwWv9hACcDR3sCW3M/vhEWswyzk53VcGnMvjyteG2Yx + qxjOFXQmixClfM8XLFEQRS29BFJKpblCHfwN2nMpGZRxmAIOEGAQXSxLhb4MZ6HA73seoxndaEMKxexh + n8rHLp37dLcCgsPdwSNYovJ+zWd0vSx5BJ8oFA9rKeZd3iOdVMLUKE4XP8OdQp8u9RaKBChlKlmkUEPF + 6U/NSzzG1RalgY8HWK8whyJCkcbha7cY7OAy+QlI3OGhRgqTVFqudsWNAgrwqKDiVEuYSkopS7B43TVc + KvT7geC+pRRRFi1pVDIzOqRElALaU6Y5T2vqOVDjcpUxhOqYFECmMNtpoil8B+5V8Y0f4dacWQlH2qlz + AZNUIj1A48j64uinQrTQvZ5FKfrwpCkJXMwMw91lJgUQEDZnam2gHUU/oZ/SgIkuzFPNBdS5mNmqve2t + uU7TfVKiAm8jePP0TTm9jNmGF3u4gtkmOstM1wKUs1Of5iaJAI8IH4nyBPHO/IlhBgwPcBNzEybzfcJx + yXVjHRF+F8U7+lRkrUwer3CR7mw8jXvI190BFItpAYxWzOzPZZDmO3TkYcUMrIVCp1AtTXmap3WVxH30 + YS4PadiZJJPnuVq1PB1gKNOjj6oxP1G4Jo/uulIRoAMvMUnYQ6hkRx6vxs1W1kug3eORwx8KikDqZNGG + lfUaYlowU1DRUqYrzVhd7x6ZPE5vYQgfXbmeThRxNGFbfToDmMB9dWbZqdGIoVxIDSVxaxim0IGhjOfW + OkI6nw31Whbb8qShUYd++nAtzTmUcNRyOpfxIHfpkEss+2JmWfkuiabfBG4xdLswa3ie706fBbicBxSX + iVVnHb+PTtfw0Y9x9NIQKsj3fM5atnBEQQgt6cNABtHaUEZXzhEOUEQVtd/8FrQhR7Gfv4wXWXC6fc7P + YCbqLAHUp4otfMY6tik0B7fhfPpzKa1N1MC+YFz02AIBAIQpYCfl5NBb03BI5XvsZQflZNOTVjqjF6aU + AxyjjGrCpJFFC9ppGpdnFcVspogm9Db4VipxioPRdQJr49SeJhbEKVYAFjUE+TjHRNk8co/Ohgd3+Mg2 + VRQyTw6XWX7PFDoayEv14YqpYRLnkALwOFIAHkcKwONIAXgcKQCPIwXgcaQAPI4UgMeRAvA4UgAeRwrA + 40gBeBwpAI8jBeBxpAA8jhSAx5EC8DhSAB5HCsDjSAF4HCkAjyMF4HGkADyOLSuEhCxcWi1gWqOnLFvp + z2c6udyVMmCxAGpYxWds4aiF0fTTnPO4jEG6llwA2M9S1lKgsB2sUXyk04m+DNU9C6qGL1nJd5anTE8u + 41INc55V4mTN3EAI8jEvs8+2dTVbcjujNE+FLmQeSyzeZeQMAS7nfs0iOMVi/qiy6atZWnMHN+h6k2Pn + BlpUBijjEaay18ZlVY8wi3GaFnkNs5xb+dC2xw9BlnM7H2iKbQmTmWbjiwGF5DPR8GqGlgiglIkssS2C + Z1jDWA17fn7EI4Lt2KykjCd4O+FVJUxgWRJS5gvGCXcgUscCAQR5SmWzF2vZwdQES7du5glbF3eNjfdz + CRaRPMUMhWXn7GEr0wzleRYIYFFS3v4I6/ibim9V0h4/wCnyBTt31LJQuKq3HazmXQOhTAugmleSsgvf + GURrZQN8aGD3XDMcjFvT+AwVvJbklHndwO5qpgXwtcrC5vZQwscCnxALkpzksFCY46wSbgxpF8dZqjuM + aQF8muRIqv3nQbYn3ZZ9wr1L3ZQyYkwLQOuWLVayVbDty64kfv8jhKPLY9XHTSkjxrQA9G2/Yg0VMft/ + OG0LwoqpE9acFO5GKsK0AJL/zkFIUOFxwhbxvzphTVB3VdC0AJJd6FL7VzfZ0lCQ3cEex/YNI7IYyrk6 + /ibIXj7RtHmqEfowSNf26qWsYr1N73gWV9FNV8oUsES14ckINgugFzMNLJt6N1P5ynJbUhjPT3VneXew + iCcVt601R29mGtj54G6msMZSO2z9BGQYevzQlKcsXHA1whh+ZiC6fkbwS8ttySLf0MYXzSxPGVsFMMTw + osnZXGuxLamMNrzK7k90D0ZJhPGUaSZcRN8Ytgqgm0Nhlcg28ea00rgBjna6mghrbcrYKgAzWxmY2wZB + KaJmomq1Ne5JGVkN9DhSAB5HCsDjSAF4HCkAjyMF4HGkADyOFIDHkQLwOFIAHkcKwONIAXgcKQCPIwXg + caQAPI4UgMeRAvA4UgAeRwrA40gBeBxbBVDtdOxiCJpaoc/qmNi3gplebBVA8pdrEFNKoeGwhyi12Br3 + pIytAviUfU7HL0oN7xqe4/e+5VO9V7gmZWwVQCWTkr6CkJj5vGHgMxBkAW9abks5D7PX6QQBbJ8cuoPb + GEw3DZMZbrZ9onKI5/mIQTTXPEUsTAlfsdkWa7ZxK1domh18i+EpbVqwfXp4OR9puMrHaPtNAbaxLQn/ + oo1yPtRwlZ9f2CoAWQ30OKYFYKc6G4YtbkoB/ZgWgJm16q3GGVvSdbq7C9MCsH4hh4ZmSyud7u7CtAB6 + Ox2DGLpavpBDYnzCFHBTyogxLYDBTscghjacl/T/7ExngY+bUkaMaQFcTBen4xATmRuTXiS7Tvit708n + pxNEA6YFkMZ/uqgcPJzuSf2/9two9GvEr1yUMiIsaAe4ih87HYsoaUwjI2n/lsoUslX8r+FqpxMkIRYI + wM/DDHA6HlF68liSJJDCgwniHWAKlzidIAmwpCUwk1mMdE12N4yZ5Nr+LzlMZ1TCq7J4hmtckzJKWNQU + nMk0ZtHdJVG9lLcYZWM+kMo1vM5wTbFtzHTy6eaSlInHsh4YP0O4nPV8xncc1j2CxmdxArVgCnexnHXs + oczCnUMb05G+DKG9jlABrmIIa1nJdxzWPRbIbuFY2gUXoB/9AAjpTvSA5VFrxU/5KRDWvYuGCL/hxxGg + P/0Npoy9/XU29cG6qZPRZ4O4jOOmlHGjPZIkIwXgcaQAPI4UgMeRAvA4rhVAhdMGuBZrU8a1Avi30wa4 + FmuHqbtUAAUsdNoEl7KLRZbez4UCCLOJCfIToECIDUzUvTmsOqZbAmdbvKVaDXvZ6qp5xUaZafEc4BoK + 2Gr5vGLTAvg/Siw26WzhXw0iF3PhJ0CSTBqoANzau+40+tOlQQrA30Bm3SSfgO6UaZACyCHLaRNcSlMy + dYZokAK4wGkDXIv+lGmQArjSaQNcio8husM0QAG0ayCTrpJPRwbpDtPgBODnPtKcNsKV+BlroFmnwQng + WoY5bYJLuZErDIRqYAIYzCRXDfF0D1cx3tDDTMbKTBaRws+43/KN3M8GUrmFuw2mTAMRQBqX8CsuctoM + F5JOP+4yUTE2LYA8i7sn4w3MpQd5dGxoXyv629ynmUouPelHB1MpY1oAM22NZENmjtMGaKKhvVYSi5EC + 8DhSAB5HCsDjSAF4HCkAjyMF4HGkADyOFIDHkQLwOFIAHkcKwONIAXgcKQCPIwXgcaQAPI7/zHRCq1bU + lbid2CftPzOUsCHMZpdYQeySHv6c6OFhp+2SJInCmGN/06LI4Q7LVtWWuJvt0aPMKv/x6HJcOznutGWS + JFDFxuixf6O/0dLISTnLnLZNkgQ2szd6nPGZv9XitGjp7x3L16CSuI0wb0WP/eHmC/y9D2QsiTjsYb7T + 9klsZjWfR48ztrZf458YbjnXH4w4vRhTQJCcfRznqZiifva8WVV+GLg0a3nEqYzJHHLaSolNlDGV/dGz + zJ3d3wQ/TAh2eCilKuK8h3HscdpSiQ0c52FWR898oZaTny0+vVnXpoMX+0ujC+8UsYiWLt7pTmKENTzI + lpjz5n+78snF4ehubUNWVl5Y2TPiWcUyVtOU1nI2/llANRuZxUsUx7g12ThwzKOVELO05Nicf88vqbf8 + Vmv60ou2NJarcjRAQlRQyDbWs7deR1/mtq4/er2g9jgmn7+/2Za/nBjptNkSu2myseMNb+yJnMW82qsr + R/w9mFLxw7AcI3DW4gu1eDvvphdjKnp18vY1obs+qVxRfUFNW1kCPBvJ2NX+3qFPPFqn31/hQU9rtOH6 + kt+W9wvKnOCswUfm1ux53d94tjjeR5HHU3afX3hjxRDyyuzbhV2SBDJqAhszPm02v/3Xs63d2kUikUgk + EolEIpFIJA2R/wdOE2BbbcdkRgAAAABJRU5ErkJggigAAACAAAAAAAEAAAEAIAAAAAAAAAABABMLAAAT + CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAICAgAFPT08sPz8/bjMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4A+Pj5xTU1NMnR0dAIA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAImJiQBHR0dEOTk5xzQ0NP4zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk50UVFRVGOjo4AAAAAAAAAAAAAAAAAAAAAAAAAAABs + bGwEPj4+jzQ0NP4zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/z4+PqFdXV0IAAAAAAAAAAAAAAAAZmZmAT09PZ8zMzP/MzMz/zMzM/9iYmL/r6+v/9jY2P/k + 5OT/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l5eX/5eXl/+Xl5f/l + 5eX/5eXl/+Xl5f/l5eX/5OTk/9ra2v+zs7P/aWlp/zMzM/8zMzP/MzMz/zw8PLJ6enoEAAAAAAAAAABC + QkJqMzMz/zMzM/88PDz/tbW1//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////wcHB/0FBQf8zMzP/MzMz/z8/P34AAAAAWlpaEjY2Nu4zMzP/NjY2/8XFxf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////0tLS/zo6Ov8zMzP/NTU19lFRUR8/ + Pz9xMzMz/zMzM/+Kior///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////m5ub/zMzM/8zMzP/Pj4+hjo6OsAzMzP/NTU1/+Xl5f////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////w8PD/Ozs7/zMzM/85 + OTnVQUFB+zMzM/9TU1P///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////9jY2P/MzMz/zY2Nv01NTX/MzMz/2lpaf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////3p6ev8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ////////////////////////////////////uLi4/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1 + tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1 + tbX/vb29/+Li4v////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////9zc3P+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1 + tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7W1tf+1tbX/tbW1/7e3t//MzMz/9/f3//////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////86 + Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NTU1/2lpaf/h4eH///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9DQ0P/p6en//7+/v////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + /////////////////////////////////////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0NDQ//c3Nz///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/iYmJ//////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + ////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/1tbW//+ + /v7///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////52dnf8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/wsLC//////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/83Nzf////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9qamr/////////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/n5+f//////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////+dnZ3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/z8/P//8/Pz///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/OTk5//f39////////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////9hYWH/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9b + W1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1FRUf80NDT/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5SUlP////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////sLCw/1tbW/9b + W1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9b + W1v/W1tb/1tbW/9aWlr/Pz8//zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////8DAwP81NTX/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////z8/P/Z2dn/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////2hoaP8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+UlJT///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////Nzc3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////9zc3P8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////94eHj/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/lJSU//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/2 + 9vb///////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////c + 3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + ///////////////////////////////////////////////x8fH/vLy8/6Wlpf+jo6P/o6Oj/6Ojo/+j + o6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo//9/f3/////////////////eHh4/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5SUlP////////////////////////////////////////////r6+v/I + yMj/qKio/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+j + o6P/o6Oj/6Ojo/+jo6P/o6Oj/6enp//FxcX/+Pj4//////////////////////////////////////// + /////////////////////v7+/9XV1f+tra3/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+j + o6P/o6Oj/6Ojo/+jo6P/0dHR/////////////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85 + OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v////////////////////////////////////////////////////////////////////////////9 + /f3/nJyc/z09Pf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/NDQ0//v7+/////////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////// + //////////////////////////////++vr7/SkpK/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9G + Rkb/t7e3/////////////////////////////////////////////////9vb2/9eXl7/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+ZmZn///////////// + ////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + /////////////////////////////////////v7+/4SEhP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/80NDT/+/v7/////////////////3h4eP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT/////////////////////////////////s7Oz/zU1Nf8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/80NDT/q6ur//////////////////////// + ///////////////a2tr/QEBA/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5mZmf/////////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/OTk5//b29v///////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr///////////////////////////////////////////////////////////////////////C + wsL/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zQ0NP/7+/v/////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP// + /////////////////////////+rq6v89PT3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/86Ojr/5OTk/////////////////////////////f39/1tbW/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/mZmZ//////// + /////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + /////////////////////////////////////////25ubv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NDQ0//v7+/////////////////94 + eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU////////////////////////////oKCg/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+Wlpb///////////// + ///////////////Q0ND/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+ZmZn/////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zk5Of/29vb///////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + ////RERE/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/80NDT/+/v7/////////////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+U + lJT///////////////////////////92dnb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2xsbP///////////////////////////6enp/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5mZmf// + ///////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP/7+/v///////////// + ////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP///////////////////////////2xsbP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////// + ////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/mZmZ/////////////////9zc3P8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/85OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/R0dH/2pqav9ra2v/a2tr/2tra/9r + a2v/a2tr/2tra/9ra2v/a2tr//z8/P////////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/lJSU////////////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/89 + PT3/aGho/21tbf9tbW3/bW1t/21tbf9tbW3/bW1t/21tbf9tbW3/bW1t/21tbf9paWn/Pj4+/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////////////////////+dnZ3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zY2Nv9gYGD/a2tr/2tra/9ra2v/a2tr/2tra/9ra2v/a2tr/2tra/+1 + tbX/////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/2pqav/39/f///////////////////////////////////////////////////////////// + /////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////9s + bGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/SEhI/+bm5v////////////////////////////////// + ///////////////////////////////q6ur/TU1N/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv// + /////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/82Njb/x8fH//////// + ///////////////////////////////////////////////////////////////c3Nz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/OTk5//b29v///////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/xcXF//////////////////////// + ////////////////////////////////////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5SUlP///////////////////////////2xsbP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+T + k5P///////////////////////////////////////////////////////////////////////////+a + mpr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi////////////////////////////nZ2d/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2FhYf////////////////////////////////////////////////// + /////////////////////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + /////////////////////////////////////////////////////////zo6Ov8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM//R0dH///////////////////////////////////////////////////////////// + //////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////////////////////// + ////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5+fn/////////////////////////////////// + /////////////////////////////////////////6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9i + YmL///////////////////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//////// + ////////////////////////////////////////////////////////////////////3Nzc/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + ////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9HR0f////////////////// + /////////////////////////////////////////////////////////3h4eP8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+UlJT///////////////////////////9sbGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/n5+f//////////////////////////////////////////////////////////////////////// + ////pqam/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv///////////////////////////52dnf8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9tbW3///////////////////////////////////////////// + ///////////////////////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////86Ojr/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/0dHR//////////////////////////////////////////////////////// + ////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP////////////////// + /////////2xsbP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+fn5////////////////////////////// + //////////////////////////////////////////////+mpqb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/YmJi////////////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/21tbf// + /////////////////////////////////////////////////////////////////////////9zc3P8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + /////////////////////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//R0dH///////////// + //////////////////////////////////////////////////////////////94eHj/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/lJSU////////////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5+fn/////////////////////////////////////////////////////////////////// + /////////6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////////////////////+d + nZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//////////////////////////////////////// + ////////////////////////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/2 + 9vb///////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ////////////////////////////////////////////////////////////////////Ojo6/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/9HR0f////////////////////////////////////////////////// + /////////////////////////3h4eP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////// + //////////////9sbGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/n5+f//////////////////////// + ////////////////////////////////////////////////////pqam/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/2JiYv///////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9t + bW3////////////////////////////////////////////////////////////////////////////c + 3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/0dHR//////// + ////////////////////////////////////////////////////////////////////eHh4/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5SUlP///////////////////////////2xsbP8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+fn5////////////////////////////////////////////////////////////// + //////////////+mpqb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////////////////////// + ////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/21tbf////////////////////////////////// + /////////////////////////////////////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85 + OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v//////////////////////////////////////////////////////////////////////zo6Ov8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM//R0dH///////////////////////////////////////////// + //////////////////////////////94eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU//////// + ////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5+fn/////////////////// + /////////////////////////////////////////////////////////6ampv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9iYmL///////////////////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/bW1t//////////////////////////////////////////////////////////////////////// + ////3Nzc/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9HR0f// + /////////////////////////////////////////////////////////////////////////3h4eP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////9sbGz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/n5+f//////////////////////////////////////////////////////// + ////////////////////pqam/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv////////////////// + /////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9tbW3///////////////////////////// + ///////////////////////////////////////////////c3Nz/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/OTk5//b29v///////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////86 + Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/0dHR//////////////////////////////////////// + ////////////////////////////////////eHh4/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP// + /////////////////////////2xsbP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+fn5////////////// + //////////////////////////////////////////////////////////////+mpqb/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/YmJi////////////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/21tbf////////////////////////////////////////////////////////////////// + /////////9zc3P8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/9vb2//////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + /////////////////////////////////////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//R + 0dH///////////////////////////////////////////////////////////////////////////94 + eHj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/lJSU////////////////////////////bGxs/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/5+fn/////////////////////////////////////////////////// + /////////////////////////6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////// + //////////////+dnZ3/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//////////////////////// + ////////////////////////////////////////////////////3Nzc/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zk5Of/29vb///////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + ////Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9DQ0P////////////////////////////////// + /////////////////////////////////////////3Z2dv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+U + lJT///////////////////////////9sbGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/np6e//////// + ////////////////////////////////////////////////////////////////////paWl/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2JiYv///////////////////////////52dnf8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + ///////////////b29v/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5//b29v////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////86Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/p6en///////////////////////////////////////////////////////////////////////8 + /Pz/UVFR/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5SUlP///////////////////////////2xsbP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/91dXX///////////////////////////////////////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////// + ////////////////////nZ2d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/0lJSf/5+fn///////////// + /////////////////////////////////////////////////////////7Kysv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/85OTn/9vb2////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/89PT3/qamp/9PT0//U1NT/1NTU/9TU1P/U + 1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/U1NT/y8vL/3R0dP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/lJSU////////////////////////////bGxs/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP+N + jY3/0NDQ/9TU1P/U1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/R0dH/k5OT/zU1Nf8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9iYmL///////////////////////////+dnZ3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/21tbf/Jycn/1NTU/9TU1P/U1NT/1NTU/9TU1P/U1NT/1NTU/9TU1P/U + 1NT/1NTU/9PT0/+urq7/QEBA/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zk5Of/29vb///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////Ojo6/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+UlJT///////////////////////////9s + bGz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2JiYv// + /////////////////////////52dnf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/OTk5//b29v///////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////88PDz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/5aWlv///////////////////////////25ubv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/ZGRk////////////////////////////n5+f/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/86Ojr/+Pj4//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + /////////////////////////////////////////////////////////1NTU/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys//////////////////////// + ////hYWF/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/97 + e3v///////////////////////////+2trb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0pKSv////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + ////////////////////kJCQ/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zY2Nv/n5+f////////////////////////////CwsL/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/7m5uf///////////////////////////+3t7f86 + Ojr/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/h4eH//////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + ///////////////////////////////////////////////////////////////s7Oz/RUVF/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/jIyM//////////////////////// + //////////39/f9lZWX/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9e + Xl7/+/v7/////////////////////////////////5WVlf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0FBQf/n5+f///////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + ///////////////////////////////S0tL/RERE/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/3d3d//5+fn//////////////////////////////////////+3t7f9cXFz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/V1dX/+np6f////////////////////////////////// + /////Pz8/39/f/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9CQkL/zMzM//////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ///////////////////////////////////////////////////////////////////////////////s + 7Oz/kJCQ/1JSUv89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89 + PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/QkJC/2lpaf+6urr//v7+//////////////////////// + //////////////////////////n5+f+mpqb/Xl5e/z8/P/89PT3/PT09/z09Pf89PT3/PT09/z09Pf89 + PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf8/Pz//XFxc/6Kiov/3 + 9/f//////////////////////////////////////////////////v7+/7+/v/9ra2v/Q0ND/z09Pf89 + PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89PT3/PT09/z09Pf89 + PT3/PT09/z09Pf9RUVH/jY2N/+np6f////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////////////////////////////////39/f/8/Pz//Pz8//z8/P/8 + /Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/+ + /v7///////////////////////////////////////////////////////////////////////////// + /////v7+//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8 + /Pz//Pz8//z8/P/8/Pz//Pz8//7+/v////////////////////////////////////////////////// + /////////////////////////////////////Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8 + /Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//z8/P/8/Pz//f39//////////////////////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + ///////////////////////////////IyMj/gICA/3Z2dv+lpaX/+Pj4//////////////////////// + /////////////////////////////////////////8rKyv+BgYH/dnZ2/6Ghof/19fX///////////// + ///////////////////////////////+/v7/4eHh/66urv+MjIz/eXl5/3Jycv94eHj/i4uL/66urv/k + 5OT///////////////////////////////////////////////////////////////////////z8/P/p + 6en/2NjY/9jY2P/k5OT/+Pj4////////////////////////////3t7e/4iIiP92dnb/pKSk//j4+P// + ///////////////////////////////////////////////////////////////////////////////x + 8fH/vLy8/5OTk/97e3v/c3Nz/3h4eP+Li4v/sLCw/+Xl5f////////////////////////////////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ////////////////////////////////////////////////////////////////////t7e3/zU1Nf8z + MzP/MzMz/zMzM/9qamr//v7+//////////////////////////////////////////////////////+n + p6f/NTU1/zMzM/8zMzP/MzMz/15eXv/6+vr/////////////////////////////////wcHB/19fX/80 + NDT/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zU1Nf9lZWX/yMjI//////////////////////// + //////////////////////////v7+/+dnZ3/SUlJ/zMzM/8zMzP/MzMz/zMzM/88PDz/b29v/9nZ2f// + /////////+Li4v8/Pz//MzMz/zMzM/8zMzP/cnJy//7+/v////////////////////////////////// + ///////////////////////////////o6Oj/hISE/zs7O/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/NTU1/2lpaf/Pz8////////////////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////9VVVX/MzMz/zMzM/8zMzP/MzMz/zMzM//Q0ND///////////// + ////////////////////////////////////0dHR/zc3N/8zMzP/MzMz/zMzM/8zMzP/MzMz/8fHx/// + ////////////////////9/f3/3t7e/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/80NDT/hoaG//r6+v//////////////////////////////////////hISE/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/RERE//f39///////kZGR/zMzM/8zMzP/MzMz/zMzM/8z + MzP/3d3d////////////////////////////////////////////////////////////vLy8/z8/P/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP+Pj4///Pz8//////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v/////////////////////////////////////////////////////////////////+/v7/zc3N/8z + MzP/MzMz/zMzM/8zMzP/MzMz/6+vr/////////////////////////////////////////////j4+P9U + VFT/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/19fX//////////////////r6+v9sbGz/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/f39///////// + /////////////////////////+bm5v82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/83 + Nzf/8PDw//////91dXX/MzMz/zMzM/8zMzP/MzMz/zMzM//CwsL///////////////////////////// + /////////////////////////7W1tf82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9/f3///v7+//////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ///////////////////////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys//////// + ////////////////////////////////////lJSU/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/1hYWP/9 + /f3/////////////////lJSU/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/0xMTP+Hh4f/mZmZ/4eHh/9Q + UFD/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/yMjI////////////////////////////ubm5/zMzM/8z + MzP/MzMz/zMzM/82Njb/iIiI/5ubm/9/f3//ampq/7W1tf///////////3Nzc/8zMzP/MzMz/zMzM/8z + MzP/MzMz/7+/v//////////////////////////////////////////////////a2tr/OTk5/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0RERP9aWlr/S0tL/zQ0NP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+o + qKj//////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////j4+P82 + Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+srKz//////////////////////////////////////9jY2P84 + ODj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/t7e3/////////////////+bm5v85OTn/MzMz/zMzM/8z + MzP/MzMz/zMzM/+Ojo7/+fn5//////////////////z8/P+urq7/Pj4+/zMzM/8zMzP/MzMz/zMzM/+K + ior///////////////////////////+hoaH/MzMz/zMzM/8zMzP/MzMz/3d3d/////////////////// + ////////////////////c3Nz/zMzM/8zMzP/MzMz/zMzM/8zMzP/v7+///////////////////////// + /////////////////////v7+/2lpaf8zMzP/MzMz/zMzM/8zMzP/MzMz/0JCQv+9vb3/+/v7///////+ + /v7/1tbW/1lZWf8zMzP/MzMz/zMzM/8zMzP/MzMz/0BAQP/w8PD///////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + ////////////////////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/6ysrP// + ///////////////////////////////7+/v/XV1d/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/15eXv/9 + /f3/////////////////l5eX/zMzM/8zMzP/MzMz/zMzM/8zMzP/bW1t//7+/v////////////////// + ///////////////d3d3/UFBQ/zMzM/8zMzP/MzMz/6Ojo////////////////////////////5eXl/8z + MzP/MzMz/zMzM/8zMzP/lZWV//////////////////////////////////////9zc3P/MzMz/zMzM/8z + MzP/MzMz/zMzM/+/v7/////////////////////////////////////////////b29v/NDQ0/zMzM/8z + MzP/MzMz/zMzM/82Njb/z8/P////////////////////////////8PDw/0tLS/8zMzP/MzMz/zMzM/8z + MzP/MzMz/6Wlpf////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra//////////////////////////////////////////////////////////////////4 + +Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys/////////////////////////////////6CgoP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/84ODj/1tbW//////////////////////9cXFz/MzMz/zMzM/8z + MzP/MzMz/zMzM//Kysr////////////////////////////////////////////u7u7/hISE/2dnZ/+X + l5f/+vr6////////////////////////////lZWV/zMzM/8zMzP/MzMz/zMzM/+ampr///////////// + /////////////////////////3Nzc/8zMzP/MzMz/zMzM/8zMzP/MzMz/7+/v/////////////////// + /////////////////////////5ycnP8zMzP/MzMz/zMzM/8zMzP/MzMz/3Nzc/////////////////// + ////////////////////q6ur/zMzM/8zMzP/MzMz/zMzM/8zMzP/ZmZm//////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////j4+P82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+s + rKz////////////////////////////a2tr/Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5qamv// + ////////////////////+fn5/zw8PP8zMzP/MzMz/zMzM/8zMzP/NDQ0/7S0tP++vr7/vr6+/76+vv++ + vr7/vr6+/76+vv++vr7/vr6+/7+/v//Ly8v/6urq//////////////////////////////////////+V + lZX/MzMz/zMzM/8zMzP/MzMz/5qamv//////////////////////////////////////c3Nz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/vr6+////////////////////////////////////////////dHR0/zMzM/8z + MzP/MzMz/zMzM/8zMzP/sbGx///////////////////////////////////////p6en/MzMz/zMzM/8z + MzP/MzMz/zMzM/9AQED//Pz8////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + ////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/6ysrP//////////////////////7+/v/1JSUv8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9tbW3//f39///////////////////////u7u7/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/81 + NTX/ZmZm/+rq6v///////////////////////////5WVlf8zMzP/MzMz/zMzM/8zMzP/mpqa//////// + //////////////////////////////9zc3P/MzMz/zMzM/8zMzP/MzMz/zMzM/+4uLj///////////// + //////////////////////////////9eXl7/MzMz/zMzM/8zMzP/MzMz/zMzM//Pz8////////////// + //////////////////////////////87Ozv/MzMz/zMzM/8zMzP/MzMz/zY2Nv/w8PD///////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ///////////////////////////////////////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8z + MzP/rKys/////////////////+Dg4P9YWFj/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/W1tb//Pz8/// + /////////////////////////+np6f8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/fHx8//////////////////////// + ////lZWV/zMzM/8zMzP/MzMz/zMzM/+ampr//////////////////////////////////////3Nzc/8z + MzP/MzMz/zMzM/8zMzP/MzMz/62trf///////////////////////////////////////////1lZWf8z + MzP/MzMz/zMzM/8zMzP/MzMz/9bW1v///////////////////////////////////////////0FBQf8z + MzP/MzMz/zMzM/8zMzP/NDQ0/+zs7P///////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + //////////j4+P82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/9mZmb/iYmJ/4KCgv9lZWX/NjY2/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/2JiYv/v7+//////////////////////////////////8/Pz/zQ0NP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9NTU3///////////////////////////+VlZX/MzMz/zMzM/8zMzP/MzMz/5qamv// + ////////////////////////////////////c3Nz/zMzM/8zMzP/MzMz/zMzM/8zMzP/mZmZ//////// + ////////////////////////////////////ZGRk/zMzM/8zMzP/MzMz/zMzM/8zMzP/x8fH//////// + ///////////////////////////////7+/v/NjY2/zMzM/8zMzP/MzMz/zMzM/84ODj/9PT0//////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + ////////////////////////////////////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/83Nzf/mpqa/+np6f// + ///////////////////////////////9/f3/RkZG/zMzM/8zMzP/MzMz/zMzM/8zMzP/m5ub/6urq/+r + q6v/q6ur/6urq/+rq6v/q6ur/6ampv8zMzP/MzMz/zMzM/8zMzP/MzMz/01NTf////////////////// + /////////5WVlf8zMzP/MzMz/zMzM/8zMzP/mpqa//////////////////////////////////////9z + c3P/MzMz/zMzM/8zMzP/MzMz/zMzM/92dnb///////////////////////////////////////////+A + gID/MzMz/zMzM/8zMzP/MzMz/zMzM/+enp7//////////////////////////////////////9fX1/8z + MzP/MzMz/zMzM/8zMzP/MzMz/0pKSv////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + ///////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/OTk5/4qKiv/09PT///////////////////////////9y + cnL/MzMz/zMzM/8zMzP/MzMz/zMzM/+zs7P/////////////////////////////////ysrK/zMzM/8z + MzP/MzMz/zMzM/8zMzP/aWlp////////////////////////////lZWV/zMzM/8zMzP/MzMz/zMzM/+a + mpr//////////////////////////////////////3Nzc/8zMzP/MzMz/zMzM/8zMzP/MzMz/0NDQ//5 + +fn//////////////////////////////////////7CwsP8zMzP/MzMz/zMzM/8zMzP/MzMz/1VVVf/8 + /Pz/////////////////////////////////ioqK/zMzM/8zMzP/MzMz/zMzM/8zMzP/enp6//////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////j4+P82Njb/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/1dXV//r6+v//////////////////////7a2tv8zMzP/MzMz/zMzM/8zMzP/MzMz/1FRUf/z + 8/P///////////////////////v7+/9mZmb/MzMz/zMzM/8zMzP/MzMz/zMzM/+jo6P///////////// + //////////////+VlZX/MzMz/zMzM/8zMzP/MzMz/5qamv////////////////////////////////// + ////c3Nz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5ycnP/////////////////z8/P/0dHR/+7u7v// + ////7+/v/zs7O/8zMzP/MzMz/zMzM/8zMzP/MzMz/5iYmP/+/v7//////////////////////8fHx/84 + ODj/MzMz/zMzM/8zMzP/MzMz/zMzM//BwcH///////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + ////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/2VlZf/+/v7///////////// + ////+fn5/05OTv8zMzP/MzMz/zMzM/8zMzP/MzMz/1lZWf/FxcX/8vLy//Pz8//Ozs7/aGho/zMzM/8z + MzP/MzMz/zMzM/8zMzP/Pz8//+/v7////////////////////////////5WVlf8zMzP/MzMz/zMzM/8z + MzP/mpqa//////////////////////////////////////9zc3P/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/NDQ0/2RkZP99fX3/YmJi/zk5Of8zMzP/PDw8/7y8vP//////jIyM/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/3Jycv/CwsL/29vb/8zMzP+NjY3/ODg4/zMzM/8zMzP/MzMz/zMzM/8zMzP/W1tb//39/f// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + ///////////////////////////////////////////////////////////////4+Pj/NjY2/zMzM/8z + MzP/MzMz/zMzM/8zMzP/pKSk//Ly8v/y8vL/8vLy//Ly8v/u7u7/4eHh/8XFxf+RkZH/Pz8//zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/8LCwv//////////////////////xMTE/zU1Nf8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/82Njb/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+oqKj///////////// + ////9vb2/3Nzc/88PDz/NjY2/zMzM/8zMzP/MzMz/zMzM/82Njb/OTk5/0ZGRv92dnb/7e3t//////// + /////////3Nzc/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/RUVF//v7+//z8/P/UFBQ/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zs7O//W1tb///////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////j4+P82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+srKz///////////// + ///////////////////////////////c3Nz/Ojo6/zMzM/8zMzP/MzMz/zMzM/8zMzP/f39///////// + ////////////////////paWl/zQ0NP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/hoaG//7+/v////////////////+2trb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+goKD/////////////////fn5+/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/85OTn/+Pj4///////f39//SUlJ/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/86Ojr/v7+///////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v/////////////////////////////////////////////////////////////////+Pj4/zY2Nv8z + MzP/MzMz/zMzM/8zMzP/MzMz/6ysrP////////////////////////////////////////////////9s + bGz/MzMz/zMzM/8zMzP/MzMz/zMzM/9cXFz/////////////////////////////////vLy8/0ZGRv8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/Ozs7/6SkpP/+/v7///////////// + /////////9zc3P88PDz/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NjY2/8nJyf// + //////////////+tra3/MzMz/zMzM/8zMzP/MzMz/0pKSv9dXV3/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/4eHh//////////////////q6ur/bW1t/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/VlZW/9TU1P////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + ///////////////////////////////4+Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/rKys//////// + /////////////////////////////////////////3BwcP8zMzP/MzMz/zMzM/8zMzP/MzMz/1NTU/// + ////////////////////////////////////8vLy/6Kiov9aWlr/NTU1/zMzM/8zMzP/MzMz/zMzM/80 + NDT/SUlJ/46Ojv/m5ub//////////////////////////////////////+fn5/+4uLj/cHBw/zMzM/8z + MzP/MzMz/zMzM/9zc3P/srKy/7S0tP/d3d3///////////////////////j4+P9kZGT/MzMz/zMzM/84 + ODj/urq6//Dw8P9ycnL/NDQ0/zMzM/8zMzP/MzMz/01NTf+oqKj//Pz8///////////////////////+ + /v7/ysrK/3d3d/8+Pj7/MzMz/zMzM/8zMzP/MzMz/zMzM/84ODj/Z2dn/7W1tf/6+vr///////////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////j4+P82 + Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/+srKz////////////////////////////////////////////r + 6+v/Pz8//zMzM/8zMzP/MzMz/zMzM/8zMzP/YmJi//////////////////////////////////////// + ///////////////w8PD/0dHR/8HBwf++vr7/ysrK/+Xl5f/+/v7///////////////////////////// + //////////////////////////////+VlZX/MzMz/zMzM/8zMzP/MzMz/5qamv////////////////// + //////////////////////////z8/P/Pz8//wMDA/+jo6P/////////////////k5OT/wsLC/8HBwf/d + 3d3//v7+//////////////////////////////////////////////////v7+//d3d3/xsbG/729vf/D + w8P/19fX//b29v////////////////////////////////////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + ////////////////////////////////////+Pj4/zY2Nv8zMzP/MzMz/zMzM/8zMzP/MzMz/6urq//9 + /f3//f39//39/f/9/f3//f39//v7+//z8/P/xMTE/1VVVf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+N + jY3///////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////5WVlf8z + MzP/MzMz/zMzM/8zMzP/mpqa//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra//////////////////////////////////////////////////////////////////4 + +Pj/NjY2/zMzM/8zMzP/MzMz/zMzM/8zMzP/Pj4+/0VFRf9FRUX/RUVF/0VFRf9ERET/Pj4+/zQ0NP8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NDQ0/9jY2P////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////lpaW/zMzM/8zMzP/MzMz/zMzM/+ampr///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////r6+v82Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+C + goL///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////+c + nJz/MzMz/zMzM/8zMzP/MzMz/6Kiov////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////fHx8/zMzM/8z + MzP/MzMz/zMzM/9ra2v///////////////////////////////////////////////////////////// + /////////0tLS/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/ampq//f39/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////76+vv8zMzP/MzMz/zMzM/8zMzP/xMTE//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////// + ////////////////////////////////////////////////////oaGh/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/PT09/5iYmP/7 + +/v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////f39/4aGhv85OTn/Ozs7/4+Pj//+/v7///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////3x8fP8z + MzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////////////////////// + ///////////////9/f3/sLCw/2dnZ/9PT0//TU1N/01NTf9NTU3/TU1N/01NTf9NTU3/TU1N/01NTf9N + TU3/T09P/1ZWVv9lZWX/gICA/7CwsP/w8PD///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////X19f/29vb///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////98 + fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9r + a2v///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////98fHz/MzMz/zMzM/8zMzP/MzMz/2tra/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////3x8fP8zMzP/MzMz/zMzM/8z + MzP/a2tr//////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////fHx8/zMzM/8zMzP/MzMz/zMzM/9ra2v///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////98fHz/MzMz/zMzM/8z + MzP/MzMz/2tra/////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////3x8fP8zMzP/MzMz/zMzM/8zMzP/a2tr//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////fHx8/zMzM/8z + MzP/Ozs7/zMzM/9fX1////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////9wcHD/MzMz/zMzM/89PT3cMzMz/z4+Pv/39/f///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////Pz8/0pKSv8z + MzP/OTk57Dw8PJUzMzP/MzMz/7W1tf////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////Gxsb/MzMz/zMzM/87OzuqS0tLNjQ0NP0zMzP/TExM//Hx8f// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////9/f3/1dXV/8z + MzP/MzMz/0VFRUmNjY0APDw8rTMzM/8zMzP/ZGRk//Hx8f////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////b29v9wcHD/MzMz/zMzM/86OjrAgYGBAgAAAABTU1MYNzc34zMzM/8z + MzP/TExM/7a2tv/39/f///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////r6+v++vr7/U1NT/zMzM/8z + MzP/NjY27E1NTSMAAAAAAAAAAAAAAABKSkoqNzc34jMzM/8zMzP/MzMz/z4+Pv9gYGD/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9sbGz/bGxs/2xsbP9s + bGz/bGxs/2xsbP9iYmL/QUFB/zMzM/8zMzP/MzMz/zY2NutHR0c3AAAAAAAAAAAAAAAAAAAAAAAAAABT + U1MXPDw8rDQ0NP0zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zQ0NP47 + Ozu5TU1NIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACNjY0AS0tLNTw8PJU9PT3bOzs7/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/Ojo6/0BAQOM8PDycR0dHPo+PjwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////////////////////// + ////////////////////+AAAAAAAAAAAAAAAAAAAH+AAAAAAAAAAAAAAAAAAAAfAAAAAAAAAAAAAAAAA + AAADgAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAHA + AAAAAAAAAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAB/AAAAAAAAAAAAAAAAAAAA////////////////// + //////////////////////////////////////////////8oAAAAQAAAAIAAAAABACAAAAAAAABAAAAT + CwAAEwsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgICAAENDQyYzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQEJCQil0dHQAAAAAAAAAAAAAAAAAPz8/JTc3N8Iz + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/Nzc3yD8/PyoA + AAAAQkJCGzU1NedWVlb/xMTE/+/v7//y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y + 8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y + 8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y + 8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/y8vL/8vLy//Ly8v/v + 7+//x8fH/1paWv81NTXsQUFBIDg4OJxKSkr/8PDw//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////09PT/T09P/zc3N6Y4ODjum5ub//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////6Ojo/81NTX0MzMz/7W1tf// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////+9 + vb3/MzMz/zMzM/+1tbX///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////++vr7/MzMz/zMzM/+1 + tbX/////////////////////////////////29vb/9ra2v/a2tr/2tra/9ra2v/a2tr/2tra/9ra2v/a + 2tr/2tra/9ra2v/a2tr/5+fn//////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////k5OT/2tra/9ra2v/a + 2tr/2tra/9ra2v/a2tr/2tra/9ra2v/a2tr/2tra/9ra2v/g4OD//f39//////////////////////// + ////vr6+/zMzM/8zMzP/tbW1/////////////////////////////////zc3N/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9wcHD/9vb2//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////aGho/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/1RUVP/h + 4eH//////////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////83 + Nzf/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/5aWlv// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////2hoaP8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/ZWVl//////////////////////++vr7/MzMz/zMzM/+1tbX///////////// + ////////////////////Nzc3/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/9mZmb///////////////////////////////////////////////////////////// + //////////////////////////////////////////////9oaGj/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zg4OP/8/Pz/////////////////vr6+/zMzM/8z + MzP/tbW1/////////////////////////////////66urv+tra3/ra2t/62trf+tra3/ra2t/62trf+t + ra3/ra2t/62trf+RkZH/NDQ0/zMzM/8zMzP/Y2Nj//////////////////////////////////////// + ////////////////////////////////////////////////////////////////////wsLC/62trf+t + ra3/ra2t/62trf+tra3/ra2t/62trf+tra3/ra2t/6Ojo/9AQED/MzMz/zMzM/82Njb/+/v7//////// + /////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////////////////////// + /////////////////////////////////////////1FRUf8zMzP/MzMz/2NjY/////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////hISE/zMzM/8z + MzP/NjY2//v7+/////////////////++vr7/MzMz/zMzM/+1tbX///////////////////////////// + //////////////////////////////////////////////////////////////9VVVX/MzMz/zMzM/9j + Y2P///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////4iIiP8zMzP/MzMz/zY2Nv/7+/v/////////////////vr6+/zMzM/8zMzP/tbW1//////// + //////////////////////////7+/v+ysrL/cnJy/2tra/9ra2v/a2tr/2tra/9ra2v/a2tr//39/f// + ////VVVV/zMzM/8zMzP/Y2Nj/////////////////+/v7/+Pj4//bGxs/2tra/9ra2v/a2tr/2tra/9r + a2v/a2tr/2tra/9ra2v/bGxs/46Ojv/t7e3//////////////////////87Ozv96enr/a2tr/2tra/9r + a2v/a2tr/2tra/9ra2v/2tra//////+IiIj/MzMz/zMzM/82Njb/+/v7/////////////////76+vv8z + MzP/MzMz/7W1tf////////////////////////////////+enp7/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM//9/f3//////1VVVf8zMzP/MzMz/2NjY/////////////r6+v9WVlb/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/U1NT//j4+P///////////8zMzP82 + Njb/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/8zMzP//////iIiI/zMzM/8zMzP/NjY2//v7+/// + //////////////++vr7/MzMz/zMzM/+1tbX/////////////////////////////////RkZG/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP//f39//////9VVVX/MzMz/zMzM/9jY2P////////////F + xcX/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//A + wMD///////////93d3f/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM//MzMz//////4iIiP8z + MzP/MzMz/zY2Nv/7+/v/////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////// + /////////zc3N/8zMzP/MzMz/zMzM/9GRkb/T09P/09PT/9PT0//T09P//39/f//////VVVV/zMzM/8z + MzP/Y2Nj////////////tra2/zMzM/8zMzP/MzMz/zU1Nf9PT0//UFBQ/1BQUP9QUFD/UFBQ/09PT/82 + Njb/MzMz/zMzM/8zMzP/sbGx////////////aGho/zMzM/8zMzP/MzMz/z8/P/9PT0//T09P/09PT/9P + T0//09PT//////+IiIj/MzMz/zMzM/82Njb/+/v7/////////////////76+vv8zMzP/MzMz/7W1tf// + //////////////////////////////83Nzf/MzMz/zMzM/9lZWX//f39//////////////////////// + /////////1VVVf8zMzP/MzMz/2NjY////////////7a2tv8zMzP/MzMz/zMzM/+wsLD///////////// + ////////////////////tLS0/zMzM/8zMzP/MzMz/7Gxsf///////////2hoaP8zMzP/MzMz/z8/P//x + 8fH/////////////////////////////////iIiI/zMzM/8zMzP/NjY2//v7+/////////////////++ + vr7/MzMz/zMzM/+1tbX/////////////////////////////////Nzc3/zMzM/8zMzP/goKC//////// + //////////////////////////////9VVVX/MzMz/zMzM/9jY2P///////////+2trb/MzMz/zMzM/8z + MzP/z8/P/////////////////////////////////9LS0v8zMzP/MzMz/zMzM/+xsbH///////////9o + aGj/MzMz/zMzM/9QUFD//////////////////////////////////////4iIiP8zMzP/MzMz/zY2Nv/7 + +/v/////////////////vr6+/zMzM/8zMzP/tbW1/////////////////////////////////zc3N/8z + MzP/MzMz/4KCgv//////////////////////////////////////VVVV/zMzM/8zMzP/Y2Nj//////// + ////tra2/zMzM/8zMzP/MzMz/8/Pz//////////////////////////////////S0tL/MzMz/zMzM/8z + MzP/sbGx////////////aGho/zMzM/8zMzP/UFBQ//////////////////////////////////////+I + iIj/MzMz/zMzM/82Njb/+/v7/////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////83Nzf/MzMz/zMzM/+CgoL//////////////////////////////////////1VVVf8z + MzP/MzMz/2NjY////////////7a2tv8zMzP/MzMz/zMzM//Pz8////////////////////////////// + ////0tLS/zMzM/8zMzP/MzMz/7Gxsf///////////2hoaP8zMzP/MzMz/1BQUP////////////////// + ////////////////////iIiI/zMzM/8zMzP/NjY2//v7+/////////////////++vr7/MzMz/zMzM/+1 + tbX/////////////////////////////////Nzc3/zMzM/8zMzP/goKC//////////////////////// + //////////////9VVVX/MzMz/zMzM/9jY2P///////////+2trb/MzMz/zMzM/8zMzP/z8/P//////// + /////////////////////////9LS0v8zMzP/MzMz/zMzM/+xsbH///////////9oaGj/MzMz/zMzM/9Q + UFD//////////////////////////////////////4iIiP8zMzP/MzMz/zY2Nv/7+/v///////////// + ////vr6+/zMzM/8zMzP/tbW1/////////////////////////////////zc3N/8zMzP/MzMz/4KCgv// + ////////////////////////////////////VVVV/zMzM/8zMzP/Y2Nj////////////tra2/zMzM/8z + MzP/MzMz/8/Pz//////////////////////////////////S0tL/MzMz/zMzM/8zMzP/sbGx//////// + ////aGho/zMzM/8zMzP/UFBQ//////////////////////////////////////+IiIj/MzMz/zMzM/82 + Njb/+/v7/////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////83 + Nzf/MzMz/zMzM/93d3f//////////////////////////////////v7+/0tLS/8zMzP/MzMz/2NjY/// + /////////7a2tv8zMzP/MzMz/zMzM//ExMT/////////////////////////////////yMjI/zMzM/8z + MzP/MzMz/7Gxsf///////////2hoaP8zMzP/MzMz/0dHR//9/f3///////////////////////////// + ////fX19/zMzM/8zMzP/NjY2//v7+/////////////////++vr7/MzMz/zMzM/+1tbX///////////// + ////////////////////Nzc3/zMzM/8zMzP/NjY2/3h4eP+EhIT/hISE/4SEhP+EhIT/hISE/2lpaf8z + MzP/MzMz/zMzM/9jY2P///////////+2trb/MzMz/zMzM/8zMzP/SkpK/4KCgv+EhIT/hISE/4SEhP+E + hIT/g4OD/0xMTP8zMzP/MzMz/zMzM/+xsbH///////////9oaGj/MzMz/zMzM/8zMzP/Z2dn/4SEhP+E + hIT/hISE/4SEhP+EhIT/enp6/zY2Nv8zMzP/MzMz/zY2Nv/7+/v/////////////////vr6+/zMzM/8z + MzP/tbW1/////////////////////////////////z09Pf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/ampq////////////vLy8/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/t7e3////////////b29v/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/86Ojr//f39//////// + /////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////99fX3/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/6qqqv///////////+/v7/9A + QED/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/Pj4+/+zs7P// + /////////6+vr/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/eHh4//////////////////////++vr7/MzMz/zMzM/+1tbX///////////////////////////// + ////9PT0/319ff89PT3/ODg4/zg4OP84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84ODj/RERE/5iYmP/+ + /v7/////////////////0NDQ/1paWv84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84 + ODj/WVlZ/83Nzf/////////////////+/v7/nJyc/0VFRf84ODj/ODg4/zg4OP84ODj/ODg4/zg4OP84 + ODj/ODg4/zg4OP89PT3/e3t7//Ly8v//////////////////////vr6+/zMzM/8zMzP/tbW1//////// + //////////////////////////////////////////7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+ + /v7//v7+/////////////////////////////////////////////v7+//7+/v/+/v7//v7+//7+/v/+ + /v7//v7+//7+/v/+/v7//v7+/////////////////////////////////////////////v7+//7+/v/+ + /v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//////////////////////////////////////76+vv8z + MzP/MzMz/7W1tf////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////++vr7/MzMz/zMzM/+1tbX///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////++ + vr7/MzMz/zMzM/+1tbX///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////Hx8f+9 + vb3/5+fn/////////////////////////////////9LS0v/FxcX//Pz8///////////////////////j + 4+P/wcHB/7q6uv/Ozs7/+Pj4//////////////////////////////////n5+f/r6+v/9/f3//////// + ////9/f3/7+/v//n5+f///////////////////////////////////////z8/P/T09P/u7u7/8DAwP/l + 5eX//////////////////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////9dXV3/MzMz/0FBQf/z8/P//////////////////////6urq/8zMzP/MzMz/5SUlP// + /////////9zc3P9iYmL/MzMz/zMzM/8zMzP/MzMz/0BAQP+goKD//v7+/////////////////5SUlP85 + OTn/MzMz/zU1Nf9wcHD//f39/3l5ef8zMzP/Q0ND//b29v///////////////////////////7m5uf9J + SUn/MzMz/zMzM/8zMzP/MzMz/2hoaP/i4uL///////////////////////////++vr7/MzMz/zMzM/+1 + tbX////////////////////////////8/Pz/NTU1/zMzM/8zMzP/1tbW/////////////////+Li4v87 + Ozv/MzMz/zMzM/+YmJj//////+Pj4/9BQUH/MzMz/zMzM/9OTk7/YWFh/zo6Ov8zMzP/MzMz/56env// + /////////+fn5/80NDT/MzMz/0lJSf9gYGD/YmJi//v7+/9UVFT/MzMz/zMzM//g4OD///////////// + /////////7Kysv80NDT/MzMz/zMzM/9BQUH/OTk5/zMzM/8zMzP/RkZG/+np6f////////////////// + ////vr6+/zMzM/8zMzP/tbW1/////////////////////////////Pz8/zQ0NP8zMzP/MzMz/9XV1f// + //////////7+/v9oaGj/MzMz/zMzM/8+Pj7/7e3t//////96enr/MzMz/zMzM/+Li4v//v7+///////q + 6ur/aGho/zMzM/9lZWX////////////Ozs7/MzMz/zMzM//Dw8P/////////////////U1NT/zMzM/8z + MzP/39/f//////////////////b29v9BQUH/MzMz/zQ0NP+zs7P//v7+//T09P9ycnL/MzMz/zMzM/+C + goL//////////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////z8/P80 + NDT/MzMz/zMzM//V1dX///////////+tra3/MzMz/zMzM/8zMzP/qqqq///////+/v7/QEBA/zMzM/8z + MzP/z8/P/97e3v/e3t7/3t7e/9ra2v+oqKj/5OTk////////////ysrK/zMzM/8zMzP/zMzM//////// + /////////1NTU/8zMzP/MzMz/9/f3//////////////////Dw8P/MzMz/zMzM/9iYmL///////////// + ////5OTk/zMzM/8zMzP/Q0ND//7+/v////////////////++vr7/MzMz/zMzM/+1tbX///////////// + ///////////////8/Pz/NDQ0/zMzM/8zMzP/1dXV///////Jycn/Ozs7/zMzM/8zMzP/e3t7//7+/v// + ////9fX1/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/4CAgP///////////8rKyv8z + MzP/MzMz/8zMzP////////////////9TU1P/MzMz/zMzM//Z2dn/////////////////ra2t/zMzM/8z + MzP/g4OD//////////////////////84ODj/MzMz/zQ0NP/39/f/////////////////vr6+/zMzM/8z + MzP/tbW1/////////////////////////////Pz8/zQ0NP8zMzP/MzMz/1VVVf9TU1P/NDQ0/zMzM/8z + MzP/WVlZ//b29v////////////v7+/84ODj/MzMz/zMzM/9ra2v/b29v/29vb/9ubm7/MzMz/zMzM/9A + QED////////////Kysr/MzMz/zMzM//MzMz/////////////////U1NT/zMzM/8zMzP/w8PD//////// + /////////7i4uP8zMzP/MzMz/3Nzc//////////////////09PT/NDQ0/zMzM/86Ojr//Pz8//////// + /////////76+vv8zMzP/MzMz/7W1tf////////////////////////////z8/P80NDT/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9KSkr/zc3N////////////ZGRk/zMzM/8zMzP/vb29//////// + ////ysrK/zMzM/8zMzP/XV1d////////////ysrK/zMzM/8zMzP/zMzM/////////////////1NTU/8z + MzP/MzMz/4ODg////////Pz8/+/v7//n5+f/NTU1/zMzM/88PDz/5OTk////////////oqKi/zMzM/8z + MzP/aGho//////////////////////++vr7/MzMz/zMzM/+1tbX////////////////////////////8 + /Pz/NDQ0/zMzM/8zMzP/f39//5KSkv+SkpL/g4OD/01NTf8zMzP/MzMz/z8/P//v7+///////8PDw/80 + NDT/MzMz/zw8PP+IiIj/i4uL/0BAQP8zMzP/MzMz/7W1tf//////2tra/4GBgf8zMzP/MzMz/4KCgv+u + rq7/+vr6//////9TU1P/MzMz/zMzM/8zMzP/UlJS/0BAQP81NTX/v7+//4GBgf8zMzP/MzMz/0NDQ/+B + gYH/cHBw/zQ0NP8zMzP/NTU1/8vLy///////////////////////vr6+/zMzM/8zMzP/tbW1//////// + /////////////////////Pz8/zQ0NP8zMzP/MzMz/9XV1f/////////////////29vb/Q0ND/zMzM/8z + MzP/tra2////////////paWl/zg4OP8zMzP/MzMz/zMzM/8zMzP/NTU1/5eXl////////////4CAgP8z + MzP/MzMz/zMzM/8zMzP/NDQ0/9ra2v//////ZGRk/zMzM/85OTn/Pj4+/zMzM/8zMzP/MzMz/66urv/3 + 9/f/dXV1/zMzM/8zMzP/MzMz/zMzM/8zMzP/PDw8/7Ozs////////////////////////////76+vv8z + MzP/MzMz/7W1tf////////////////////////////z8/P80NDT/MzMz/zMzM//V1dX///////////// + ////+vr6/0VFRf8zMzP/MzMz/62trf/////////////////l5eX/n5+f/35+fv97e3v/mJiY/9zc3P// + ///////////////5+fn/r6+v/zMzM/8zMzP/sLCw/+Tk5P///////////9bW1v99fX3/tra2/9jY2P+D + g4P/gYGB/7y8vP/+/v7////////////Q0ND/k5OT/3p6ev+AgID/paWl/+vr6/////////////////// + //////////////++vr7/MzMz/zMzM/+1tbX////////////////////////////8/Pz/NDQ0/zMzM/8z + MzP/i4uL/6Ghof+hoaH/mJiY/2BgYP8zMzP/MzMz/zMzM//Z2dn///////////////////////////// + /////////////////////////////////////////8rKyv8zMzP/MzMz/83Nzf////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////// + /////v7+/zo6Ov8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+FhYX///////////// + ///////////////////////////////////////////////////////////////W1tb/MzMz/zMzM//Z + 2dn///////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf// + //////////////////////////////+goKD/R0dH/0BAQP9AQED/QEBA/0BAQP9AQED/SEhI/2VlZf+x + sbH//v7+//////////////////////////////////////////////////////////////////////// + /////v7+/62trf+wsLD///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////++ + vr7/MzMz/zMzM/+1tbX///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////++vr7/MzMz/zMzM/+1 + tbX///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////vr6+/zMzM/8zMzP/tbW1//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////76+vv8zMzP/MzMz/7W1tf////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////+9vb3/MzMz/zc3N/alpaX///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////ra2t/zQ0NPo3 + NzeyWlpa//v7+/////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////f39/2FhYf83Nze8Pj4+MTQ0NPh1dXX/6+vr//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////7e3t/3t7e/80NDT6Pj4+OQAAAAA8PDxJNTU16jY2Nv9MTEz/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9Q + UFD/UFBQ/1BQUP9QUFD/UFBQ/1BQUP9QUFD/TU1N/zY2Nv81NTXtOzs7UAAAAAAAAAAAAAAAAEtLSw09 + PT1cNzc3gDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4Az + MzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDMzM4AzMzOAMzMzgDc3N4A+Pj5gSEhIEAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAP//////////wAAAAAAAAAOAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAHAAAAAAAAAA///////////KAAAADAAAABg + AAAAAQAgAAAAAAAAJAAAEwsAABMLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA9PT0lNzc3kTMzM68z + MzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68z + MzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68z + MzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzMzM68zMzOvMzMzrzY2NpQ8PDwoAAAAADs7OzM6 + OjrvkpKS/8DAwP/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/C + wsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/C + wsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wsLC/8LCwv/CwsL/wcHB/5WVlf87 + OzvxOzs7ODY2NsGtra3///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////+0tLT/NjY2yTs7O/zv7+////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////z8/P/Ozs7/jo6Ov/09PT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////01NTf9KSkr/SkpK/0pKSv9KSkr/SkpK/0pKSv9K + Skr/SkpK/11dXf/MzMz///////////////////////////////////////////////////////////// + ////////////////////m5ub/0pKSv9KSkr/SkpK/0pKSv9KSkr/SkpK/0pKSv9KSkr/Tk5O/5CQkP/8 + /Pz////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9ISEj/+vr6//////////////////////////////////////// + ////////////////////////////////////jo6O/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/+2trb////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////15eXv9b + W1v/W1tb/1tbW/9bW1v/W1tb/1tbW/9YWFj/NTU1/zMzM/80NDT/7+/v//////////////////////// + ////////////////////////////////////////////////////pKSk/1tbW/9bW1v/W1tb/1tbW/9b + W1v/W1tb/1tbW/9DQ0P/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + ////////////////////////////////////////////////////dHR0/zMzM/80NDT/7+/v//////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////MzMz/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/0 + 9PT////////////////////////////6+vr/8/Pz//Pz8//z8/P/8/Pz//b29v//////gICA/zMzM/80 + NDT/7+/v/////////////Pz8//T09P/z8/P/8/Pz//Pz8//z8/P/8/Pz//Pz8//29vb///////////// + //////////7+/v/09PT/8/Pz//Pz8//z8/P/8/Pz//39/f/Z2dn/MzMz/zMzM/+YmJj////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////8HBwf9HR0f/NjY2/zY2Nv82Njb/NjY2/2dnZ/// + ////gICA/zMzM/80NDT/7+/v///////e3t7/VVVV/zY2Nv82Njb/NjY2/zY2Nv82Njb/NjY2/zY2Nv88 + PDz/kJCQ////////////8/Pz/2pqav84ODj/NjY2/zY2Nv82Njb/NjY2/9nZ2f/Z2dn/MzMz/zMzM/+Y + mJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////0pKSv8zMzP/MzMz/zMzM/8z + MzP/MzMz/2VlZf//////gICA/zMzM/80NDT/7+/v//////92dnb/MzMz/zMzM/8zMzP/MzMz/zMzM/8z + MzP/MzMz/zMzM/8zMzP/MzMz/9jY2P//////oqKi/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/9nZ2f/Z + 2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8z + MzP/NjY2/3V1df97e3v/e3t7/5ubm///////gICA/zMzM/80NDT/7+/v//////9iYmL/MzMz/zMzM/9o + aGj/fHx8/3x8fP98fHz/e3t7/0ZGRv8zMzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/WVlZ/3t7e/97 + e3v/e3t7/+bm5v/Z2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////////zY2Nv8zMzP/ampq////////////////////////////gICA/zMzM/80NDT/7+/v//////9i + YmL/MzMz/0FBQf/7+/v//////////////////////6ampv8zMzP/MzMz/8TExP//////jo6O/zMzM/8z + MzP/3d3d///////////////////////Z2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////////zY2Nv8zMzP/bm5u////////////////////////////gICA/zMzM/80 + NDT/7+/v//////9iYmL/MzMz/0NDQ//+/v7//////////////////////6urq/8zMzP/MzMz/8TExP// + ////jo6O/zMzM/8zMzP/4uLi///////////////////////Z2dn/MzMz/zMzM/+YmJj////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8zMzP/bm5u//////////////////////// + ////gICA/zMzM/80NDT/7+/v//////9iYmL/MzMz/0NDQ//+/v7//////////////////////6urq/8z + MzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/4uLi///////////////////////Z2dn/MzMz/zMzM/+Y + mJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8zMzP/bm5u//////// + ////////////////////gICA/zMzM/80NDT/7+/v//////9iYmL/MzMz/0NDQ//+/v7///////////// + /////////6urq/8zMzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/4uLi///////////////////////Z + 2dn/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////zY2Nv8z + MzP/aGho////////////////////////////enp6/zMzM/80NDT/7+/v//////9iYmL/MzMz/0BAQP/7 + +/v//////////////////////6Wlpf8zMzP/MzMz/8TExP//////jo6O/zMzM/8zMzP/29vb//////// + ///////////////S0tL/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////////zY2Nv8zMzP/NDQ0/2lpaf9vb2//b29v/29vb/9ra2v/Nzc3/zMzM/80NDT/7+/v//////9i + YmL/MzMz/zMzM/9dXV3/b29v/29vb/9vb2//b29v/0FBQf8zMzP/MzMz/8TExP//////jo6O/zMzM/8z + MzP/UFBQ/29vb/9vb2//b29v/29vb/9OTk7/MzMz/zMzM/+YmJj////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////////01NTf8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/9D + Q0P/+Pj4//////95eXn/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/NDQ0/9vb2/// + ////paWl/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/zMzM/+wsLD////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////8nJyf9NTU3/Nzc3/zc3N/83Nzf/Nzc3/zc3N/83 + Nzf/Nzc3/0hISP+9vb3////////////j4+P/Xl5e/zc3N/83Nzf/Nzc3/zc3N/83Nzf/Nzc3/zc3N/8/ + Pz//m5ub////////////9vb2/3R0dP85OTn/Nzc3/zc3N/83Nzf/Nzc3/zc3N/83Nzf/OTk5/3t7e//4 + +Pj////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////////////////v7+//7+/v/+ + /v7//v7+//7+/v/+/v7//v7+//////////////////////////////////7+/v/+/v7//v7+//7+/v/+ + /v7//v7+//7+/v/////////////////////////////////+/v7//v7+//7+/v/+/v7//v7+//7+/v/+ + /v7//v7+///////////////////////4+Pj/PDw8/zo6Ov/09PT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zo6Ov/09PT///////////////////////7+/v/6+vr////////////////////////////5 + +fn///////////////////////7+/v/39/f//Pz8//////////////////////////////////////// + //////////7+/v/6+vr//////////////////////////////////v7+//b29v/9/f3///////////// + ///////////////4+Pj/PDw8/zo6Ov/09PT//////////////////////2xsbP9ERET/2dnZ//////// + /////////6ampv8+Pj7/lJSU///////6+vr/mJiY/01NTf88PDz/QUFB/3Z2dv/j4+P////////////g + 4OD/bm5u/1hYWP90dHT/6+vr/39/f/9ERET/3Nzc//////////////////v7+/+bm5v/TU1N/zs7O/9F + RUX/goKC/+/v7//////////////////4+Pj/PDw8/zo6Ov/09PT//////////////////f39/zQ0NP8z + MzP/ra2t////////////2tra/zg4OP8zMzP/ioqK//////9+fn7/MzMz/0ZGRv+Hh4f/ZmZm/zQ0NP9M + TEz/+Pj4//////+Dg4P/MzMz/29vb/+BgYH/5eXl/0tLS/8zMzP/tLS0/////////////////4GBgf8z + MzP/Pj4+/3BwcP9JSUn/MzMz/1lZWf/4+Pj////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////Pz8/zQ0NP8zMzP/ra2t///////7+/v/YGBg/zMzM/9AQED/5+fn/+Xl5f82Njb/MzMz/9bW1v// + /////v7+/6mpqf9vb2//9/f3//////9ycnL/MzMz/9fX1////////////0tLS/8zMzP/tLS0//////// + ////5ubm/zQ0NP80NDT/y8vL///////s7Oz/QUFB/zMzM/+5ubn////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////Pz8/zQ0NP8zMzP/ra2t//39/f+Pj4//MzMz/zU1Nf+4uLj//////8fHx/8z + MzP/MzMz/01NTf9OTk7/Tk5O/09PT/9wcHD/9fX1//////9xcXH/MzMz/9nZ2f///////////0tLS/8z + MzP/sLCw////////////w8PD/zMzM/9AQED/+fn5////////////Z2dn/zMzM/+VlZX////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////Pz8/zQ0NP8zMzP/RkZG/0ZGRv8zMzP/MzMz/2pqav/x + 8fH//////9LS0v8zMzP/MzMz/4uLi/+Tk5P/jo6O/zMzM/8zMzP/2NjY//////9xcXH/MzMz/9nZ2f// + /////////0tLS/8zMzP/mZmZ////////////z8/P/zMzM/84ODj/7u7u///////+/v7/V1dX/zMzM/+h + oaH////////////4+Pj/PDw8/zo6Ov/09PT//////////////////Pz8/zQ0NP8zMzP/QEBA/0lJSf9G + Rkb/NjY2/zMzM/9NTU3/6enp//j4+P9LS0v/MzMz/4yMjP/f39//lZWV/zMzM/9FRUX/9vb2//b29v9q + amr/MzMz/8bGxv/5+fn//////0tLS/8zMzP/S0tL/6+vr/+SkpL/z8/P/0lJSf8zMzP/enp6/9PT0/+b + m5v/NDQ0/zg4OP/e3t7////////////4+Pj/PDw8/zo6Ov/09PT//////////////////Pz8/zQ0NP8z + MzP/rKys//39/f/8/Pz/4ODg/zw8PP8zMzP/nJyc///////Ly8v/QUFB/zMzM/8zMzP/MzMz/z09Pf/C + wsL//////3R0dP8zMzP/MzMz/zQ0NP+Ghob//////1VVVf8zMzP/PDw8/zMzM/8zMzP/jIyM/83Nzf9D + Q0P/MzMz/zMzM/8zMzP/ODg4/62trf/////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + /////Pz8/zQ0NP8zMzP/ra2t////////////6+vr/z09Pf8zMzP/kpKS////////////8PDw/7Kysv+b + m5v/ra2t/+zs7P////////////X19f9oaGj/MzMz/8LCwv/39/f//////9HR0f+oqKj/5eXl/6CgoP+z + s7P/+Pj4///////y8vL/tLS0/5ubm/+rq6v/5ubm///////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT//////////////////f39/zU1Nf8zMzP/RkZG/1NTU/9RUVH/PT09/zMzM/83Nzf/0tLS//////// + //////////////////////////////////////////////90dHT/MzMz/9vb2/////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zo6Ov/09PT//////////////////////3l5ef8+Pj7/PT09/z09Pf89PT3/QkJC/2FhYf/B + wcH////////////////////////////////////////////////////////////FxcX/i4uL//r6+v// + //////////////////////////////////////////////////////////////////////////////// + ///////////////4+Pj/PDw8/zo6Ov/09PT///////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////4+Pj/PDw8/zo6Ov/09PT///////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////4+Pj/PDw8/zo6Ov/0 + 9PT///////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////4 + +Pj/PDw8/zs7O/7x8fH///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////19fX/Ozs7/zY2NtC/v7////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////FxcX/NjY21zo6OkpDQ0P5srKy/+Dg4P/h4eH/4eHh/+Hh4f/h + 4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h + 4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h + 4eH/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/h4eH/4ODg/7W1tf9FRUX7OTk5UHFxcQA6OjpCNjY2uTQ0NN8z + MzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98z + MzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98z + MzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfMzMz3zMzM98zMzPfNDQ03zc3N7w6OjpGa2trAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAP///////wAAgAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////8AACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAABMLAAAT + CwAAAAAAAAAAAAAAAAAARERECjMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAz + MzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAzMzMgMzMzIDMzMyAz + MzMgMzMzIDMzMyBDQ0MKAAAAADc3N0pjY2PwkpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+S + kpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+SkpL/kpKS/5KSkv+S + kpL/kpKS/5KSkv+SkpL/kpKS/2VlZfE3NzdOWVlZ4vv7+/////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////Pz8/1tbW+Z0dHT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////eHh4/3R0dP////////////////// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////94eHj/dHR0//////// + /////////4iIiP+Hh4f/h4eH/4eHh/+Hh4f/h4eH/6Kiov/9/f3///////////////////////////// + ////////////////////0tLS/4eHh/+Hh4f/h4eH/4eHh/+Hh4f/iIiI/8zMzP///////////3h4eP90 + dHT/////////////////NTU1/zMzM/8zMzP/MzMz/zMzM/8zMzP/MzMz/7+/v/////////////////// + //////////////////////////////+0tLT/MzMz/zMzM/8zMzP/MzMz/zMzM/8zMzP/QUFB//7+/v// + ////eHh4/3R0dP/////////////////W1tb/1tbW/9bW1v/W1tb/1tbW/4WFhf8zMzP/sbGx//////// + //////////////////////////////////////////Dw8P/W1tb/1tbW/9bW1v/W1tb/09PT/0pKSv81 + NTX//f39//////94eHj/dHR0/////////////////+zs7P+3t7f/tbW1/7W1tf/a2tr/qqqq/zMzM/+x + sbH//////9/f3/+1tbX/tbW1/7W1tf+1tbX/tbW1/97e3v///////////9HR0f+1tbX/tbW1/7W1tf/2 + 9vb/XV1d/zU1Nf/9/f3//////3h4eP90dHT/////////////////UlJS/zMzM/8zMzP/MzMz/5iYmP+q + qqr/MzMz/7Gxsf/v7+//PDw8/zMzM/8zMzP/MzMz/zMzM/8zMzP/Ozs7/+7u7v/Q0ND/NDQ0/zMzM/8z + MzP/MzMz/+Xl5f9dXV3/NTU1//39/f//////eHh4/3R0dP////////////////81NTX/QEBA/6SkpP+n + p6f/09PT/6qqqv8zMzP/sbGx/9ra2v8zMzP/U1NT/6enp/+np6f/p6en/1RUVP8zMzP/2NjY/7S0tP8z + MzP/aGho/6enp/+np6f/9PT0/11dXf81NTX//f39//////94eHj/dHR0/////////////////zU1Nf9b + W1v/////////////////qqqq/zMzM/+xsbH/2tra/zMzM/+BgYH/////////////////g4OD/zMzM//Y + 2Nj/tLS0/zMzM/+np6f/////////////////XV1d/zU1Nf/9/f3//////3h4eP90dHT///////////// + ////NTU1/1tbW/////////////////+qqqr/MzMz/7Gxsf/a2tr/MzMz/4GBgf////////////////+D + g4P/MzMz/9jY2P+0tLT/MzMz/6enp/////////////////9dXV3/NTU1//39/f//////eHh4/3R0dP// + //////////////81NTX/WFhY/////////////////6enp/8zMzP/sbGx/9ra2v8zMzP/fn5+//////// + /////////4CAgP8zMzP/2NjY/7S0tP8zMzP/paWl/////////////////1tbW/81NTX//f39//////94 + eHj/dHR0/////////////////zY2Nv80NDT/WVlZ/1tbW/9bW1v/QUFB/zMzM/+zs7P/3Nzc/zMzM/85 + OTn/W1tb/1tbW/9bW1v/OTk5/zMzM//Z2dn/tbW1/zMzM/9AQED/W1tb/1tbW/9ZWVn/NDQ0/zY2Nv/9 + /f3//////3h4eP90dHT/////////////////iIiI/zc3N/81NTX/NTU1/zU1Nf81NTX/UVFR/+np6f/7 + +/v/Z2dn/zY2Nv81NTX/NTU1/zU1Nf82Njb/ZmZm//r6+v/r6+v/UlJS/zU1Nf81NTX/NTU1/zU1Nf83 + Nzf/hoaG////////////eHh4/3R0dP////////////////////////////7+/v/+/v7//v7+//7+/v// + /////////////////////v7+//7+/v/+/v7//v7+//7+/v///////////////////////v7+//7+/v/+ + /v7//v7+//////////////////////94eHj/dHR0//////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////3h4eP90dHT///////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////eHh4/3R0dP////////////////+Q + kJD/xsbG////////////rKys/6Kiov//////z8/P/4KCgv97e3v/tra2////////////sbGx/5OTk//b + 29v/mZmZ/8jIyP///////////+3t7f+Tk5P/eHh4/6CgoP/4+Pj///////////94eHj/dHR0//////// + /////f39/zQ0NP+EhIT//////9LS0v81NTX/fX19/9fX1/83Nzf/g4OD/6Ghof9AQED/wMDA/+3t7f8z + MzP/m5ub/9fX1/9DQ0P/iYmJ///////9/f3/VlZW/1NTU/+bm5v/Q0ND/3l5ef///////////3h4eP90 + dHT////////////9/f3/NDQ0/4SEhP/y8vL/U1NT/0VFRf/q6ur/mZmZ/zMzM/+FhYX/iYmJ/3p6ev/Y + 2Nj/5OTk/zMzM//m5ub//////0NDQ/+Hh4f//////9zc3P8zMzP/ubm5//////+UlJT/Nzc3//39/f// + ////eHh4/3R0dP////////////39/f80NDT/PDw8/zs7O/8zMzP/c3Nz//Pz8/+lpaX/MzMz/6ampv+q + qqr/MzMz/6enp//k5OT/MzMz/+bm5v//////Q0ND/2tra//+/v7/4+Pj/zMzM/+kpKT//////39/f/9C + QkL//v7+//////94eHj/dHR0/////////////f39/zQ0NP9vb2//ycnJ/7Gxsf83Nzf/hoaG//Dw8P9R + UVH/S0tL/0xMTP9NTU3/7Ozs/4SEhP8zMzP/ZmZm//X19f9HR0f/Nzc3/z4+Pv91dXX/iIiI/zc3N/9W + Vlb/NTU1/6ysrP///////////3h4eP90dHT////////////9/f3/NDQ0/3Fxcf/Q0ND/vLy8/zg4OP97 + e3v///////j4+P/Hx8f/xMTE//b29v//////3Nzc/zMzM//Y2Nj//////9TU1P/j4+P/wcHB/+7u7v// + ////2NjY/76+vv/k5OT/////////////////eHh4/3R0dP////////////////9VVVX/OTk5/zk5Of88 + PDz/X19f/+Dg4P/////////////////////////////////19fX/cXFx//X19f////////////////// + //////////////////////////////////////////////94eHj/dHR0//////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////3h4eP90dHT///////////// + //////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////eHh4/3R0dP// + //////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////94 + eHj/X19f6v7+/v////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /////v7+/2FhYe03NzdcdHR0+qampv+np6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+n + p6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+np6f/p6en/6enp/+n + p6f/p6en/6enp/92dnb7Nzc3YQAAAAA+Pj4aNTU1QDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0AzMzNAMzMzQDMzM0Az + MzNAMzMzQDMzM0AzMzNANTU1QEBAQBwAAAAAgAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAEoAAAAEAAAACAAAAABACAAAAAAAAAEAAAT + CwAAEwsAAAAAAAAAAAAAWFhYUYeHh4+IiIiPiIiIj4iIiI+IiIiPiIiIj4iIiI+IiIiPiIiIj4iIiI+I + iIiPiIiIj4iIiI+IiIiPWVlZUrS0tPj///////////////////////////////////////////////// + /////////////////////////7a2tvm6urr//////8PDw//Dw8P/w8PD/+fn5/////////////////// + ////9PT0/8PDw//Dw8P/w8PD//Ly8v+8vLz/urq6//////+FhYX/hISE/3BwcP91dXX///////////// + /////////+jo6P+EhIT/hISE/2FhYf+cnJz/vLy8/7q6uv//////ioqK/3R0dP+ysrL/cnJy/8LCwv90 + dHT/dHR0/4CAgP/v7+//e3t7/3R0dP+lpaX/mZmZ/7y8vP+6urr//////0FBQf/S0tL/ycnJ/3Jycv+H + h4f/n5+f/9PT0/9PT0//xsbG/11dXf/T09P/q6ur/5mZmf+8vLz/urq6//////9HR0f//////9TU1P9y + cnL/h4eH/7+/v///////Wlpa/8bGxv9tbW3//////62trf+ZmZn/vLy8/7q6uv//////SkpK/0hISP9C + QkL/iIiI/5ycnP9AQED/SEhI/0JCQv/d3d3/Pz8//0hISP8+Pj7/rq6u/7y8vP+6urr///////////// + //////////////////////////////////////////////////////////////+8vLz/urq6///////V + 1dX//////9PT0//z8/P/v7+//+3t7f/s7Oz/29vb/9jY2P//////4ODg/8XFxf/9/f3/vLy8/7q6uv/+ + /v7/XFxc/8XFxf94eHj/dnZ2/4yMjP+VlZX/jo6O/9bW1v9mZmb/9vb2/2VlZf+cnJz/q6ur/7y8vP+6 + urr//v7+/0RERP96enr/iYmJ/4aGhv96enr/hYWF/3R0dP/Q0ND/S0tL/6Wlpf9mZmb/goKC/7u7u/+8 + vLz/urq6//7+/v9NTU3/gICA/3x8fP/9/f3/4uLi//39/f+dnZ3/8/Pz/+3t7f/r6+v/9fX1/+jo6P// + ////vLy8/7q6uv////////////////////////////////////////////////////////////////// + /////////7y8vP+2trb6//////////////////////////////////////////////////////////// + //////////////+3t7f7YWFhXJCQkJ+QkJCfkJCQn5CQkJ+QkJCfkJCQn5CQkJ+QkJCfkJCQn5CQkJ+Q + kJCfkJCQn5CQkJ+QkJCfYmJiXgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + + + \ No newline at end of file diff --git a/src/RetroGOG/retroGOG.ico b/src/RetroGOG/retroGOG.ico new file mode 100644 index 0000000..d251c32 Binary files /dev/null and b/src/RetroGOG/retroGOG.ico differ diff --git a/user_config.py b/user_config.py deleted file mode 100644 index 47dfd25..0000000 --- a/user_config.py +++ /dev/null @@ -1,14 +0,0 @@ -# enter path for your roms and RetroArch here. Put them between the quotation marks. -# Be sure to add a "/" at the end of each path. -# example: (this is also the standard RetroArch path, so if you didn't choose a specific folder for installing it, -# you can just copy the example path) -# emu_path = "C:/Users/USERNAME/AppData/Roaming/RetroArch/" - -emu_path = "" -rom_path = "" - -#Select the core you want to use. Standard is Mupen64Plus_Next. -# Mupen64Plus_Next = 1 -# ParaLLEl = 2 - -core = 1