]> git.0d.be Git - botaradio.git/blob - interface.py
Improve Web interface
[botaradio.git] / interface.py
1 #!/usr/bin/python3
2
3 from flask import Flask, render_template, request, redirect, send_file
4 import variables as var
5 import util
6 from datetime import datetime
7 import os.path
8 import random
9 from werkzeug.utils import secure_filename
10 import errno
11 import media
12
13
14 class ReverseProxied(object):
15     '''Wrap the application in this middleware and configure the
16     front-end server to add these headers, to let you quietly bind
17     this to a URL other than / and to an HTTP scheme that is
18     different than what is used locally.
19
20     In nginx:
21     location /myprefix {
22         proxy_pass http://192.168.0.1:5001;
23         proxy_set_header Host $host;
24         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
25         proxy_set_header X-Scheme $scheme;
26         proxy_set_header X-Script-Name /myprefix;
27         }
28
29     :param app: the WSGI application
30     '''
31
32     def __init__(self, app):
33         self.app = app
34
35     def __call__(self, environ, start_response):
36         script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
37         if script_name:
38             environ['SCRIPT_NAME'] = script_name
39             path_info = environ['PATH_INFO']
40             if path_info.startswith(script_name):
41                 environ['PATH_INFO'] = path_info[len(script_name):]
42
43         scheme = environ.get('HTTP_X_SCHEME', '')
44         if scheme:
45             environ['wsgi.url_scheme'] = scheme
46         real_ip = environ.get('HTTP_X_REAL_IP', '')
47         if real_ip:
48             environ['REMOTE_ADDR'] = real_ip
49         return self.app(environ, start_response)
50
51
52 web = Flask(__name__)
53
54
55 def init_proxy():
56     global web
57     if var.is_proxified:
58         web.wsgi_app = ReverseProxied(web.wsgi_app)
59
60
61 @web.route("/", methods=['GET', 'POST'])
62 def index():
63     folder_path = var.music_folder
64     files = util.get_recursive_filelist_sorted(var.music_folder)
65     music_library = util.Dir(folder_path)
66     for file in files:
67         music_library.add_file(file)
68
69     if request.method == 'POST':
70         print(request.form)
71         if 'add_file' in request.form and ".." not in request.form['add_file']:
72             item = {'type': 'file',
73                     'path' : request.form['add_file'],
74                     'user' : 'Web'}
75             var.playlist.append(item)
76
77         elif ('add_folder' in request.form and ".." not in request.form['add_folder']) or ('add_folder_recursively' in request.form and ".." not in request.form['add_folder_recursively']):
78             try:
79                 folder = request.form['add_folder']
80             except:
81                 folder = request.form['add_folder_recursively']
82
83             if not folder.endswith('/'):
84                 folder += '/'
85
86             print('folder:', folder)
87             if 'add_folder_recursively' in request.form:
88                 files = music_library.get_files_recursively(folder)
89             else:
90                 files = music_library.get_files(folder)
91             files = list(map(lambda file: {'type':'file','path': os.path.join(folder, file), 'user':'Web'}, files))
92             print('Adding to playlist: ', files)
93             var.playlist.extend(files)
94
95         elif 'add_url' in request.form:
96             var.playlist.append({'type':'url',
97                                 'url': request.form['add_url'],
98                                 'user': 'Web',
99                                 'ready': 'validation'})
100             media.url.get_url_info()
101             var.playlist[-1]['ready'] = "no"
102
103         elif 'add_radio' in request.form:
104             var.playlist.append({'type': 'radio',
105                                 'path': request.form['add_radio'],
106                                 'user': "Web"})
107
108         elif 'delete_music' in request.form:
109             if len(var.playlist) >= request.form['delete_music']:
110                 var.playlist.pop(request.form['delete_music'])
111         
112         elif 'action' in request.form:
113             action = request.form['action']
114             if action == "randomize":
115                 random.shuffle(var.playlist)
116
117     return render_template('index.html',
118                            all_files=files,
119                            music_library=music_library,
120                            os=os,
121                            playlist=var.playlist,
122                            user=var.user)
123
124
125 @web.route('/upload', methods=["POST"])
126 def upload():
127     file = request.files['file']
128     if not file:
129         return redirect("./", code=406)
130
131     filename = secure_filename(file.filename).strip()
132     if filename == '':
133         return redirect("./", code=406)
134
135     targetdir = request.form['targetdir'].strip()
136     if targetdir == '':
137         targetdir = 'uploads/'
138     elif '../' in targetdir:
139         return redirect("./", code=406)
140
141     print('Uploading file:')
142     print('filename:', filename)
143     print('targetdir:', targetdir)
144     print('mimetype:', file.mimetype)
145
146     if "audio" in file.mimetype:
147         storagepath = os.path.abspath(os.path.join(var.music_folder, targetdir))
148         print('storagepath:',storagepath)
149         if not storagepath.startswith(os.path.abspath(var.music_folder)):
150             return redirect("./", code=406)
151
152         try:
153             os.makedirs(storagepath)
154         except OSError as ee:
155             if ee.errno != errno.EEXIST:
156                 return redirect("./", code=500)
157
158         filepath = os.path.join(storagepath, filename)
159         print('filepath:',filepath)
160         if os.path.exists(filepath):
161             return redirect("./", code=406)
162
163         file.save(filepath)
164         return redirect("./", code=302)
165     else:
166         return redirect("./", code=409)
167
168
169 @web.route('/download', methods=["GET"])
170 def download():
171     if 'file' in request.args:
172         requested_file = request.args['file']
173         if '../' not in requested_file:
174             folder_path = var.music_folder
175             files = util.get_recursive_filelist_sorted(var.music_folder)
176
177             if requested_file in files:
178                 filepath = os.path.join(folder_path, requested_file)
179                 try:
180                     return send_file(filepath, as_attachment=True)
181                 except Exception as e:
182                     self.log.exception(e)
183                     self.Error(400)
184     elif 'directory' in request.args:
185         requested_dir = request.args['directory']
186         folder_path = var.music_folder
187         requested_dir_fullpath = os.path.abspath(os.path.join(folder_path, requested_dir)) + '/'
188         if requested_dir_fullpath.startswith(folder_path):
189             if os.path.samefile(requested_dir_fullpath, folder_path):
190                 prefix = 'all'
191             else:
192                 prefix = secure_filename(os.path.relpath(requested_dir_fullpath, folder_path))
193             zipfile = util.zipdir(requested_dir_fullpath, prefix)
194             try:
195                 return send_file(zipfile, as_attachment=True)
196             except Exception as e:
197                 self.log.exception(e)
198                 self.Error(400)
199
200     return redirect("./", code=400)
201
202
203 if __name__ == '__main__':
204     web.run(port=8181, host="127.0.0.1")