Tidied the dashboard by adding a user drop down menu rather than having all users displayed on a single page
182 lines
7.1 KiB
Python
182 lines
7.1 KiB
Python
import sqlite3
|
|
from datetime import datetime
|
|
import traceback
|
|
|
|
DB_PATH = '/nddata/navidrome.db'
|
|
OUTPUT_HTML = '/app/public/index.html'
|
|
|
|
def get_all_users():
|
|
try:
|
|
conn = sqlite3.connect(DB_PATH)
|
|
cursor = conn.cursor()
|
|
cursor.execute("SELECT name FROM user")
|
|
users = [row[0] for row in cursor.fetchall()]
|
|
conn.close()
|
|
return users
|
|
except Exception as e:
|
|
print(f"Error fetching users: {e}")
|
|
return []
|
|
|
|
def get_aggregated_scrobbles(user_name):
|
|
try:
|
|
conn = sqlite3.connect(DB_PATH)
|
|
cursor = conn.cursor()
|
|
cursor.execute("""
|
|
SELECT
|
|
m.title,
|
|
m.artist,
|
|
COUNT(*) AS play_count,
|
|
MAX(s.submission_time) AS last_played
|
|
FROM scrobbles s
|
|
JOIN media_file m ON s.media_file_id = m.id
|
|
JOIN user u ON s.user_id = u.id
|
|
WHERE u.name = ?
|
|
GROUP BY m.title, m.artist
|
|
ORDER BY play_count DESC, last_played DESC, m.artist ASC
|
|
""", (user_name,))
|
|
rows = cursor.fetchall()
|
|
conn.close()
|
|
return rows
|
|
except Exception as e:
|
|
print(f"Error fetching scrobbles for {user_name}: {e}")
|
|
return []
|
|
|
|
def generate_html():
|
|
print("Fetching users from Navidrome DB...")
|
|
users = get_all_users()
|
|
print(f"Found users: {users}")
|
|
|
|
html_content = """<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Music Listening Dashboard - All-Time Top Tracks</title>
|
|
<style>
|
|
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #121212; color: #e0e0e0; margin: 0; padding: 20px; }
|
|
.header-container { display: flex; justify-content: space-between; align-items: center; max-width: 1200px; margin: 0 auto 20px auto; flex-wrap: wrap; gap: 15px; }
|
|
h1 { color: #fff; margin: 0; font-size: 24px; }
|
|
.controls { display: flex; align-items: center; gap: 15px; }
|
|
select { background: #1e1e1e; color: #e0e0e0; border: 1px solid #333; padding: 8px 12px; font-size: 14px; border-radius: 6px; outline: none; cursor: pointer; }
|
|
select:focus { border-color: #bb86fc; }
|
|
.refresh-btn { background: #bb86fc; color: #121212; border: none; padding: 9px 16px; font-size: 14px; font-weight: bold; border-radius: 6px; cursor: pointer; transition: background 0.2s; }
|
|
.refresh-btn:hover { background: #9965f4; }
|
|
.refresh-btn:disabled { background: #555; color: #888; cursor: not-allowed; }
|
|
.container { max-width: 1200px; margin: 0 auto; }
|
|
.card { background: #1e1e1e; border-radius: 10px; padding: 25px; box-shadow: 0 4px 10px rgba(0,0,0,0.4); display: none; }
|
|
.card.active { display: block; }
|
|
h2 { border-bottom: 2px solid #333; padding-bottom: 10px; color: #bb86fc; margin-top: 0; }
|
|
table { width: 100%; border-collapse: collapse; margin-top: 15px; }
|
|
th, td { text-align: left; padding: 10px; border-bottom: 1px solid #2c2c2c; font-size: 14px; }
|
|
th { color: #888; font-weight: 600; }
|
|
.time { color: #888; font-size: 12px; white-space: nowrap; }
|
|
.plays { text-align: center; font-weight: bold; color: #03dac6; }
|
|
.count { font-size: 13px; color: #aaa; margin-bottom: 15px; }
|
|
@media (max-width: 600px) {
|
|
body { padding: 10px; }
|
|
.header-container { flex-direction: column; align-items: stretch; text-align: center; }
|
|
.controls { justify-content: center; }
|
|
.card { padding: 15px; }
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="header-container">
|
|
<h1>All-Time Top Tracks & History</h1>
|
|
<div class="controls">
|
|
<div>
|
|
<label for="userSelect" style="margin-right: 8px; font-size: 14px; color: #888;">User:</label>
|
|
<select id="userSelect" onchange="switchUser()">
|
|
"""
|
|
|
|
for i, user in enumerate(users):
|
|
selected = "selected" if i == 0 else ""
|
|
html_content += f' <option value="{user}" {selected}>{user}</option>\n'
|
|
|
|
html_content += """ </select>
|
|
</div>
|
|
<button id="refreshBtn" class="refresh-btn" onclick="triggerRefresh()">Regenerate Stats</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="container">
|
|
"""
|
|
|
|
for i, user in enumerate(users):
|
|
print(f"Processing scrobbles for {user}...")
|
|
rows = get_aggregated_scrobbles(user)
|
|
active_class = " active" if i == 0 else ""
|
|
html_content += f"""
|
|
<div class="card{active_class}" id="user-card-{user}">
|
|
<h2>{user}</h2>
|
|
<div class="count">Unique tracks played: {len(rows)}</div>
|
|
<table>
|
|
<tr><th>Track</th><th>Artist</th><th class="plays">Plays</th><th class="time">Last Played</th></tr>
|
|
"""
|
|
for title, artist, play_count, last_played in rows:
|
|
try:
|
|
dt = datetime.fromtimestamp(int(last_played)).strftime('%Y-%m-%d %H:%M')
|
|
except:
|
|
dt = str(last_played)
|
|
html_content += f"<tr><td>{title}</td><td>{artist}</td><td class=\"plays\">{play_count}</td><td class=\"time\">{dt}</td></tr>\n"
|
|
|
|
html_content += """
|
|
</table>
|
|
</div>
|
|
"""
|
|
|
|
html_content += """
|
|
</div>
|
|
|
|
<script>
|
|
function switchUser() {
|
|
const selectedUser = document.getElementById('userSelect').value;
|
|
const cards = document.querySelectorAll('.card');
|
|
cards.forEach(card => {
|
|
card.classList.remove('active');
|
|
});
|
|
const targetCard = document.getElementById('user-card-' + selectedUser);
|
|
if (targetCard) {
|
|
targetCard.classList.add('active');
|
|
}
|
|
}
|
|
|
|
async function triggerRefresh() {
|
|
const btn = document.getElementById('refreshBtn');
|
|
btn.disabled = true;
|
|
btn.textContent = 'Regenerating...';
|
|
|
|
try {
|
|
const response = await fetch('http://' + window.location.hostname + ':8083/', { method: 'POST' });
|
|
if (response.ok) {
|
|
alert('Dashboard updated successfully! Reloading page...');
|
|
location.reload();
|
|
} else {
|
|
alert('Failed to regenerate stats.');
|
|
btn.disabled = false;
|
|
btn.textContent = 'Regenerate Stats';
|
|
}
|
|
} catch (err) {
|
|
console.error(err);
|
|
alert('Error connecting to the update server.');
|
|
btn.disabled = false;
|
|
btn.textContent = 'Regenerate Stats';
|
|
}
|
|
}
|
|
</script>
|
|
</body>
|
|
</html>
|
|
"""
|
|
|
|
print(f"Writing HTML to {OUTPUT_HTML}...")
|
|
with open(OUTPUT_HTML, 'w') as f:
|
|
f.write(html_content)
|
|
print("Dashboard HTML generated successfully.")
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
print("Starting script execution...")
|
|
generate_html()
|
|
except Exception as e:
|
|
print("An error occurred during execution:")
|
|
traceback.print_exc() |