1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-27 13:34:28 +00:00

a lot of stuff

This commit is contained in:
Steffo 2018-03-12 13:29:12 +01:00
parent 166dea459b
commit aae8cb90ff
5 changed files with 55 additions and 22 deletions

8
db.py
View file

@ -497,7 +497,7 @@ class Discord(Base):
avatar_hex = Column(String) avatar_hex = Column(String)
def __str__(self): def __str__(self):
return f"{self.username}#{self.discriminator}" return f"{self.name}#{self.discriminator}"
def __repr__(self): def __repr__(self):
return f"<Discord user {self.discord_id}>" return f"<Discord user {self.discord_id}>"
@ -526,7 +526,7 @@ class Discord(Base):
def avatar_url(self, size=256): def avatar_url(self, size=256):
if self.avatar_hex is None: if self.avatar_hex is None:
return "https://discordapp.com/assets/6debd47ed13483642cf09e832ed0bc1b.png" return "https://discordapp.com/assets/6debd47ed13483642cf09e832ed0bc1b.png"
return f"https://cdn.discordapp.com/avatars/{self.id}/{self.avatar}.png?size={size}" return f"https://cdn.discordapp.com/avatars/{self.discord_id}/{self.avatar_hex}.png?size={size}"
class Overwatch(Base): class Overwatch(Base):
@ -665,8 +665,8 @@ class PlayedMusic(Base):
__tablename__ = "playedmusic" __tablename__ = "playedmusic"
id = Column(Integer, primary_key=True) id = Column(Integer, primary_key=True)
enqueuer_id = Column(Integer, ForeignKey("royals.id")) enqueuer_id = Column(BigInteger, ForeignKey("discord.discord_id"))
enqueuer = relationship("Royal", lazy="joined") enqueuer = relationship("Discord", lazy="joined")
filename = Column(String) filename = Column(String)
def __repr__(self): def __repr__(self):

View file

@ -27,12 +27,14 @@ loop = asyncio.get_event_loop()
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read("config.ini") config.read("config.ini")
async def find_user(user: discord.User): async def find_user(user: discord.User):
session = await loop.run_in_executor(executor, db.Session) session = await loop.run_in_executor(executor, db.Session)
user = await loop.run_in_executor(executor, session.query(db.Discord).filter_by(discord_id=user.id).join(db.Royal).first) user = await loop.run_in_executor(executor, session.query(db.Discord).filter_by(discord_id=user.id).join(db.Royal).first)
await loop.run_in_executor(executor, session.close) await loop.run_in_executor(executor, session.close)
return user return user
class DurationError(Exception): class DurationError(Exception):
pass pass
@ -44,12 +46,11 @@ class Video:
self.ytdl_url = None self.ytdl_url = None
@staticmethod @staticmethod
async def init(user, filename=None, ytdl_url=None): async def init(user_id: str, *, filename=None, ytdl_url=None):
if filename is None and ytdl_url is None: if filename is None and ytdl_url is None:
raise Exception("Filename or url must be specified") raise Exception("Filename or url must be specified")
self = Video() self = Video()
discord_user = await find_user(user) self.enqueuer = int(user_id)
self.enqueuer = discord_user.royal if discord_user is not None else None
self.filename = filename self.filename = filename
self.ytdl_url = ytdl_url self.ytdl_url = ytdl_url
return self return self
@ -61,7 +62,7 @@ class Video:
if "entries" in info: if "entries" in info:
info = info["entries"][0] info = info["entries"][0]
file_id = info.get("title", str(hash(self.ytdl_url))) file_id = info.get("title", str(hash(self.ytdl_url)))
file_id = re.sub(r"(?:\/|\\|\?|\*|\"|<|>|\||:)", "_", file_id) file_id = re.sub(r'[/\\?*"<>|]', "_", file_id)
# Set the filename to the downloaded video # Set the filename to the downloaded video
self.filename = file_id self.filename = file_id
if os.path.exists(f"opusfiles/{file_id}.opus"): if os.path.exists(f"opusfiles/{file_id}.opus"):
@ -86,12 +87,13 @@ class Video:
async def add_to_db(self): async def add_to_db(self):
session = await loop.run_in_executor(executor, db.Session) session = await loop.run_in_executor(executor, db.Session)
pm = db.PlayedMusic(enqueuer=self.enqueuer, pm = db.PlayedMusic(enqueuer_id=self.enqueuer,
filename=self.filename) filename=self.filename)
session.add(pm) session.add(pm)
await loop.run_in_executor(executor, session.commit) await loop.run_in_executor(executor, session.commit)
await loop.run_in_executor(executor, session.close) await loop.run_in_executor(executor, session.close)
if __debug__: if __debug__:
version = "Dev" version = "Dev"
else: else:
@ -120,8 +122,9 @@ voice_queue: typing.List[Video] = []
# Init the executor # Init the executor
executor = concurrent.futures.ThreadPoolExecutor(max_workers=3) executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
async def on_error(event, *args, **kwargs): async def on_error(event, *args, **kwargs):
type, exception, traceback = sys.exc_info() t, exception, traceback = sys.exc_info()
try: try:
await client.send_message(client.get_channel(config["Discord"]["main_channel"]), await client.send_message(client.get_channel(config["Discord"]["main_channel"]),
f"☢️ ERRORE CRITICO NELL'EVENTO `{event}`\n" f"☢️ ERRORE CRITICO NELL'EVENTO `{event}`\n"
@ -200,10 +203,10 @@ async def on_message(message: discord.Message):
return return
# Se è una playlist, informa che potrebbe essere richiesto un po' di tempo # Se è una playlist, informa che potrebbe essere richiesto un po' di tempo
if "playlist" in url: if "playlist" in url:
await client.send_message(message.channel, f" Hai inviato una playlist al bot.\n" await client.send_message(message.channel, f"⚠ Le playlist non sono ancora supportate dal bot.\n"
f"L'elaborazione potrebbe richiedere un po' di tempo.") f"Prova mettendo i video singoli a mano!")
# If target is a single video # If target is a single video
video = await Video.init(user=message.author, ytdl_url=url) video = await Video.init(user_id=message.author.id, ytdl_url=url)
await client.send_message(message.channel, f"✅ Aggiunto alla coda: <{url}>") await client.send_message(message.channel, f"✅ Aggiunto alla coda: <{url}>")
voice_queue.append(video) voice_queue.append(video)
elif message.content.startswith("!search"): elif message.content.startswith("!search"):
@ -221,7 +224,7 @@ async def on_message(message: discord.Message):
"Sintassi corretta: `!search <titolo>`") "Sintassi corretta: `!search <titolo>`")
return return
# If target is a single video # If target is a single video
video = await Video.init(user=message.author, ytdl_url=f"ytsearch:{text}") video = await Video.init(user_id=message.author.id, ytdl_url=f"ytsearch:{text}")
await client.send_message(message.channel, f"✅ Aggiunto alla coda: `ytsearch:{text}`") await client.send_message(message.channel, f"✅ Aggiunto alla coda: `ytsearch:{text}`")
voice_queue.append(video) voice_queue.append(video)
elif message.content.startswith("!file"): elif message.content.startswith("!file"):
@ -239,7 +242,7 @@ async def on_message(message: discord.Message):
"Sintassi corretta: `!file <nomefile>`") "Sintassi corretta: `!file <nomefile>`")
return return
# If target is a single video # If target is a single video
video = await Video.init(user=message.author, filename=text) video = await Video.init(user_id=message.author.id, filename=text)
await client.send_message(message.channel, f"✅ Aggiunto alla coda: `{text}`") await client.send_message(message.channel, f"✅ Aggiunto alla coda: `{text}`")
voice_queue.append(video) voice_queue.append(video)
elif message.content.startswith("!skip"): elif message.content.startswith("!skip"):
@ -264,7 +267,7 @@ async def on_message(message: discord.Message):
if not len(voice_queue) > 1: if not len(voice_queue) > 1:
await client.send_message(message.channel, f"⚠ Non ci sono video da annullare.") await client.send_message(message.channel, f"⚠ Non ci sono video da annullare.")
return return
video = voice_queue.pop() voice_queue.pop()
await client.send_message(message.channel, f"❌ L'ultimo video aggiunto alla playlist è stato rimosso.") await client.send_message(message.channel, f"❌ L'ultimo video aggiunto alla playlist è stato rimosso.")
elif message.content.startswith("!stop"): elif message.content.startswith("!stop"):
if voice_player is None: if voice_player is None:

View file

@ -4,3 +4,5 @@ flask
sqlalchemy sqlalchemy
youtube-dl youtube-dl
requests requests
psycopg2
PyNaCl

View file

@ -26,14 +26,37 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% for record in music_data %} {% for record in music_counts %}
<tr> <tr>
<td>{{ record.filename }}</td> <td><a href="https://royal.steffo.eu/music/{{ record.filename }}.opus">{{ record.filename }}</a></td>
<td sorttable_customkey="{{ record[1] }}">{{ record[1] }} volt{{ 'a' if record[1] == 1 else 'e' }}</td> <td sorttable_customkey="{{ record[1] }}">{{ record[1] }} volt{{ 'a' if record[1] == 1 else 'e' }}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
</table> </table>
<h2>
Cronologia
</h2>
<table class="table table-hover">
<thead>
<tr>
<th>File</th>
<th>Aggiunto da</th>
</tr>
</thead>
<tbody>
{% for record in music_last %}
<tr>
<td><a href="https://royal.steffo.eu/music/{{ record.filename }}.opus">{{ record.filename }}</a></td>
{% if record.enqueuer is not none %}
<td><img class="thirtytwo round" src="{{ record.enqueuer.avatar_url(size=32) }}"> {{ record.enqueuer }}</td>
{% else %}
<td></td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div> </div>
</div> </div>
</body> </body>

View file

@ -1,5 +1,5 @@
from flask import Flask, render_template from flask import Flask, render_template
from db import Session, Royal, Steam, RocketLeague, Dota, Osu, Overwatch, LeagueOfLegends, Diario, Telegram, PlayedMusic from db import Session, Royal, Steam, RocketLeague, Dota, Osu, Overwatch, LeagueOfLegends, Diario, Telegram, PlayedMusic, Discord
from sqlalchemy import func from sqlalchemy import func
app = Flask(__name__) app = Flask(__name__)
@ -7,10 +7,12 @@ app = Flask(__name__)
app.jinja_env.trim_blocks = True app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True app.jinja_env.lstrip_blocks = True
@app.route("/") @app.route("/")
def page_index(): def page_index():
return render_template("index.html") return render_template("index.html")
@app.route("/diario") @app.route("/diario")
def page_diario(): def page_diario():
session = Session() session = Session()
@ -18,6 +20,7 @@ def page_diario():
session.close() session.close()
return render_template("diario.html", diario_data=diario_data) return render_template("diario.html", diario_data=diario_data)
@app.route("/leaderboards") @app.route("/leaderboards")
def page_leaderboards(): def page_leaderboards():
session = Session() session = Session()
@ -29,12 +32,14 @@ def page_leaderboards():
session.close() session.close()
return render_template("leaderboards.html", dota_data=dota_data, rl_data=rl_data, ow_data=ow_data, osu_data=osu_data, lol_data=lol_data) return render_template("leaderboards.html", dota_data=dota_data, rl_data=rl_data, ow_data=ow_data, osu_data=osu_data, lol_data=lol_data)
@app.route("/music") @app.route("/music")
def page_music(): def page_music():
session = Session() session = Session()
music_data = session.query(PlayedMusic.filename, func.count(PlayedMusic.filename)).group_by(PlayedMusic.filename).all() music_counts = session.query(PlayedMusic.filename, func.count(PlayedMusic.filename)).group_by(PlayedMusic.filename).all()
music_last = session.query(PlayedMusic).join(Discord).join(Royal).order_by(PlayedMusic.id.desc()).limit(50).all()
session.close() session.close()
return render_template("music.html", music_data=music_data) return render_template("music.html", music_counts=music_counts, music_last=music_last)
if __name__ == "__main__": if __name__ == "__main__":