-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
337 lines (268 loc) · 10.9 KB
/
Copy pathapp.py
File metadata and controls
337 lines (268 loc) · 10.9 KB
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
from flask import Flask, render_template, session, redirect, url_for, request, jsonify
from functools import wraps
import os
from dotenv import load_dotenv
from werkzeug.utils import secure_filename
import uuid
from datetime import datetime
import traceback
import json
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
load_dotenv()
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', 'your-secret-key-here')
UPLOAD_FOLDER = os.path.join('static', 'uploads')
ALLOWED_EXTENSIONS = {'webm', 'wav', 'mp3', 'ogg', 'm4a', 'aac', 'flac', 'opus'}
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024
# Helper Functions
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def get_metadata_path():
return os.path.join(app.config['UPLOAD_FOLDER'], 'metadata.json')
def load_metadata():
path = get_metadata_path()
if not os.path.exists(path):
return {}
try:
with open(path, 'r') as f:
return json.load(f)
except json.JSONDecodeError:
logger.error("Metadata file is corrupt. Returning empty dict.")
return {}
except Exception as e:
logger.error(f"Error loading metadata: {e}")
return {}
def save_metadata(metadata):
try:
with open(get_metadata_path(), 'w') as f:
json.dump(metadata, f, indent=2)
return True
except Exception as e:
logger.error(f"Error saving metadata: {e}")
return False
@app.context_processor
def inject_firebase_config():
return dict(
config={
'FIREBASE_API_KEY': os.getenv('FIREBASE_API_KEY', ''),
'FIREBASE_AUTH_DOMAIN': os.getenv('FIREBASE_AUTH_DOMAIN', ''),
'FIREBASE_PROJECT_ID': os.getenv('FIREBASE_PROJECT_ID', ''),
'FIREBASE_STORAGE_BUCKET': os.getenv('FIREBASE_STORAGE_BUCKET', ''),
'FIREBASE_MESSAGING_SENDER_ID': os.getenv('FIREBASE_MESSAGING_SENDER_ID', ''),
'FIREBASE_APP_ID': os.getenv('FIREBASE_APP_ID', '')
}
)
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user' not in session:
return redirect(url_for('auth'))
return f(*args, **kwargs)
return decorated_function
# Public Routes
@app.route('/')
def index():
return render_template('index.html')
@app.route('/auth')
def auth():
if 'user' in session:
return redirect(url_for('home'))
return render_template('auth.html')
@app.route('/home')
@login_required
def home():
return render_template('home.html')
@app.route('/pitch')
@login_required
def pitch():
return render_template('pitch.html')
@app.route('/tuner')
@login_required
def tuner():
return render_template('tuner.html')
@app.route('/chords')
@login_required
def chords():
return render_template('chords.html')
@app.route('/spectrum')
@login_required
def spectrum():
return render_template('spectrum.html')
@app.route('/metronome')
@login_required
def metronome():
return render_template('metronome.html')
@app.route('/profile')
@login_required
def profile():
return render_template('profile.html')
# APIs
@app.route('/api/login', methods=['POST'])
def login():
try:
data = request.get_json()
if not data:
return jsonify({'success': False, 'error': 'No data provided'}), 400
required_fields = ['email', 'uid']
for field in required_fields:
if not data.get(field):
return jsonify({'success': False, 'error': f'Missing required field: {field}'}), 400
session['user'] = {
'email': data.get('email'),
'name': data.get('name', ''),
'uid': data.get('uid')
}
return jsonify({'success': True})
except Exception as e:
logger.error(f"Login error: {str(e)}")
traceback.print_exc()
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/logout', methods=['POST'])
def logout():
try:
session.clear()
return jsonify({'success': True})
except Exception as e:
logger.error(f"Logout error: {str(e)}")
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/check-auth')
def check_auth():
try:
if 'user' in session:
return jsonify({'authenticated': True, 'user': session['user']})
return jsonify({'authenticated': False})
except Exception as e:
return jsonify({'authenticated': False, 'error': str(e)}), 500
@app.route('/api/upload-recording', methods=['POST'])
@login_required
def upload_recording():
try:
if 'audio' not in request.files:
return jsonify({'success': False, 'error': 'No audio file provided'}), 400
file = request.files['audio']
if file.filename == '':
return jsonify({'success': False, 'error': 'No file selected'}), 400
if not allowed_file(file.filename):
return jsonify({'success': False, 'error': 'File type not supported. Supported formats: ' + ', '.join(ALLOWED_EXTENSIONS)}), 400
original_extension = file.filename.rsplit('.', 1)[1].lower() if '.' in file.filename else 'webm'
user_id = session['user']['uid']
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
unique_id = str(uuid.uuid4())[:8]
filename = f"{user_id}_{timestamp}_{unique_id}.{original_extension}"
filename = secure_filename(filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
return jsonify({
'success': True,
'filename': filename,
'url': url_for('static', filename=f'uploads/{filename}')
})
except Exception as e:
logger.error(f"Upload error: {str(e)}")
traceback.print_exc()
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/rename-recording', methods=['POST'])
@login_required
def rename_recording():
try:
data = request.get_json()
filename = data.get('filename')
new_name = data.get('newName', '').strip()
logger.info(f"Rename request - filename: {filename}, new_name: {new_name}")
if not filename or not new_name:
return jsonify({'success': False, 'error': 'Filename and new name are required'}), 400
user_id = session['user']['uid']
if not filename.startswith(user_id):
return jsonify({'success': False, 'error': 'Unauthorized'}), 403
if len(new_name) > 100:
return jsonify({'success': False, 'error': 'Name too long (max 100 characters)'}), 400
metadata = load_metadata()
metadata[filename] = {
'customName': new_name,
'updatedAt': datetime.now().isoformat()
}
if save_metadata(metadata):
logger.info(f"Successfully renamed {filename} to {new_name}")
return jsonify({'success': True, 'newName': new_name})
else:
return jsonify({'success': False, 'error': 'Failed to save metadata'}), 500
except Exception as e:
logger.error(f"Rename error: {str(e)}")
traceback.print_exc()
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/delete-recording', methods=['POST'])
@login_required
def delete_recording():
try:
data = request.get_json()
filename = data.get('filename')
logger.info(f"Delete request for filename: {filename}")
if not filename:
return jsonify({'success': False, 'error': 'No filename provided'}), 400
user_id = session['user']['uid']
if not filename.startswith(user_id):
logger.warning(f"Unauthorized delete attempt: filename doesn't start with user_id")
return jsonify({'success': False, 'error': 'Unauthorized'}), 403
if '..' in filename or '/' in filename or '\\' in filename:
return jsonify({'success': False, 'error': 'Invalid filename'}), 400
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
if os.path.exists(filepath):
try:
os.remove(filepath)
logger.info(f"Successfully deleted file: {filepath}")
metadata = load_metadata()
if filename in metadata:
del metadata[filename]
save_metadata(metadata)
return jsonify({'success': True})
except PermissionError as e:
logger.error(f"Permission error: {str(e)}")
return jsonify({'success': False, 'error': 'Permission denied'}), 403
except Exception as e:
logger.error(f"Error deleting file: {str(e)}")
traceback.print_exc()
return jsonify({'success': False, 'error': f'Error deleting file: {str(e)}'}), 500
else:
logger.warning(f"File not found: {filepath}")
return jsonify({'success': False, 'error': 'File not found'}), 404
except Exception as e:
logger.error(f"Delete recording error: {str(e)}")
traceback.print_exc()
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/get-recordings')
@login_required
def get_recordings():
try:
user_id = session['user']['uid']
recordings = []
metadata = load_metadata()
for filename in os.listdir(app.config['UPLOAD_FOLDER']):
if filename.startswith(user_id) and any(filename.endswith(f'.{ext}') for ext in ALLOWED_EXTENSIONS):
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
custom_name = metadata.get(filename, {}).get('customName')
recordings.append({
'filename': filename,
'customName': custom_name,
'url': url_for('static', filename=f'uploads/{filename}'),
'timestamp': os.path.getctime(filepath)
})
recordings.sort(key=lambda x: x['timestamp'], reverse=True)
return jsonify({'success': True, 'recordings': recordings})
except Exception as e:
logger.error(f"Get recordings error: {str(e)}")
traceback.print_exc()
return jsonify({'success': False, 'error': str(e)}), 500
#Error Handlers
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
if __name__ == '__main__':
app.run(host='localhost', port=5000, debug=True)