1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 19:44:20 +00:00

5.0a61: Possibly fix a race condition in play?

I have no way to test it
This commit is contained in:
Steffo 2019-09-30 19:07:30 +02:00
parent a8d637a27b
commit e3770adda8
8 changed files with 43 additions and 29 deletions

View file

@ -17,17 +17,20 @@ import keyring
help="The names of the command pack modules that should be imported.") help="The names of the command pack modules that should be imported.")
@click.option("-n", "--network-address", type=str, default=None, @click.option("-n", "--network-address", type=str, default=None,
help="The Network server URL to connect to.") help="The Network server URL to connect to.")
@click.option("--local-network-server/--no-local-network-server", default=True, @click.option("-l", "--local-network-server", is_flag=True, default=False,
help="Locally run a Network server, bind it to port 44444.") help="Locally run a Network server and bind it to port 44444. Overrides -n.")
@click.option("-s", "--secrets-name", type=str, default="__default__", @click.option("-s", "--secrets-name", type=str, default="__default__",
help="The name in the keyring that the secrets are stored with.") help="The name in the keyring that the secrets are stored with.")
@click.option("-v", "--verbose", is_flag=True, default=False,
help="Print all possible debug information.")
def run(telegram: typing.Optional[bool], def run(telegram: typing.Optional[bool],
discord: typing.Optional[bool], discord: typing.Optional[bool],
database: typing.Optional[str], database: typing.Optional[str],
command_packs: typing.List[str], command_packs: typing.List[str],
network_address: typing.Optional[str], network_address: typing.Optional[str],
local_network_server: bool, local_network_server: bool,
secrets_name: str): secrets_name: str,
verbose: bool):
# Get the network password # Get the network password
network_password = keyring.get_password(f"Royalnet/{secrets_name}", "network") network_password = keyring.get_password(f"Royalnet/{secrets_name}", "network")
@ -62,7 +65,7 @@ def run(telegram: typing.Optional[bool],
server_process = multiprocessing.Process(name="Network Server", server_process = multiprocessing.Process(name="Network Server",
target=r.network.NetworkServer("0.0.0.0", target=r.network.NetworkServer("0.0.0.0",
44444, 44444,
network_password).run_blocking(), network_password).run_blocking,
daemon=True) daemon=True)
server_process.start() server_process.start()
network_address = "ws://127.0.0.1:44444/" network_address = "ws://127.0.0.1:44444/"
@ -106,6 +109,7 @@ def run(telegram: typing.Optional[bool],
secrets_name=secrets_name) secrets_name=secrets_name)
telegram_process = multiprocessing.Process(name="Telegram Interface", telegram_process = multiprocessing.Process(name="Telegram Interface",
target=telegram_bot.run_blocking, target=telegram_bot.run_blocking,
args=(verbose,),
daemon=True) daemon=True)
telegram_process.start() telegram_process.start()
@ -118,6 +122,7 @@ def run(telegram: typing.Optional[bool],
secrets_name=secrets_name) secrets_name=secrets_name)
discord_process = multiprocessing.Process(name="Discord Interface", discord_process = multiprocessing.Process(name="Discord Interface",
target=discord_bot.run_blocking, target=discord_bot.run_blocking,
args=(verbose,),
daemon=True) daemon=True)
discord_process.start() discord_process.start()

View file

@ -63,13 +63,6 @@ class YtdlDiscord:
dfiles.append(dfile) dfiles.append(dfile)
return dfiles return dfiles
@classmethod
def create_and_ready_from_url(cls, url, **ytdl_args) -> typing.List["YtdlDiscord"]:
dfiles = cls.create_from_url(url, **ytdl_args)
for dfile in dfiles:
dfile.ready_up()
return dfiles
@property @property
def info(self) -> typing.Optional[YtdlInfo]: def info(self) -> typing.Optional[YtdlInfo]:
return self.ytdl_file.info return self.ytdl_file.info

View file

@ -217,6 +217,7 @@ class DiscordBot(GenericBot):
guild_music_data = self.music_data[guild] guild_music_data = self.music_data[guild]
for dfile in dfiles: for dfile in dfiles:
log.debug(f"Adding {dfile} to music_data") log.debug(f"Adding {dfile} to music_data")
dfile.ready_up()
guild_music_data.add(dfile) guild_music_data.add(dfile)
if guild_music_data.now_playing is None: if guild_music_data.now_playing is None:
await self.advance_music_data(guild) await self.advance_music_data(guild)

View file

@ -190,6 +190,13 @@ class GenericBot:
"""A blocking coroutine that should make the bot start listening to commands and requests.""" """A blocking coroutine that should make the bot start listening to commands and requests."""
raise NotImplementedError() raise NotImplementedError()
def run_blocking(self): def run_blocking(self, verbose=False):
if verbose:
core_logger = logging.getLogger("royalnet")
core_logger.setLevel(logging.DEBUG)
stream_handler = logging.StreamHandler()
stream_handler.formatter = logging.Formatter("{asctime}\t{name}\t{levelname}\t{message}", style="{")
core_logger.addHandler(stream_handler)
core_logger.debug("Logging setup complete.")
self._initialize() self._initialize()
self.loop.run_until_complete(self.run()) self.loop.run_until_complete(self.run())

View file

@ -39,9 +39,9 @@ class PlayNH(NetworkHandler):
} }
# Start downloading # Start downloading
if data["url"].startswith("http://") or data["url"].startswith("https://"): if data["url"].startswith("http://") or data["url"].startswith("https://"):
dfiles: typing.List[YtdlDiscord] = await asyncify(YtdlDiscord.create_and_ready_from_url, data["url"], **ytdl_args) dfiles: typing.List[YtdlDiscord] = await asyncify(YtdlDiscord.create_from_url, data["url"], **ytdl_args)
else: else:
dfiles = await asyncify(YtdlDiscord.create_and_ready_from_url, f"ytsearch:{data['url']}", **ytdl_args) dfiles = await asyncify(YtdlDiscord.create_from_url, f"ytsearch:{data['url']}", **ytdl_args)
await bot.add_to_music_data(dfiles, guild) await bot.add_to_music_data(dfiles, guild)
# Create response dictionary # Create response dictionary
response = { response = {

View file

@ -44,10 +44,10 @@ class ZawarudoNH(NetworkHandler):
"outtmpl": f"./downloads/{datetime.datetime.now().timestamp()}_%(title)s.%(ext)s" "outtmpl": f"./downloads/{datetime.datetime.now().timestamp()}_%(title)s.%(ext)s"
} }
# Start downloading # Start downloading
zw_start: typing.List[YtdlDiscord] = await asyncify(YtdlDiscord.create_and_ready_from_url, zw_start: typing.List[YtdlDiscord] = await asyncify(YtdlDiscord.create_from_url,
"https://scaleway.steffo.eu/jojo/zawarudo_intro.mp3", "https://scaleway.steffo.eu/jojo/zawarudo_intro.mp3",
**ytdl_args) **ytdl_args)
zw_end: typing.List[YtdlDiscord] = await asyncify(YtdlDiscord.create_and_ready_from_url, zw_end: typing.List[YtdlDiscord] = await asyncify(YtdlDiscord.create_from_url,
"https://scaleway.steffo.eu/jojo/zawarudo_outro.mp3", "https://scaleway.steffo.eu/jojo/zawarudo_outro.mp3",
**ytdl_args) **ytdl_args)
old_playlist = bot.music_data[guild] old_playlist = bot.music_data[guild]

View file

@ -40,10 +40,7 @@ class NetworkServer:
self.port: int = port self.port: int = port
self.required_secret: str = required_secret self.required_secret: str = required_secret
self.identified_clients: typing.List[ConnectedClient] = [] self.identified_clients: typing.List[ConnectedClient] = []
if loop is None: self.loop = loop
self._loop = asyncio.get_event_loop()
else:
self._loop = loop
def find_client(self, *, nid: str = None, link_type: str = None) -> typing.List[ConnectedClient]: def find_client(self, *, nid: str = None, link_type: str = None) -> typing.List[ConnectedClient]:
assert not (nid and link_type) assert not (nid and link_type)
@ -91,7 +88,7 @@ class NetworkServer:
pass pass
# Otherwise, route the package to its destination # Otherwise, route the package to its destination
# noinspection PyAsyncCall # noinspection PyAsyncCall
self._loop.create_task(self.route_package(package)) self.loop.create_task(self.route_package(package))
def find_destination(self, package: Package) -> typing.List[ConnectedClient]: def find_destination(self, package: Package) -> typing.List[ConnectedClient]:
"""Find a list of destinations for the package. """Find a list of destinations for the package.
@ -129,14 +126,25 @@ class NetworkServer:
await destination.send(specific_package) await destination.send(specific_package)
async def serve(self): async def serve(self):
await websockets.serve(self.listener, host=self.address, port=self.port) log.debug(f"Serving on ws://{self.address}:{self.port}")
await websockets.serve(self.listener, host=self.address, port=self.port, loop=self.loop)
log.debug(f"Serve has finished?!")
async def run(self): async def run(self):
log.debug(f"Starting main server loop for <server> on ws://{self.address}:{self.port}") if self.loop is None:
self.loop = asyncio.get_event_loop()
log.debug(f"Starting main server loop on ws://{self.address}:{self.port}")
# noinspection PyAsyncCall # noinspection PyAsyncCall
self._loop.create_task(self.serve()) await self.serve()
# Just to be sure it has started on Linux
await asyncio.sleep(0.5)
def run_blocking(self): def run_blocking(self, verbose=False):
self._loop.run_until_complete(self.run()) if verbose:
core_logger = _logging.getLogger("royalnet")
core_logger.setLevel(_logging.DEBUG)
stream_handler = _logging.StreamHandler()
stream_handler.formatter = _logging.Formatter("{asctime}\t{name}\t{levelname}\t{message}", style="{")
core_logger.addHandler(stream_handler)
core_logger.debug("Logging setup complete.")
if self.loop is None:
self.loop = asyncio.get_event_loop()
self.loop.run_until_complete(self.run())

View file

@ -1 +1 @@
semantic = "5.0a60" semantic = "5.0a61"