Add Docker, remove test data

This commit is contained in:
2019-05-26 03:13:18 +02:00
parent c62314d9eb
commit 83a7b195f2
11 changed files with 14 additions and 6 deletions

104
app/database.py Normal file
View File

@ -0,0 +1,104 @@
# -*- coding: utf_8 -*-
import sqlite3
import pandas
from io import StringIO
song_table = "songs"
entry_table = "entries"
index_label = "Id"
def open_db():
conn = sqlite3.connect("test.db")
conn.execute('PRAGMA encoding = "UTF-8";')
return conn
def import_songs(song_csv):
print("Start importing Songs...")
df = pandas.read_csv(StringIO(song_csv), sep=';')
conn = open_db()
cur = conn.cursor()
df.to_sql(song_table, conn, if_exists='replace',
index=False)
cur.execute("SELECT Count(Id) FROM songs")
num_songs = cur.fetchone()[0]
conn.close()
print("Imported songs ({} in Database)".format(num_songs))
return("Imported songs ({} in Database)".format(num_songs))
def create_entry_table():
conn = open_db()
t = (entry_table,)
conn.execute('CREATE TABLE IF NOT EXISTS '+entry_table +
' (ID INTEGER PRIMARY KEY NOT NULL, Song_Id INTEGER NOT NULL, Name VARCHAR(255))')
conn.close()
def create_song_table():
conn = open_db()
t = (entry_table,)
conn.execute("CREATE TABLE IF NOT EXISTS \""+song_table+"""\" (
"Id" INTEGER,
"Title" TEXT,
"Artist" TEXT,
"Year" INTEGER,
"Duo" INTEGER,
"Explicit" INTEGER,
"Date Added" TEXT,
"Styles" TEXT,
"Languages" TEXT
)""")
conn.close()
def create_list_view():
conn = open_db()
conn.execute("""CREATE VIEW IF NOT EXISTS [Liste] AS
SELECT Name, Title, Artist, entries.Id
FROM entries, songs
WHERE entries.Song_Id=songs.Id""")
conn.close()
def get_list():
conn = open_db()
cur = conn.cursor()
cur.execute("SELECT * FROM Liste")
return cur.fetchall()
def get_song_list():
conn =open_db()
cur = conn.cursor()
cur.execute("SELECT Title || \" - \" || Artist AS Song, Id FROM songs")
return cur.fetchall()
def get_song_completions(input_string):
conn = open_db()
cur = conn.cursor()
# Don't look, it burns...
cur.execute(
"SELECT Title || \" - \" || Artist AS Song, Id FROM songs WHERE Song LIKE REPLACE(REPLACE(REPLACE(REPLACE(UPPER('%"+input_string+"%'),'ö','Ö'),'ü','Ü'),'ä','Ä'),'ß','')")
return cur.fetchall()
def add_entry(name,song_id):
conn = open_db()
cur = conn.cursor()
cur.execute(
"INSERT INTO entries (Song_Id,Name) VALUES(?,?);", (song_id,name))
conn.commit()
conn.close()
return
def delete_entry(id):
conn = open_db()
cur = conn.cursor()
cur.execute("DELETE FROM entries WHERE id=?",(id,))
conn.commit()
conn.close()
return True
def delete_all_entries():
conn = open_db()
cur = conn.cursor()
cur.execute("DELETE FROM entries")
conn.commit()
conn.close()
return True

33
app/helpers.py Normal file
View File

@ -0,0 +1,33 @@
import requests
from bs4 import BeautifulSoup
import json
import os
config_file = "config.json"
def get_catalog_url():
r = requests.get('https://www.karafun.de/karaoke-song-list.html')
soup = BeautifulSoup(r.content, 'html.parser')
url = soup.findAll('a', href=True, text='CSV')[0]['href']
return url
def get_songs(url):
r = requests.get(url)
return r.text
def check_config_exists():
return os.path.isfile(config_file)
def setup_config(app):
if check_config_exists():
config = json.load(open(config_file))
with open(config_file, 'r') as handle:
config = json.load(handle)
print("Loaded existing config")
else:
config = {'username': 'admin', 'password': 'changeme'}
with open(config_file, 'w') as handle:
json.dump(config, handle, indent=4, sort_keys=True)
print("Wrote new config")
app.config['BASIC_AUTH_USERNAME'] = config['username']
app.config['BASIC_AUTH_PASSWORD'] = config['password']

88
app/main.py Normal file
View File

@ -0,0 +1,88 @@
from flask import Flask, render_template, Response, abort, request, redirect
import helpers
import database
import os, errno
import json
from flask_basicauth import BasicAuth
app = Flask(__name__, static_url_path='/static')
basic_auth = BasicAuth(app)
@app.route("/")
def home():
if basic_auth.authenticate():
return render_template('main_admin.html', list=database.get_list(), auth=basic_auth.authenticate())
else:
return render_template('main.html', list=database.get_list(), auth=basic_auth.authenticate())
@app.route('/api/enqueue', methods=['POST'])
def enqueue():
if not request.json:
print(request.data)
abort(400)
name = request.json['name']
song_id = request.json['id']
database.add_entry(name,song_id)
return Response('{"status":"OK"}', mimetype='text/json')
@app.route("/list")
def songlist():
return render_template('songlist.html', list=database.get_song_list(), auth=basic_auth.authenticate())
@app.route("/api/songs")
def songs():
list = database.get_song_list()
return Response(json.dumps(list, ensure_ascii=False).encode('utf-8'), mimetype='text/json')
@app.route("/api/songs/update")
@basic_auth.required
def update_songs():
database.delete_all_entries()
status = database.import_songs(helpers.get_songs(helpers.get_catalog_url()))
print(status)
return Response('{"status": "%s" }' % status, mimetype='text/json')
@app.route("/api/songs/compl")
def get_song_completions(input_string=""):
input_string = request.args.get('search',input_string)
if input_string!="":
print(input_string)
list = database.get_song_completions(input_string=input_string)
return Response(json.dumps(list, ensure_ascii=False).encode('utf-8'), mimetype='text/json')
else:
return 400
@app.route("/api/entries/delete/<entry_id>")
@basic_auth.required
def delete_entry(entry_id):
if database.delete_entry(entry_id):
return Response('{"status": "OK"}', mimetype='text/json')
else:
return Response('{"status": "FAIL"}', mimetype='text/json')
@app.route("/api/entries/delete_all")
@basic_auth.required
def delete_all_entries():
if database.delete_all_entries():
return Response('{"status": "OK"}', mimetype='text/json')
else:
return Response('{"status": "FAIL"}', mimetype='text/json')
@app.route("/login")
@basic_auth.required
def admin():
return redirect("/", code=303)
@app.before_first_request
def activate_job():
database.create_entry_table()
database.create_song_table()
database.create_list_view()
helpers.setup_config(app)
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0')

25
app/static/css/style.css Normal file
View File

@ -0,0 +1,25 @@
body {
padding-top: 5rem;
}
html, body {
height: 100%;
}
.site {
height: auto;
min-height: 100%;
}
main {
padding-bottom: 60px; /* Höhe des Footers */
}
.footer {
margin-top: -60px;
width: 100%;
height: 60px;
/* Set the fixed height of the footer here */
/*line-height: 60px; /* Vertically center the text there */
background-color: #f5f5f5;
}

92
app/templates/base.html Normal file
View File

@ -0,0 +1,92 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>{% block title %}{% endblock %} - KaraoQueue</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="static/css/style.css" rel="stylesheet">
<!-- Fontawesome Icons-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css"
integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
<a class="navbar-brand" href="/">KaraoQueue</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault"
aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/list">Songsuche</a>
</li>
</ul>
<!--<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>-->
</div>
</nav>
<div class="site">
<main role="main" class="container">
{% block content %}{% endblock %}
</main><!-- /.container -->
</div>
<!-- Footer -->
<footer class="footer">
<div class="container text-center py-3">
{% if not auth %}
<a href="/login" class="ml-1 mr-1"><i
class="fas fa-sign-in-alt mr-1"></i><span>Login</span></a>
{% endif %}
<a href="https://github.com/PhoenixTwoFive/karaoqueue"
class="ml-1 mr-1"><i class="fab fa-github mr-1"></i><span>Github</span></a>
<span class="text-muted">KaraoQueue -&nbsp;<span
style="display:inline-block;transform: rotate(180deg) translateY(-0.2rem)">&copy</span>&nbsp;2019 - Phillip
Kühne</span>
</div>
</footer>
<!-- Footer -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha384-xBuQ/xzmlsLoJpyjoggmTEz8OWUFM0/RC5BsqQBDX2v5cMvDHcMakNTNrHIW2I5f" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous">
</script>
{% block extrajs %}{% endblock %}
<script>
$(document).ready(function () {
// get current URL path and assign 'active' class
var pathname = window.location.pathname;
$('.navbar-nav > li > a[href="' + pathname + '"]').parent().addClass('active');
})
</script>
</body>
</html>

27
app/templates/main.html Normal file
View File

@ -0,0 +1,27 @@
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
<table class="table">
<tr>
<th scope="col">Name</th>
<th scope="col">Song</th>
<th scope="col">Künstler</th>
</tr>
{% for entry in list: %}
<tr>
<td>
{{ entry[0] }}
</td>
<td>
{{ entry[1] }}
</td>
<td>
{{ entry[2] }}
</td>
</tr>
{% endfor %}
</table>
<a name="end"></a>
{% endblock %}

View File

@ -0,0 +1,139 @@
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
<div class="container">
<div class="row">
<div class="card" style="width: 100%">
<div class="card-body d-flex flex-row">
<button type="button" class="btn btn-danger m-2"
onclick="confirmDeleteAllEntries()"><i class="fas fa-trash mr-2"></i>Alle Einträge löschen</button>
<button type="button" class="btn btn-danger m-2"
onclick="confirmUpdateSongDatabase()"><i class="fas fa-file-import mr-2"></i>Song-Datenbank
aktualisieren</button>
</div>
</div>
</div>
<div class="row">
<table class="table">
<tr>
<th scope="col">Name</th>
<th scope="col">Song</th>
<th scope="col">Künstler</th>
<th scope="col">Löschen</th>
</tr>
{% for entry in list: %}
<tr>
<td>
{{ entry[0] }}
</td>
<td>
{{ entry[1] }}
</td>
<td>
{{ entry[2] }}
</td>
<td>
<button type='button' class='btn btn-danger justify-content-center align-content-between'
onclick='confirmDeleteEntry("{{ entry[0] }}",{{ entry[3] }})'><i
class="fas fa-trash"></i></button>
</td>
</tr>
{% endfor %}
</table>
<a name="end"></a>
</div>
</div>
{% endblock %}
{% block extrajs %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"
integrity="sha256-4F7e4JsAJyLUdpP7Q8Sah866jCOhv72zU5E8lIRER4w=" crossorigin="anonymous"></script>
<script>
function confirmDeleteEntry(name, entry_id) {
bootbox.confirm("Wirklich den Eintrag von "+name+" löschen?", function(result){
if (result) {
deleteEntry(entry_id)
}
})
}
function confirmDeleteAllEntries() {
bootbox.confirm({
message: "Wirklich alle Eintragungen löschen?",
buttons: {
confirm: {
label: 'Ja',
className: 'btn btn-danger'
},
cancel: {
label: 'Nein',
className: 'btn btn-secondary'
}
},
callback: function(result){
if (result) {
deleteAllEntries()
}
}
})
}
function confirmUpdateSongDatabase() {
bootbox.confirm({
message: "Wirklich die Song-Datenbank aktualisieren?<br>Dies lädt die Aktuelle Song-Liste von <a href='https://www.karafun.de/karaoke-song-list.html'>KaraFun</a> herunter, <b>und wird alle Eintragungen löschen!</b>",
buttons: {
confirm: {
label: 'Ja',
className: 'btn-primary'
},
cancel: {
label: 'Nein',
className: 'btn btn-secondary'
}
},
callback: function(result){
if (result) {
var dialog = bootbox.dialog({
message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i> Aktualisiere Song-Datenbank...</p>',
closeButton: false
});
updateSongDatabase(dialog)
}
}
})
}
function deleteEntry(entry_id) {
$.ajax({
type: 'GET',
url: '/api/entries/delete/'+entry_id,
contentType: "application/json",
dataType: 'json'
});
location.reload();
}
function deleteAllEntries() {
$.ajax({
type: 'GET',
url: '/api/entries/delete_all',
contentType: "application/json",
dataType: 'json'
});
location.reload();
}
function updateSongDatabase(wait_dialog) {
$.ajax({
type: 'GET',
url: '/api/songs/update',
contentType: "application/json",
dataType: 'json',
success: function(data) {
wait_dialog.modal('hide')
bootbox.alert({
message: data["status"],
callback: function() {location.reload()}
})
}
});
}
</script>
{% endblock %}

111
app/templates/songlist.html Normal file
View File

@ -0,0 +1,111 @@
{% extends 'base.html' %}
{% block title %}Songsuche{% endblock %}
{% block content %}
<input class="form-control" id="filter" type="text" placeholder="Suchen...">
<table class="table">
<tbody id="songtable">
<!--{% for entry in (): %}
<tr>
<td>
{{ entry[0] }}
</td>
<td>
<button type="button" class="btn btn-primary"><i class="material-icons">queue_music</i></button>
</td>
</tr>
{% endfor %}-->
</tbody>
</table>
<div class="modal fade" id="enqueueModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Auf Liste setzen</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="form-group">
<form id="nameForm">
<div class="modal-body">
<label for="singerNameInput">Sängername</label>
<input type="text" class="form-control" id="singerNameInput" placeholder="Max Mustermann"
required>
<input id="selectedId" name="selectedId" type="hidden" value="">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" id="submitSongButton">Anmelden</button>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
{% block extrajs %}
<script>
$(document).ready(function () {
$("#filter").keyup( function () {
var value = $(this).val().toLowerCase();
//alert(value);
if(value.length >= 3) {
$.getJSON("/api/songs/compl", { search: value }, function (data) {
var items = [];
$.each(data, function (key, val) {
items.push("<tr><td>"+val[0]+`</td>
<td><button type='button'
class='btn btn-primary justify-content-center align-content-between'
data-toggle='modal'
data-target='#enqueueModal' onclick='setSelectedId(`+val[1]+`)'><i
class="fas fa-plus"></i></button></td>
</tr>`)
});
$("#songtable").html("")
$(items.join("")).appendTo("#songtable");
});
} else {
$("#songtable").html("")
}
});
$("#nameForm").submit( function (e) {
e.preventDefault();
submitModal();
});
});
function enqueue(id,name,success_callback) {
var data = {
"name": name,
"id": id
}
$.ajax({
type: 'POST',
url: '/api/enqueue',
data: JSON.stringify(data), // or JSON.stringify ({name: 'jonas'}),
success: success_callback,
contentType: "application/json",
dataType: 'json'
});
}
function setSelectedId(id) {
$("#selectedId").attr("value",id);
}
function submitModal() {
var name = $("#singerNameInput").val();
var id = $("#selectedId").attr("value");
enqueue(id,name,function(){
$("#enqueueModal").modal('hide');
window.location.href = '/#end';
});
}
</script>
{% endblock %}