Skip to content

Commit

Permalink
[UI] Added changelogs for all server
Browse files Browse the repository at this point in the history
  • Loading branch information
kevin0216 authored Dec 9, 2023
1 parent 1485d28 commit 41acbfe
Show file tree
Hide file tree
Showing 6 changed files with 230 additions and 99 deletions.
8 changes: 3 additions & 5 deletions utils/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ def __init__(self):
"""fetch from database"""
try:
with open(self._cache_path, "rb") as f:
self._cache = json_decode(f.read())
self._cache: dict = json_decode(f.read())

shutil.copyfile(self._cache_path, self._bak_cache_path)
except DecodeError:
with open(self._bak_cache_path, "rb") as bak_f:
self._cache = json_decode(bak_f.read(), type)
self._cache: dict = json_decode(bak_f.read(), type)

shutil.copyfile(self._bak_cache_path, self._cache_path)

Expand All @@ -30,9 +30,7 @@ async def update_cache(self, new_data: dict) -> None:
try:
with open(self._cache_path, "rb") as f:
if debug: print("[DEBUG | Cache Module] Loading Cache from disk")

data = json_decode(f.read())

if debug: print("[DEBUG | Cache Module] Cache file okay!")

shutil.copyfile(self._cache_path, self._bak_cache_path)
Expand Down Expand Up @@ -62,7 +60,7 @@ async def update_cache(self, new_data: dict) -> None:
)

# Pause here to prevent asyncio thread lockdown
await asyncio.sleep(0.1)
await asyncio.sleep(0.02)

with open(self._cache_path, "wb"):
# clear whole cache file
Expand Down
2 changes: 1 addition & 1 deletion utils/data.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"default": {"volume_level": 100, "multitype_remembered": false, "multitype_choice": ""}, "844597380170252348": {"volume_level": 50, "multitype_remembered": false, "multitype_choice": ""}}
{"default": {"volume_level": 100, "multitype_remembered": false, "multitype_choice": "", "changelogs_latestversion": ""}, "844597380170252348": {"volume_level": 50, "multitype_remembered": false, "multitype_choice": ""}, "642704558551728181": {"changelogs_latestversion": "m.20231209.linkandui-ce"}}
83 changes: 12 additions & 71 deletions utils/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import asyncio, json, os, time
import dotenv
import validators
from .cache import CacheWorker

import discord
from discord.ext import commands
Expand All @@ -12,77 +11,11 @@
import wavelink
from wavelink.ext import spotify
from .playlist import Playlist, SpotifyAlbum, SpotifyPlaylist, LoopState
from .storage import GuildInfo
from .cache import CacheWorker

INF = int(1e18)


class GuildInfo:
def __init__(self, guild_id):
self.guild_id: int = guild_id
self.text_channel: discord.TextChannel = None
self._task: asyncio.Task = None
self._refresh_msg_task: asyncio.Task = None
self._timer: asyncio.Task = None
self._dsa: bool = None
self._multitype_remembered: bool = None
self._multitype_choice: str = None
self._timer_done: bool = None

@property
def data_survey_agreement(self):
if self._dsa is None:
self._dsa = self.fetch("dsa")
return self._dsa

@data_survey_agreement.setter
def data_survey_agreement(self, value: bool):
self._dsa = value
self.update("dsa", value)

@property
def multitype_remembered(self):
if self._multitype_remembered is None:
self._multitype_remembered = self.fetch("multitype_remembered")
return self._multitype_remembered

@multitype_remembered.setter
def multitype_remembered(self, value: bool):
self._multitype_remembered = value
self.update("multitype_remembered", value)

@property
def multitype_choice(self):
if self._multitype_choice is None:
self._multitype_choice = self.fetch("multitype_choice")
return self._multitype_choice

@multitype_choice.setter
def multitype_choice(self, value: str):
self._multitype_choice = value
self.update("multitype_choice", value)

def fetch(self, key: str) -> not None:
"""fetch from database"""
with open(rf"{os.getcwd()}/utils/data.json", "r") as f:
data: dict = json.load(f)
if (
data.get(str(self.guild_id)) is None
or data[str(self.guild_id)].get(key) is None
):
return data["default"][key]
return data[str(self.guild_id)][key]

def update(self, key: str, value: str) -> None:
"""update database"""

with open(rf"{os.getcwd()}/utils/data.json", "r") as f:
data: dict = json.load(f)
if data.get(str(self.guild_id)) is None:
data[str(self.guild_id)] = dict()
data[str(self.guild_id)][key] = value
with open(rf"{os.getcwd()}/utils/data.json", "w") as f:
json.dump(data, f)

class Player:
def __init__(self, bot: commands.Bot):
self.bot = bot
Expand Down Expand Up @@ -304,6 +237,7 @@ async def resolve_ui(self):
@app_commands.command(name="help", description="❓ | 不知道怎麼使用我嗎?來這裡就對了~")
async def help(self, interaction: discord.Interaction):
await self.ui.Survey.SendSurvey(interaction) # 202308 Survey
await self.ui.Changelogs.SendChangelogs(interaction)
await self.ui.Help.Help(interaction)

##############################################
Expand Down Expand Up @@ -439,13 +373,15 @@ async def skip(self, interaction: discord.Interaction):
@app_commands.command(name="np", description="▶️ | 查看現在在播放什麼!")
async def nowplaying(self, interaction: discord.Interaction):
await self.ui.Survey.SendSurvey(interaction) # 202308 Survey
await self.ui.Changelogs.SendChangelogs(interaction)
await self.ui.PlayerControl.NowPlaying(interaction)

##############################################

@app_commands.command(name="stop", description="⏹️ | 停止音樂並清除待播清單")
async def stop(self, interaction: discord.Interaction):
await self.ui.Survey.SendSurvey(interaction) # 202308 Survey
await self.ui.Changelogs.SendChangelogs(interaction)
try:
await self._stop(interaction.guild)
await self.ui.PlayerControl.StopSucceed(interaction)
Expand Down Expand Up @@ -636,7 +572,7 @@ async def play(
tmpmsg = await interaction.original_response()
await tmpmsg.delete()

async def _suggest_processing(self, result: list, track, data: dict, final: bool, set_completed):
async def _suggest_processing(self, result: list, track, data: dict, final: bool, set_completed: Callable[[], None]):
if self._cache.get(track.identifier) is not None:
expired = (
int(time.time())
Expand Down Expand Up @@ -697,7 +633,11 @@ def set_completed():
for i in range(len(tracks)):
if i == 16:
break


# WTF IS THIS, THIS IS WAY FASTER?
# EDIT: This is faster than past versions
# BUT it isn't because of the usage of asyncio
# It's because the shit coding (put asyncio.sleep inside for loop)
self.bot.loop.create_task(self._suggest_processing(result, tracks[i], data, (i == len(tracks) - 1) or (i == 15), set_completed))

while not is_completed[0]:
Expand All @@ -715,6 +655,7 @@ def set_completed():
@discord.app_commands.autocomplete(search=get_search_suggest)
async def _i_play(self, interaction: discord.Interaction, search: str):
await self.ui.Survey.SendSurvey(interaction) # 202308 Survey
await self.ui.Changelogs.SendChangelogs(interaction)
if validators.url(search):
if (
"list" in search
Expand Down
105 changes: 105 additions & 0 deletions utils/storage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
from typing import *

import discord
import asyncio
import json
import os

class GuildInfo:
def __init__(self, guild_id):
self.guild_id: int = guild_id
self.text_channel: discord.TextChannel = None
self._task: asyncio.Task = None
self._refresh_msg_task: asyncio.Task = None
self._timer: asyncio.Task = None
self._dsa: bool = None
self._multitype_remembered: bool = None
self._multitype_choice: str = None
self._timer_done: bool = None
self._changelogs_latestversion: str = None

@property
def data_survey_agreement(self):
if self._dsa is None:
self._dsa = self.fetch("dsa")
return self._dsa

@data_survey_agreement.setter
def data_survey_agreement(self, value: bool):
self._dsa = value
self.update("dsa", value)

@property
def multitype_remembered(self):
if self._multitype_remembered is None:
self._multitype_remembered = self.fetch("multitype_remembered")
return self._multitype_remembered

@multitype_remembered.setter
def multitype_remembered(self, value: bool):
self._multitype_remembered = value
self.update("multitype_remembered", value)

@property
def multitype_choice(self):
if self._multitype_choice is None:
self._multitype_choice = self.fetch("multitype_choice")
return self._multitype_choice

@multitype_choice.setter
def multitype_choice(self, value: str):
self._multitype_choice = value
self.update("multitype_choice", value)

@property
def changelogs_latestversion(self):
if self._changelogs_latestversion is None:
self._changelogs_latestversion = self.fetch("changelogs_latestversion")
return self._changelogs_latestversion

@changelogs_latestversion.setter
def changelogs_latestversion(self, value: str):
self._changelogs_latestversion = value
self.update("changelogs_latestversion", value)

def fetch(self, key: str) -> not None:
"""fetch from database"""
with open(rf"{os.getcwd()}/utils/data.json", "r") as f:
data: dict = json.load(f)
if (
data.get(str(self.guild_id)) is None
or data[str(self.guild_id)].get(key) is None
):
return data["default"][key]
return data[str(self.guild_id)][key]

def update(self, key: str, value: str) -> None:
"""update database"""

with open(rf"{os.getcwd()}/utils/data.json", "r") as f:
data: dict = json.load(f)
if data.get(str(self.guild_id)) is None:
data[str(self.guild_id)] = dict()
data[str(self.guild_id)][key] = value
with open(rf"{os.getcwd()}/utils/data.json", "w") as f:
json.dump(data, f)

class GuildUIInfo:
def __init__(self, guild_id):
self.guild_id: int = guild_id
self.auto_stage_available: bool = True
self.stage_topic_exist: bool = False
self.stage_topic_checked: bool = False
self.skip: bool = False
self.lastskip: bool = False
self.search: bool = False
self.lasterrorinfo: dict = {}
self.leaveoperation: bool = False
self.playinfo: Coroutine[Any, Any, discord.Message] = None
self.playinfo_view: discord.ui.View = None
self.processing_msg: discord.Message = None
self.music_suggestion: bool = False
self.suggestions_source = None
self.searchmsg: Coroutine[Any, Any, discord.Message] = None
self.previous_titles: list[str] = []
self.suggestions: list = []
33 changes: 11 additions & 22 deletions utils/ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from discord.ext import commands
import datetime
from enum import Enum, auto
from .storage import GuildUIInfo

# Just for fetching current year
cdt = datetime.datetime.now().date()
Expand Down Expand Up @@ -52,27 +53,6 @@ def _sec_to_hms(seconds, format) -> str:

from .player import MusicCog

class GuildUIInfo:
def __init__(self, guild_id):
self.guild_id: int = guild_id
self.auto_stage_available: bool = True
self.stage_topic_exist: bool = False
self.stage_topic_checked: bool = False
self.skip: bool = False
self.lastskip: bool = False
self.search: bool = False
self.lasterrorinfo: dict = {}
self.leaveoperation: bool = False
self.playinfo: Coroutine[Any, Any, discord.Message] = None
self.playinfo_view: discord.ui.View = None
self.processing_msg: discord.Message = None
self.music_suggestion: bool = False
self.suggestions_source = None
self.searchmsg: Coroutine[Any, Any, discord.Message] = None
self.previous_titles: list[str] = []
self.suggestions: list = []


class LeaveType(Enum):
ByCommand = auto()
ByButton = auto()
Expand Down Expand Up @@ -249,11 +229,20 @@ def __init__(self, music_bot, botversion):
self.Leave,
)

# Survey Section
##########
# Survey #
##########
from .ui_comp.survey import Survey

self.Survey = Survey()

#############
# Changelog #
#############
from .ui_comp.changelog import Changelogs

self.Changelogs = Changelogs()

##########
# Volume # Deprecated for now (might be used in the future)
##########
Expand Down
Loading

0 comments on commit 41acbfe

Please sign in to comment.