-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfloppymusic-web.py
144 lines (114 loc) · 4.91 KB
/
floppymusic-web.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
from flask import Flask, render_template, request, redirect, url_for, flash, g
from flask_uploads import UploadSet, configure_uploads, UploadNotAllowed
import argparse
import subprocess
import sqlite3
import os
parser = argparse.ArgumentParser(description="IMPORTANT! To ensure floppymusics functionality this script must be run as root.")
parser.add_argument("--port", help="set Flask web port", default=5000, type=int)
parser.add_argument("--host", help="set Flask ip binding (host)", default="0.0.0.0")
parser.add_argument("-debug", help="enable Flask debug option", action='store_true', default=False)
args = parser.parse_args()
app = Flask(__name__)
app.secret_key = "super secret key"
DATABASE = "database.sqlite"
db = sqlite3.connect(DATABASE)
c = db.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS songs(id INTEGER PRIMARY KEY, name TEXT, dropfac REAL)""")
db.commit()
db.close()
midis = UploadSet("MIDIS", "mid")
app.config["UPLOADED_MIDIS_DEST"] = "uploads/"
configure_uploads(app, midis)
playing = None
proc = None
def get_db():
# Opens a new database connection if there is none yet for the current application context.
if not hasattr(g, "sqlite_db"):
g.sqlite_db = sqlite3.connect(DATABASE)
return g.sqlite_db
def query_db(query, args=(), one=False):
cur = get_db().execute(query, args)
rv = cur.fetchall()
cur.close()
return (rv[0] if rv else None) if one else rv
@app.teardown_appcontext
def close_db(error):
# Closes the database again at the end of the request."""
if hasattr(g, "sqlite_db"):
g.sqlite_db.close()
@app.route("/")
def index():
return render_template("index.html", playing=playing, songs=query_db("""SELECT * FROM songs"""))
@app.route("/add", methods=["GET", "POST"])
def add():
if request.method == "POST" and "midi" in request.files:
try:
if request.files['midi'].filename == '':
flash("No file selected", "alert-warning")
return render_template("add.html")
filename = midis.save(request.files["midi"])
except UploadNotAllowed:
flash("Upload not allowed (MIDI Files only)", "alert-danger")
return render_template("add.html")
dropfactor = request.form["drop-factor"]
get_db().execute("""INSERT INTO songs (name, dropfac) VALUES(?, ?)""", [str(filename), float(dropfactor)])
get_db().commit()
flash(str(filename) + " uploaded", "alert-success")
return render_template("add.html")
@app.route("/stop")
def stop():
global playing
global proc
playing = None
if proc is None:
flash("Process not started", "alert-danger")
else:
if proc.poll() is None:
proc.terminate()
flash("Process stopped", "alert-success")
else:
flash("Process already stopped", "alert-success")
return redirect(url_for("index"))
@app.route("/play/<song_id>")
def play(song_id):
global playing
global proc
if os.path.isfile(app.config["UPLOADED_MIDIS_DEST"] + query_db("""SELECT name FROM songs WHERE id=?""", (song_id,))[0][0]):
playing = query_db("""SELECT * FROM songs WHERE id=?""", (song_id,))[0]
else:
flash("File not found", "alert-danger")
return redirect(url_for("index"))
try:
proc = subprocess.Popen(["./floppymusic", "-d " + str(playing[2]), app.config["UPLOADED_MIDIS_DEST"] + str(playing[1])])
except FileNotFoundError:
flash(flash("Floppymusic file not found", "alert-danger"))
return redirect(url_for("index"))
return redirect(url_for("index"))
@app.route("/edit/<song_id>", methods=["GET", "POST"])
def edit(song_id):
if request.method == "POST":
name = request.form["file-name"]
dropfac = request.form["drop-factor"]
try:
os.rename(app.config["UPLOADED_MIDIS_DEST"] + query_db("""SELECT name FROM songs WHERE id=?""", (song_id,))[0][0],
app.config["UPLOADED_MIDIS_DEST"] + name + ".mid")
except FileNotFoundError:
flash("File not found", "alert-danger")
return redirect(url_for('index'))
get_db().execute("""UPDATE songs SET name=?,dropfac=? WHERE id=?""", [str(name) + ".mid", float(dropfac), int(song_id)])
get_db().commit()
flash("Edited {}. {}.mid ({})".format(song_id, name, dropfac), "alert-success")
return redirect(url_for('index'))
return render_template('edit.html', song=query_db("""SELECT * FROM songs WHERE id=?""", (song_id,)))
@app.route("/delete/<song_id>")
def delete(song_id):
try:
os.remove("uploads/" + query_db("""SELECT name FROM songs WHERE id=?""", (song_id,))[0][0])
except FileNotFoundError:
flash("File not found", "alert-danger")
get_db().execute("""DELETE FROM songs WHERE id=? """, (song_id,))
get_db().commit()
return redirect(url_for("index"))
if __name__ == "__main__":
app.run(host=args.host, port=args.port, debug=args.debug)