Skip to content

Commit

Permalink
cleanup player restore logic and increase amount of metadata stored f…
Browse files Browse the repository at this point in the history
…or restore
  • Loading branch information
Drapersniper committed Apr 3, 2022
1 parent 19c90e8 commit 1d979f1
Show file tree
Hide file tree
Showing 15 changed files with 256 additions and 61 deletions.
4 changes: 3 additions & 1 deletion redbot/cogs/audio/apis/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -1004,7 +1004,9 @@ async def autoplay(self, player: lavalink.Player, playlist_api: PlaylistWrapper)
if notify_channel_id:
await self.config.guild_from_id(
guild_id=player.guild.id
).currently_auto_playing_in.set([notify_channel_id, player.channel.id])
).currently_auto_playing_in.set(
[notify_channel_id, player.channel.id, player.paused, player.volume]
)
else:
await self.config.guild_from_id(
guild_id=player.guild.id
Expand Down
9 changes: 8 additions & 1 deletion redbot/cogs/audio/apis/persist_queue_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from types import SimpleNamespace
from typing import TYPE_CHECKING, List, Union

import discord
import lavalink
from red_commons.logging import getLogger

Expand Down Expand Up @@ -114,12 +115,18 @@ async def drop(self, guild_id: int):
self.database.cursor().execute, PERSIST_QUEUE_BULK_PLAYED, ({"guild_id": guild_id})
)

async def enqueued(self, guild_id: int, room_id: int, track: lavalink.Track):
async def enqueued(
self, guild_id: int, room_id: int, track: lavalink.Track, requester: discord.Member = None
) -> None:
enqueue_time = track.extras.get("enqueue_time", 0)
if enqueue_time == 0:
track.extras["enqueue_time"] = int(time.time())
track_identifier = track.track_identifier
track = self.cog.track_to_json(track)
if requester:
if "extras" not in track:
track["extras"] = {}
track["extras"]["requester"] = requester.id
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
executor.submit(
self.database.cursor().execute,
Expand Down
2 changes: 2 additions & 0 deletions redbot/cogs/audio/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ def __init__(self, bot: Red):
default_guild = dict(
auto_play=False,
currently_auto_playing_in=None,
last_known_vc_and_notify_channels=None,
last_known_track={},
auto_deafen=True,
autoplaylist=dict(
enabled=True,
Expand Down
15 changes: 15 additions & 0 deletions redbot/cogs/audio/core/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from collections import Counter, defaultdict
from pathlib import Path
from typing import (
Iterable,
Set,
TYPE_CHECKING,
Any,
Expand Down Expand Up @@ -549,6 +550,10 @@ async def _load_v2_playlist(
def format_time(self, time: int) -> str:
raise NotImplementedError()

@abstractmethod
async def save_player_state(self) -> None:
raise NotImplementedError()

@abstractmethod
async def get_lyrics_status(self, ctx: Context) -> bool:
raise NotImplementedError()
Expand Down Expand Up @@ -576,3 +581,13 @@ async def self_deafen(self, player: lavalink.Player) -> None:
@abstractmethod
def can_join_and_speak(self, channel: discord.VoiceChannel) -> bool:
raise NotImplementedError()

@abstractmethod
async def update_guild_config(
self, *values: Dict[int, List[Tuple[str, Union[str, int, float, bool, None, dict, list]]]]
):
raise NotImplementedError()

@abstractmethod
async def clean_up_guild_config(self, *keys: str, guild_ids: Optional[Iterable[int]] = None):
raise NotImplementedError()
1 change: 1 addition & 0 deletions redbot/cogs/audio/core/commands/audioset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1447,6 +1447,7 @@ async def command_audioset_restart(self, ctx: commands.Context):
"""Restarts the lavalink connection."""
async with ctx.typing():
try:
await self.save_player_state()
await lavalink.close(self.bot)
self.lavalink_restart_connect(manual=True)
except ProcessLookupError:
Expand Down
18 changes: 12 additions & 6 deletions redbot/cogs/audio/core/commands/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,14 @@ async def command_disconnect(self, ctx: commands.Context):
await self.config.custom("EQUALIZER", ctx.guild.id).eq_bands.set(eq.bands)
await player.stop()
await player.disconnect()
await self.config.guild_from_id(guild_id=ctx.guild.id).currently_auto_playing_in.set(
[]
)
self._ll_guild_updates.discard(ctx.guild.id)
await self.api_interface.persistent_queue_api.drop(ctx.guild.id)
await self.clean_up_guild_config(
"last_known_vc_and_notify_channels",
"last_known_track",
"currently_auto_playing_in",
guild_ids=[ctx.guild.id],
)

@commands.command(name="now")
@commands.guild_only()
Expand Down Expand Up @@ -590,11 +593,14 @@ async def command_stop(self, ctx: commands.Context):
player.store("requester", None)
player.store("autoplay_notified", False)
await player.stop()
await self.config.guild_from_id(guild_id=ctx.guild.id).currently_auto_playing_in.set(
[]
)
await self.send_embed_msg(ctx, title=_("Stopping..."))
await self.api_interface.persistent_queue_api.drop(ctx.guild.id)
await self.clean_up_guild_config(
"last_known_vc_and_notify_channels",
"last_known_track",
"currently_auto_playing_in",
guild_ids=[ctx.guild.id],
)

@commands.command(name="summon")
@commands.guild_only()
Expand Down
2 changes: 2 additions & 0 deletions redbot/cogs/audio/core/commands/llset.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ async def command_llsetup_unmanaged(self, ctx: commands.Context):
),
)
try:
await self.save_player_state()
await lavalink.close(self.bot)
self.lavalink_restart_connect(manual=True)
except ProcessLookupError:
Expand Down Expand Up @@ -1168,6 +1169,7 @@ async def command_llsetup_reset(self, ctx: commands.Context):
global_data["use_external_lavalink"] = False

try:
await self.save_player_state()
await lavalink.close(self.bot)
self.lavalink_restart_connect(manual=True)
except ProcessLookupError:
Expand Down
10 changes: 8 additions & 2 deletions redbot/cogs/audio/core/events/cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,13 @@ async def on_red_audio_track_start(
player.store("autoplay_notified", False)
await player.stop()
await player.disconnect()
await self.config.guild_from_id(guild_id=guild.id).currently_auto_playing_in.set([])
await self.clean_up_guild_config(
"last_known_vc_and_notify_channels",
"last_known_track",
"currently_auto_playing_in",
guild_ids=[guild.id],
)
await self.api_interface.persistent_queue_api.drop(guild.id)
return

track_identifier = track.track_identifier
Expand Down Expand Up @@ -164,7 +170,7 @@ async def on_red_audio_track_enqueue(
persist_cache = self._persist_queue_cache.get(guild.id)
if persist_cache:
await self.api_interface.persistent_queue_api.enqueued(
guild_id=guild.id, room_id=track.extras["vc"], track=track
guild_id=guild.id, room_id=track.extras["vc"], track=track, requester=requester
)

@commands.Cog.listener()
Expand Down
11 changes: 11 additions & 0 deletions redbot/cogs/audio/core/events/dpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,13 +527,24 @@ async def cog_unload(self) -> None:

lavalink.unregister_event_listener(self.lavalink_event_handler)
lavalink.unregister_update_listener(self.lavalink_update_handler)
await self.save_player_state()
await lavalink.close(self.bot)
await self._close_database()
if self.managed_node_controller is not None:
await self.managed_node_controller.shutdown()

self.cog_cleaned_up = True

@commands.Cog.listener()
async def on_guild_remove(self, guild: discord.Guild) -> None:
await self.clean_up_guild_config(
"last_known_vc_and_notify_channels",
"last_known_track",
"currently_auto_playing_in",
guild_ids=[guild.id],
)
await self.api_interface.persistent_queue_api.drop(guild.id)

@commands.Cog.listener()
async def on_voice_state_update(
self, member: discord.Member, before: discord.VoiceState, after: discord.VoiceState
Expand Down
58 changes: 41 additions & 17 deletions redbot/cogs/audio/core/events/lavalink.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,13 @@ async def lavalink_event_handler(
await player.stop()
await player.disconnect()
if guild:
await self.config.guild_from_id(guild_id=guild.id).currently_auto_playing_in.set(
[]
await self.clean_up_guild_config(
"last_known_vc_and_notify_channels",
"last_known_track",
"currently_auto_playing_in",
guild_ids=[guild.id],
)
await self.api_interface.persistent_queue_api.drop(guild.id)
return
guild_id = self.rgetattr(guild, "id", None)
if not guild:
Expand Down Expand Up @@ -139,7 +143,7 @@ async def lavalink_event_handler(
notify_channel = player.fetch("notify_channel")
if notify_channel and autoplay:
await self.config.guild_from_id(guild_id=guild_id).currently_auto_playing_in.set(
[notify_channel, player.channel.id]
[notify_channel, player.channel.id, player.paused, player.volume]
)
else:
await self.config.guild_from_id(guild_id=guild_id).currently_auto_playing_in.set(
Expand Down Expand Up @@ -234,9 +238,13 @@ async def lavalink_event_handler(
"Queue ended for %s, Disconnecting bot due to configuration", guild_id
)
self.bot.dispatch("red_audio_audio_disconnect", guild)
await self.config.guild_from_id(
guild_id=guild_id
).currently_auto_playing_in.set([])
await self.clean_up_guild_config(
"last_known_vc_and_notify_channels",
"last_known_track",
"currently_auto_playing_in",
guild_ids=[guild.id],
)
await self.api_interface.persistent_queue_api.drop(guild.id)
# let audio buffer run out on slower machines (GH-5158)
await asyncio.sleep(2)
await player.disconnect()
Expand Down Expand Up @@ -276,9 +284,13 @@ async def lavalink_event_handler(
await self.config.custom("EQUALIZER", guild_id).eq_bands.set(eq.bands)
await player.stop()
await player.disconnect()
await self.config.guild_from_id(guild_id=guild_id).currently_auto_playing_in.set(
[]
await self.clean_up_guild_config(
"last_known_vc_and_notify_channels",
"last_known_track",
"currently_auto_playing_in",
guild_ids=[guild_id],
)
await self.api_interface.persistent_queue_api.drop(guild_id)
self._ll_guild_updates.discard(guild_id)
self.bot.dispatch("red_audio_audio_disconnect", guild)
if message_channel:
Expand Down Expand Up @@ -475,9 +487,13 @@ async def _websocket_closed_handler(
player.store("autoplay_notified", False)
await player.stop()
await player.disconnect()
await self.config.guild_from_id(
guild_id=guild_id
).currently_auto_playing_in.set([])
await self.clean_up_guild_config(
"last_known_vc_and_notify_channels",
"last_known_track",
"currently_auto_playing_in",
guild_ids=[guild_id],
)
await self.api_interface.persistent_queue_api.drop(guild_id)
else:
self.bot.dispatch("red_audio_audio_disconnect", guild)
ws_audio_log.info(
Expand All @@ -492,9 +508,13 @@ async def _websocket_closed_handler(
player.store("autoplay_notified", False)
await player.stop()
await player.disconnect()
await self.config.guild_from_id(
guild_id=guild_id
).currently_auto_playing_in.set([])
await self.clean_up_guild_config(
"last_known_vc_and_notify_channels",
"last_known_track",
"currently_auto_playing_in",
guild_ids=[guild_id],
)
await self.api_interface.persistent_queue_api.drop(guild_id)
elif code in (42069,) and has_perm and player.current and player.is_playing:
player.store("resumes", player.fetch("resumes", 0) + 1)
await player.connect(deafen=deafen)
Expand Down Expand Up @@ -580,9 +600,13 @@ async def _websocket_closed_handler(
player.store("autoplay_notified", False)
await player.stop()
await player.disconnect()
await self.config.guild_from_id(
guild_id=guild_id
).currently_auto_playing_in.set([])
await self.clean_up_guild_config(
"last_known_vc_and_notify_channels",
"last_known_track",
"currently_auto_playing_in",
guild_ids=[guild_id],
)
await self.api_interface.persistent_queue_api.drop(guild_id)
else:
if not player.paused and player.current:
player.store("resumes", player.fetch("resumes", 0) + 1)
Expand Down
23 changes: 14 additions & 9 deletions redbot/cogs/audio/core/tasks/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,32 +46,37 @@ async def player_automated_timer(self) -> None:
stop_times.pop(sid, None)
pause_times.pop(sid, None)
try:
player = lavalink.get_player(sid)
await self.clean_up_guild_config(
"last_known_vc_and_notify_channels",
"last_known_track",
"currently_auto_playing_in",
guild_ids=[sid],
)
await self.api_interface.persistent_queue_api.drop(sid)
player = lavalink.get_player(sid)
player.store("autoplay_notified", False)
await player.stop()
await player.disconnect()
await self.config.guild_from_id(
guild_id=sid
).currently_auto_playing_in.set([])
except Exception as exc:
log.debug(
"Exception raised in Audio's emptydc_timer for %s.", sid, exc_info=exc
)

elif sid in stop_times and await self.config.guild(server_obj).emptydc_enabled():
emptydc_timer = await self.config.guild(server_obj).emptydc_timer()
if (time.time() - stop_times[sid]) >= emptydc_timer:
stop_times.pop(sid)
try:
player = lavalink.get_player(sid)
await self.clean_up_guild_config(
"last_known_vc_and_notify_channels",
"last_known_track",
"currently_auto_playing_in",
guild_ids=[sid],
)
await self.api_interface.persistent_queue_api.drop(sid)
player = lavalink.get_player(sid)
player.store("autoplay_notified", False)
await player.stop()
await player.disconnect()
await self.config.guild_from_id(
guild_id=sid
).currently_auto_playing_in.set([])
except Exception as exc:
if "No such player for that guild" in str(exc):
stop_times.pop(sid, None)
Expand Down
Loading

0 comments on commit 1d979f1

Please sign in to comment.