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

Music tracking

This commit is contained in:
Steffo 2018-03-11 20:03:21 +01:00
parent f4804276d9
commit c55f1acf85
WARNING! Although there is a key with this ID in the database it does not verify this commit! This commit is SUSPICIOUS.
GPG key ID: C27544372FBB445D
4 changed files with 77 additions and 16 deletions

13
db.py
View file

@ -661,6 +661,19 @@ class BaluRage(Base):
return f"<BaluRage {self.id}>" return f"<BaluRage {self.id}>"
class PlayedMusic(Base):
__tablename__ = "playedmusic"
id = Column(Integer, primary_key=True)
enqueuer_id = Column(Integer, ForeignKey("royals.id"))
enqueuer = relationship("Royal", lazy="joined")
filename = Column(String)
def __repr__(self):
return f"<PlayedMusic {self.filename}>"
# If run as script, create all the tables in the db # If run as script, create all the tables in the db
if __name__ == "__main__": if __name__ == "__main__":
print("Creating new tables...")
Base.metadata.create_all(bind=engine) Base.metadata.create_all(bind=engine)
print("Done!")

View file

@ -27,13 +27,19 @@ 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):
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)
await loop.run_in_executor(executor, session.close)
return user
class DurationError(Exception): class DurationError(Exception):
pass pass
class Video: class Video:
def __init__(self): def __init__(self):
self.user = None self.enqueuer = None
self.filename = None self.filename = None
self.ytdl_url = None self.ytdl_url = None
@ -43,7 +49,7 @@ class Video:
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) discord_user = await find_user(user)
self.user = discord_user.royal if discord_user is not None else None 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
@ -78,6 +84,13 @@ class Video:
with youtube_dl.YoutubeDL(ytdl_args) as ytdl: with youtube_dl.YoutubeDL(ytdl_args) as ytdl:
await loop.run_in_executor(executor, functools.partial(ytdl.download, [self.ytdl_url])) await loop.run_in_executor(executor, functools.partial(ytdl.download, [self.ytdl_url]))
async def add_to_db(self):
session = await loop.run_in_executor(executor, db.Session)
pm = db.PlayedMusic(enqueuer=self.enqueuer,
filename=self.filename)
session.add(pm)
await loop.run_in_executor(executor, session.commit)
await loop.run_in_executor(executor, session.close)
if __debug__: if __debug__:
version = "Dev" version = "Dev"
@ -107,13 +120,6 @@ 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 find_user(user: discord.User):
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)
return user
async def on_error(event, *args, **kwargs): async def on_error(event, *args, **kwargs):
type, exception, traceback = sys.exc_info() type, exception, traceback = sys.exc_info()
try: try:
@ -334,7 +340,7 @@ async def update_music_queue():
video = voice_queue.pop(0) video = voice_queue.pop(0)
if video.ytdl_url: if video.ytdl_url:
await client.send_message(client.get_channel(config["Discord"]["main_channel"]), await client.send_message(client.get_channel(config["Discord"]["main_channel"]),
f" E' iniziato il download di `{video.ytdl_url}`.") f"⬇️ E' iniziato il download di `{video.ytdl_url}`.")
try: try:
await video.download() await video.download()
except DurationError: except DurationError:
@ -355,6 +361,7 @@ async def update_music_queue():
f"▶ Ora in riproduzione in <#{voice_client.channel.id}>:\n" f"▶ Ora in riproduzione in <#{voice_client.channel.id}>:\n"
f"`{video.filename}`") f"`{video.filename}`")
await client.change_presence(game=discord.Game(name=video.filename, type=2)) await client.change_presence(game=discord.Game(name=video.filename, type=2))
await video.add_to_db()
def process(users_connection=None): def process(users_connection=None):

40
templates/music.html Normal file
View file

@ -0,0 +1,40 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Music - RYG</title>
<script src="{{ url_for('static', filename='sorttable.js') }}"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"
integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" href="{{ url_for('static', filename='royal.css') }}">
</head>
<body>
<div class="container">
<h1>
Royal Music
</h1>
<div id="music">
<h2>
File più ascoltati
</h2>
<table class="table table-hover sortable">
<thead>
<tr>
<th>File</th>
<th>Ascoltato</th>
</tr>
</thead>
<tbody>
{% for record in music_data %}
<tr>
<td>{{ record.filename }}</td>
<td sorttable_customkey="{{ record[1] }}">{{ record[1] }} volt{{ 'a' if record[1] == 1 else 'e' }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</body>
</html>

View file

@ -1,5 +1,6 @@
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 from db import Session, Royal, Steam, RocketLeague, Dota, Osu, Overwatch, LeagueOfLegends, Diario, Telegram, PlayedMusic
from sqlalchemy import func
app = Flask(__name__) app = Flask(__name__)
@ -28,12 +29,12 @@ 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("/challenge/1") @app.route("/music")
def page_challenge_one(): def page_music():
session = Session() session = Session()
result = session.execute(r"SELECT sum(osu.std_pp) + sum(osu.taiko_pp) + sum(osu.catch_pp) + sum(osu.mania_pp) total_pp FROM osu;").first()[0] music_data = session.query(PlayedMusic.filename, func.count(PlayedMusic.filename)).group_by(PlayedMusic.filename).all()
session.close() session.close()
return render_template("challenge1.html", starting=4959.518703999999, result=result, target=5200) return render_template("music.html", music_data=music_data)
if __name__ == "__main__": if __name__ == "__main__":