Skip to content

Commit

Permalink
feat: bckground music, score and song limit
Browse files Browse the repository at this point in the history
  • Loading branch information
lvmasterrj committed Jan 1, 2025
1 parent 1f4b9f2 commit 24725ef
Show file tree
Hide file tree
Showing 6 changed files with 72 additions and 58 deletions.
56 changes: 32 additions & 24 deletions pikaraoke/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,27 @@
import hashlib
import json
import logging
import mimetypes
import os
import signal
import subprocess
import sys
import threading
import time
import mimetypes

import cherrypy
import flask_babel
import psutil
from flask import (
Flask,
flash,
jsonify,
make_response,
redirect,
render_template,
request,
send_file,
url_for,
jsonify,
)
from flask_babel import Babel
from flask_paginate import Pagination, get_page_parameter
Expand Down Expand Up @@ -419,21 +419,25 @@ def download():
def qrcode():
return send_file(k.qr_code_path, mimetype="image/png")


@app.route("/logo")
def logo():
return send_file(k.logo_path, mimetype="image/png")



@app.route("/background_music")
def background_music():
music_path = k.bg_music_path
mime_type, _ = mimetypes.guess_type(music_path)
return send_file(k.bg_music_path, mimetype=mime_type)


@app.route("/end_song", methods=["GET"])
def end_song():
k.end_song()
return "ok"


@app.route("/start_song", methods=["GET"])
def start_song():
k.start_song()
Expand Down Expand Up @@ -696,31 +700,34 @@ def expand_fs():
else:
flash("You don't have permission to resize the filesystem", "is-danger")
return redirect(url_for("home"))



@app.route("/change_preferences", methods=["GET"])
def change_preferences():
if is_admin():
preference = request.args["pref"]
val = request.args["val"]

rc = k.change_preferences(preference, val)
if is_admin():
preference = request.args["pref"]
val = request.args["val"]

rc = k.change_preferences(preference, val)

return jsonify(rc)
else:
flash(_("You don't have permission to define audio output"), "is-danger")
return redirect(url_for("info"))

return jsonify(rc)
else:
flash(_("You don't have permission to define audio output"), "is-danger")
return redirect(url_for("info"))

@app.route("/clear_preferences", methods=["GET"])
def clear_preferences():
if is_admin():
rc = k.clear_preferences()
if rc[0]:
flash(rc[1], "is-success")
else:
flash(rc[1], "is-danger")
else:
flash(_("You don't have permission to define audio output"), "is-danger")
return redirect(url_for("home"))
if is_admin():
rc = k.clear_preferences()
if rc[0]:
flash(rc[1], "is-success")
else:
flash(rc[1], "is-danger")
else:
flash(_("You don't have permission to define audio output"), "is-danger")
return redirect(url_for("home"))


# Handle sigterm, apparently cherrypy won't shut down without explicit handling
signal.signal(signal.SIGTERM, lambda signum, stack_frame: k.stop())
Expand Down Expand Up @@ -910,7 +917,8 @@ def main():
parser.add_argument(
"--bg-music-volume",
default=default_bg_music_volume,
help="Set the volume of background music on splash screen. A value between 0 and 1. (default: %s)" % default_bg_music_volume,
help="Set the volume of background music on splash screen. A value between 0 and 1. (default: %s)"
% default_bg_music_volume,
required=False,
),
parser.add_argument(
Expand Down Expand Up @@ -991,7 +999,7 @@ def main():
bg_music_volume=parsed_bg_volume,
bg_music_path=arg_path_parse(args.bg_music_path),
disable_score=args.disable_score,
limit_user_songs_by=args.limit_user_songs_by
limit_user_songs_by=args.limit_user_songs_by,
)
k.upgrade_youtubedl()

Expand Down
50 changes: 28 additions & 22 deletions pikaraoke/karaoke.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import configparser
import contextlib
import json
import logging
import os
import math
import random
import socket
import subprocess
Expand All @@ -12,11 +12,10 @@
from subprocess import CalledProcessError, check_output
from threading import Thread
from urllib.parse import urlparse
import configparser
from flask_babel import _

import ffmpeg
import qrcode
from flask_babel import _
from unidecode import unidecode

from pikaraoke.lib.file_resolver import FileResolver
Expand Down Expand Up @@ -104,7 +103,6 @@ def __init__(
disable_score=False,
limit_user_songs_by=0,
):

logging.basicConfig(
format="[%(asctime)s] %(levelname)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
Expand All @@ -128,11 +126,13 @@ def __init__(
self.screensaver_timeout = screensaver_timeout
self.url_override = url
self.prefer_hostname = prefer_hostname
self.disable_bg_music = self.get_user_preference("disable_bg_music") or disable_bg_music
self.disable_bg_music = self.get_user_preference("disable_bg_music") or disable_bg_music
self.bg_music_volume = self.get_user_preference("bg_music_volume") or bg_music_volume
self.bg_music_path = self.default_bg_music_path if bg_music_path == None else bg_music_path
self.disable_score = self.get_user_preference("disable_score") or disable_score
self.limit_user_songs_by = self.get_user_preference("limit_user_songs_by") or limit_user_songs_by
self.limit_user_songs_by = (
self.get_user_preference("limit_user_songs_by") or limit_user_songs_by
)

# other initializations
self.platform = get_platform()
Expand Down Expand Up @@ -170,7 +170,7 @@ def __init__(
youtubedl-version: {self.get_youtubedl_version()}
"""
)

# Generate connection URL and QR code,
if self.raspberry_pi:
# retry in case pi is still starting up
Expand Down Expand Up @@ -229,7 +229,7 @@ def get_user_preference(self, preference, default_value=False):
return self.config_obj.get("USERPREFERENCES", preference)
except (configparser.NoOptionError, ValueError):
return default_value

def change_preferences(self, preference, val):
"""Makes changes in the config.ini file that stores the user preferences.
Receives the preference and it's new value"""
Expand All @@ -241,21 +241,21 @@ def change_preferences(self, preference, val):

userprefs = self.config_obj["USERPREFERENCES"]
userprefs[preference] = str(val)
setattr(self,preference,eval(str(val)))
setattr(self, preference, eval(str(val)))
with open("config.ini", "w") as conf:
self.config_obj.write(conf)
self.changed_preferences = True
return [True, _("Your preferences were changed successfully")]
return [True, _("Your preferences were changed successfully")]
except Exception as e:
logging.debug("Failed to change user preference << %s >>: %s", preference, e)
return [False, _("Something went wrong! Your preferences were not changed")]

def clear_preferences(self):
try:
os.remove("config.ini")
return [True, _("Your preferences were cleared successfully")]
except OSError:
return [False, _("Something went wrong! Your preferences were not cleared")]
try:
os.remove("config.ini")
return [True, _("Your preferences were cleared successfully")]
except OSError:
return [False, _("Something went wrong! Your preferences were not cleared")]

def get_ip(self):
# python socket.connect will not work on android, access denied. Workaround: use ifconfig which is installed to termux by default, iirc.
Expand Down Expand Up @@ -633,23 +633,29 @@ def is_song_in_queue(self, song_path):
if each["file"] == song_path:
return True
return False

def is_user_limited(self, user):
#Returns if a user needs to be limited or not if the limitation is on and if the user reached the limit of songs in queue
# Returns if a user needs to be limited or not if the limitation is on and if the user reached the limit of songs in queue
if self.limit_user_songs_by == "0" or user == "Pikaraoke":
return False
cont = len([i for i in self.queue if i['user'] == user]) + (1 if self.now_playing_user == user else 0)
cont = len([i for i in self.queue if i["user"] == user]) + (
1 if self.now_playing_user == user else 0
)
return True if cont >= int(self.limit_user_songs_by) else False

def enqueue(self, song_path, user="Pikaraoke", semitones=0, add_to_front=False):
#Check if the song is already in the queue, if not add it
# Check if the song is already in the queue, if not add it
if self.is_song_in_queue(song_path):
logging.warn("Song is already in queue, will not add: " + song_path)
return [False, _("Song is already in queue, will not add: ") + song_path]
#check if the user has reached the limit of songs in queue
# check if the user has reached the limit of songs in queue
elif self.is_user_limited(user):
logging.debug("User limitted by: " + str(self.limit_user_songs_by))
return [False, _("You reached the limit of %s song(s) from an user in queue!") % (str(self.limit_user_songs_by))]
return [
False,
_("You reached the limit of %s song(s) from an user in queue!")
% (str(self.limit_user_songs_by)),
]
else:
queue_item = {
"user": user,
Expand Down
10 changes: 5 additions & 5 deletions pikaraoke/static/fireworks.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,16 +86,16 @@ const launchMultipleFireworks = (count) => {
simultaneousFireworks = 3;
intensity = 500
}

const launchInterval = () => {
if (Date.now() - startTime > showDuration) return; // Para após o tempo definido

const fireworkCount = Math.floor(Math.random() * simultaneousFireworks) + simultaneousFireworks; // Entre 2 e 5 fogos simultâneos
launchMultipleFireworks(fireworkCount);

const nextInterval = Math.random() * intensity + 200; // Intervalo entre 200ms e 1s
setTimeout(launchInterval, nextInterval); // Agenda o próximo grupo
};

launchInterval(); // Inicia o ciclo
};
};
2 changes: 1 addition & 1 deletion pikaraoke/static/score.css
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,4 @@ canvas {
width: 100%;
height: 100%;
/* z-index: 1; */
}
}
10 changes: 5 additions & 5 deletions pikaraoke/static/score.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ function getScoreData(scoreValue){
} else {
return {applause: "applause-h.ogg", review: scoreReviews.high[Math.floor(Math.random() * scoreReviews.high.length)]}
}
}
}

// Function that creates a random score biased towards 99
function getScoreValue() {
Expand Down Expand Up @@ -50,21 +50,21 @@ async function rotateScore(scoreTextElement, duration) {

// Function that starts the score animation
async function startScore(staticPath) {

const scoreElement = $("#score");
const scoreTextElement = $("#score-number-text")
const scoreReviewElement = $("#score-review-text")

const scoreValue = getScoreValue();
const drums = new Audio(staticPath + "sounds/score-drums.ogg");

const scoreData = getScoreData(scoreValue);

scoreElement.show();
drums.volume = 0.3;
drums.play();
const drumDuration = 4100;

await rotateScore(scoreTextElement, drumDuration);
await showFinalScore(scoreTextElement, scoreValue, scoreReviewElement, scoreData);
scoreElement.hide();
Expand Down
2 changes: 1 addition & 1 deletion pikaraoke/templates/files.html
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
if (obj.success[0]) {
// {# MSG: Notification when a song gets added to the queue. The song name comes after this string. #}
showNotification(
obj.success[1],
obj.success[1],
'is-success'
);
} else {
Expand Down

0 comments on commit 24725ef

Please sign in to comment.