Skip to content

Commit

Permalink
Holy shit mkII
Browse files Browse the repository at this point in the history
  • Loading branch information
Étienne ANDRÉ committed Mar 1, 2018
1 parent 2e53416 commit f7feed0
Show file tree
Hide file tree
Showing 13 changed files with 215 additions and 459 deletions.
14 changes: 14 additions & 0 deletions config.py.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
CONFIG = {
"secret_key": "",
"mpc_host": "localhost",
"mpc_port": "6600",
"youtube_key": "",
"spotify-clientid": "",
"spotify-secret": "",
"listen_addr": "0.0.0.0",
"listen_port": 8080,
"search_providers": [
# "spotify",
"youtube"
]
}
57 changes: 48 additions & 9 deletions jukebox.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
conn = sqlite3.connect("jukebox.sqlite3")
playlist_lock = threading.Lock()
playlist = []
player_skip = threading.Event()

@app.route("/")
def accueil():
Expand All @@ -43,8 +44,13 @@ def player_worker():
print("starting player")
while len(playlist) > 0:
print("playing {}".format(playlist[0]))
player = None
if playlist[0]["source"] == "youtube":
subprocess.run(["mpv", "--no-video", "--quiet", playlist[0]["url"]], stdin=subprocess.DEVNULL)
player = subprocess.Popen(["mpv", "--no-video", "--quiet", playlist[0]["url"]], stdin=subprocess.DEVNULL)
while player.poll() is None and not player_skip.is_set():
time.sleep(0.1)
player.kill()
player_skip.clear()
with playlist_lock:
del(playlist[0])
print("stopping player")
Expand Down Expand Up @@ -116,7 +122,16 @@ def search(query):
renvoie une liste de tracks correspondant à la requête depuis divers services
:return: un tableau contenant les infos que l'on a trouvé
"""

def parse_iso8601(x):
t = x[2:-1].split("M")
h=0
if "H" in t[0]:
h = int(t[0].split("H")[0])
t[0]=t[0].split("H")[1]
if len(t) == 2:
return int(t[0])*60 + int(t[1])
else:
return int(t[0])
results = []

# SPOTIFY
Expand Down Expand Up @@ -152,35 +167,59 @@ def search(query):
"type": "video"
})
if r.status_code != 200:
raise Exception(r.status, r.reason)
raise Exception(r.text, r.reason)
data = r.json()
print(",".join([i["id"]["videoId"] for i in data["items"]]))
if len(data["items"]) == 0: # Si le servuer n'a rien trouvé
raise Exception("nothing found on youtube")
raise Exception("nothing found on youtube")
r = requests.get("https://www.googleapis.com/youtube/v3/videos", params={
"part": "snippet,contentDetails",
"key": CONFIG["youtube_key"],
"id": ",".join([i["id"]["videoId"] for i in data["items"]])
})
data = r.json()
for i in data["items"]:
print(i)
results.append({
"source": "youtube",
"title": i["snippet"]["title"],
"artist": i["snippet"]["channelTitle"],
"url": "http://www.youtube.com/watch?v="+i["id"]["videoId"],
"albumart_url": i["snippet"]["thumbnails"]["default"]["url"]
"url": "http://www.youtube.com/watch?v="+i["id"] ,
"albumart_url": i["snippet"]["thumbnails"]["medium"]["url"],
"duration": parse_iso8601(i["contentDetails"]["duration"])
})
return jsonify(results)
@app.route("/logout")
def logout():
session['user'] = None
return redirect("/")
@app.route("/add", methods=['POST', 'GET'])
@app.route("/add", methods=['POST'])
def add():
"""
Ajoute l'url à la playlist
"""
track = request.form

print("adding", track)
with playlist_lock:
playlist.append(track)
if len(playlist) == 1:
threading.Thread(target=player_worker).start()
return "ok"

@app.route("/remove", methods=['POST'])
def remove():
"""supprime la track de la playlist"""
track = request.form
with playlist_lock:
print("removing", track)
for i in playlist:
if i["url"] == track["url"]:
if playlist.index(i) == 0:
player_skip.set()
else:
playlist.remove(i)
break
else:
print("not found !")
return "ok"
if __name__ == "__main__":
app.run(host=CONFIG["listen_addr"], port=CONFIG["listen_port"])
3 changes: 3 additions & 0 deletions static/images/icons/x.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions static/scripts/jquery.loadTemplate.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

90 changes: 90 additions & 0 deletions static/scripts/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
function template(html, d) {
var r = html;
for (i in d) {
r=r.replace("{"+i+"}", d[i]);
}
r=r.replace(/{\w+}/g, "")
return r;
}

function generate_track_html(t) {
track_html = document.createElement("div")
track_html.innerHTML = template(track_template, t)
$(track_html).children().data("track", t);
return track_html
}

track_template = `
<li class="list-group-item {active}">
<div class="row">
<div class="col-4 centered">
<img class="albumart" src="{albumart_url}">
</div>
<div class="col track-info centered">
<span class="track-title">{title}</span>
<span class="track-artist">{artist}</span>
<span class="track-duration">{duration} s.</span>
</div>
<div class="col-1 centered">
<img class="icon btn-remove" src="/static/images/icons/x.svg">
</div>
</div>
</li>
`
update_search = function() {
$.get("/sync", function (data) {
// console.log(data);
$('#playlist').html("");
for (i in data.playlist) {
var t = data.playlist[i];
if (i == 0) {
t.active = "active";
}
$('#playlist').append(generate_track_html(t))
$('#playlist li:last .btn-remove').click(function() {
$.post("/remove", $(this).parents("li").data("track"));
$(this).parents("li").hide();
});
}
});
window.setTimeout(arguments.callee, 5000);
}();

var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();

$('#query').keyup(function() {
if ($('#query').val() == "") {
$("#search_results").html("");
$("#search_results").hide();
return;
}
delay(function() {
console.log("searching "+$('#query').val());
$.get("/search/"+$('#query').val(), function(data) {
$("#search_results").html("")
console.log(data);
for (i in data) {
var t = data[i];
$('#search_results').append(generate_track_html(data[i]))
$('#search_results li:last').click(function() {
$.post("/add", $(this).data("track"));
$('#search_results').hide();
});
}
$("#search_results").show()
}, dataType="json");
},150);
});
$('#query').focus(function () {
if ($('#query').val() != "")
$('#search_results').show();
});

$('#search_results').hide();
33 changes: 33 additions & 0 deletions static/styles/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
.icon {
height: 20px;
display: block;
}

#search_results .btn-skip {
display: none;
}
#search_results li {
cursor: pointer;
}

.albumart {
width: 100%
}

.track-title {
display: block;
font-size: x-large;
}
.track-artist {
display: block;
}

.btn-remove {
cursor:pointer
}
.centered {
margin: auto
}
.track-duration {
color: #aaa;
}
Loading

0 comments on commit f7feed0

Please sign in to comment.