Skip to content

Commit

Permalink
Fix setup.py merge conflicts
Browse files Browse the repository at this point in the history
  • Loading branch information
sousa-andre committed Feb 2, 2021
2 parents 66d00b2 + 1e6e7d3 commit c5a688b
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 36 deletions.
2 changes: 1 addition & 1 deletion lcu_driver/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
from .connector import Connector
from .connector import Connector, MultipleClientConnector

16 changes: 9 additions & 7 deletions lcu_driver/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ def __init__(self, connector, process_or_string: Union[Process, str]):
if isinstance(process_or_string, Process):
process_args = parse_cmdline_args(process_or_string.cmdline())

self._lcu_pid = process_or_string.pid
self._pid = int(process_args['app-pid'])
self._port = int(process_args['app-port'])
self._auth_key = process_args['remoting-auth-token']
Expand All @@ -44,6 +45,7 @@ def __init__(self, connector, process_or_string: Union[Process, str]):
elif isinstance(process_or_string, str):
lockfile_parts = process_or_string.split(':')

self._lcu_pid = int(lockfile_parts[0])
self._pid = int(lockfile_parts[1])
self._port = int(lockfile_parts[2])
self._auth_key = lockfile_parts[3]
Expand All @@ -57,12 +59,13 @@ async def init(self):
self.session = aiohttp.ClientSession(auth=aiohttp.BasicAuth('riot', self._auth_key), headers=self._headers)
setattr(self, 'request', self.request)

self._connector.register_connection(self)
tasks = [asyncio.create_task(self._connector.run_event('open', self))]
await self._wait_api_ready()

tasks.append(asyncio.create_task(self._connector.run_event('ready', self)))
try:
if len(self._connector.ws.registered_uris) > 0:
if self._connector.should_run_ws:
await self.run_ws()
except ClientConnectorError:
logger.info('Client closed unexpectedly')
Expand All @@ -72,7 +75,7 @@ async def init(self):

async def _close(self):
await self._connector.run_event('close', self)
self._connector.remove_connection()
self._connector.unregister_connection(self._lcu_pid)
await self.session.close()

@property
Expand Down Expand Up @@ -145,11 +148,10 @@ def _produce_url(self, endpoint: str, **kwargs):
async def request(self, method: str, endpoint: str, **kwargs):
"""Run an HTTP request against the API
:param method: HTTP method
:type method: str
:param endpoint: Request Endpoint
:type endpoint: str
:param kwargs: Arguments for `aiohttp.Request <https://docs.aiohttp.org/en/stable/client_reference.html#aiohttp.request>`_. The **data** keyworded argument will be JSON encoded automatically.
:param method: HTTP method :type method: str :param endpoint: Request Endpoint :type endpoint: str :param
kwargs: Arguments for `aiohttp.Request
<https://docs.aiohttp.org/en/stable/client_reference.html#aiohttp.request>`_. The **data** keyworded argument
will be JSON encoded automatically.
"""
url = self._produce_url(endpoint, **kwargs)
if kwargs.get('data'):
Expand Down
96 changes: 80 additions & 16 deletions lcu_driver/connector.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,51 @@
import asyncio
import logging
from abc import ABC
from sys import platform
from typing import Union

from psutil import Process
import time
from abc import ABC, abstractmethod

from .connection import Connection
from .events.managers import ConnectorEventManager, WebsocketEventManager
from .utils import _return_ux_process_when_available
from .utils import _return_ux_process

logger = logging.getLogger('lcu-driver')


class BaseConnector(ConnectorEventManager):
class BaseConnector(ConnectorEventManager, ABC):
def __init__(self, loop=None):
super().__init__()
self.loop = loop or asyncio.get_event_loop()
self.ws = WebsocketEventManager()
self.connection = None

def create_connection(self, process_or_string: Union[Process, str]):
@abstractmethod
def register_connection(self, connection: Connection):
"""Creates a connection and saves a reference to it"""
connection = Connection(self, process_or_string)
self.connection = connection
pass

def remove_connection(self):
@abstractmethod
def unregister_connection(self, lcu_pid):
"""Cancel the connection"""
self.connection = None
pass

@property
def should_run_ws(self) -> bool:
return True


class Connector(BaseConnector):
def __init__(self, *, loop=None):
super().__init__(loop)
self._repeat_flag = True
self.connection = None

def register_connection(self, connection):
self.connection = connection

def unregister_connection(self, _):
self.connection = None

@property
def should_run_ws(self) -> bool:
return len(self.ws.registered_uris) > 0

def start(self) -> None:
"""Starts the connector. This method should be overridden if different behavior is required.
Expand All @@ -42,9 +54,14 @@ def start(self) -> None:
"""
try:
def wrapper():
connection = _return_ux_process_when_available()
self.create_connection(connection)
self.loop.run_until_complete(self.connection.init())
process = next(_return_ux_process(), None)
while not process:
process = next(_return_ux_process(), None)
time.sleep(0.5)

connection = Connection(self, process)
self.register_connection(connection)
self.loop.run_until_complete(connection.init())

if self._repeat_flag and len(self.ws.registered_uris) > 0:
logger.debug('Repeat flag=True. Looking for new clients.')
Expand All @@ -60,3 +77,50 @@ async def stop(self) -> None:
:rtype: None
"""
self._repeat_flag = False


class MultipleClientConnector(BaseConnector):
def __init__(self, *, loop=None):
super().__init__(loop=loop)
self.connections = []

def register_connection(self, connection):
self.connections.append(connection)

def unregister_connection(self, lcu_pid):
for index, connection in enumerate(self.connections):
if connection.pid == lcu_pid:
del connection[index]

@property
def should_run_ws(self) -> bool:
return True

def _process_was_initialized(self, non_initialized_connection):
for connection in self.connections:
if non_initialized_connection.pid == connection.pid:
return True
return False

async def _astart(self):
tasks = []
try:
while True:
process_iter = _return_ux_process()

process = next(process_iter, None)
while process:
connection = Connection(self, process)
if not self._process_was_initialized(connection):
tasks.append(asyncio.create_task(connection.init()))

process = next(process_iter, None)
await asyncio.sleep(0.5)

except KeyboardInterrupt:
logger.info('Event loop interrupted by keyboard')
finally:
await asyncio.gather(*tasks)

def start(self) -> None:
self.loop.run_until_complete(self._astart())
16 changes: 4 additions & 12 deletions lcu_driver/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Dict, List, Optional
from typing import Dict, Generator

from psutil import process_iter, Process

Expand All @@ -12,15 +12,7 @@ def parse_cmdline_args(cmdline_args) -> Dict[str, str]:
return cmdline_args_parsed


def return_process(process_name: List[str]) -> Optional[Process]:
def _return_ux_process() -> Generator[Process, None, None]:
for process in process_iter():
if process.name() in process_name:
return process
return None


def _return_ux_process_when_available() -> Process:
process = None
while not process:
process = return_process(['LeagueClientUx.exe', 'LeagueClientUx'])
return process
if process.name() in ['LeagueClientUx.exe', 'LeagueClientUx']:
yield process
4 changes: 4 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
from setuptools import setup

<<<<<<< HEAD
__version__ = '2.1.3'
=======
__version__ = '3.0.0a1'
>>>>>>> multiclients

with open('README.md', encoding='utf-8') as f:
long_description = f.read()
Expand Down

0 comments on commit c5a688b

Please sign in to comment.