-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathneondisplay.py
More file actions
2800 lines (2674 loc) · 115 KB
/
neondisplay.py
File metadata and controls
2800 lines (2674 loc) · 115 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from flask import Flask, request, redirect, url_for, flash, Response, render_template, send_file, jsonify
from spotipy.oauth2 import SpotifyOAuth
from datetime import datetime, timezone
from collections import Counter
from functools import wraps
from logging.handlers import RotatingFileHandler
import os, toml, time, requests, subprocess, sys, signal, urllib.parse, socket, logging, threading, json, hashlib, spotipy, io, sqlite3, shutil, re, random
app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True
@app.after_request
def add_header(response):
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response
app.secret_key = 'hud-launcher-secret-key'
CONFIG_PATH = "config.toml"
DEFAULT_CONFIG = {
"display": {
"type": "framebuffer",
"framebuffer": "/dev/fb1",
"rotation": 0,
"st7789": {
"spi_port": 0,
"spi_cs": 1,
"dc_pin": 9,
"backlight_pin": 13,
"rotation": 0,
"spi_speed": 60000000
}
},
"api_keys": {
"openweather": "",
"google_geo": "",
"client_id": "",
"client_secret": "",
"lastfm": "",
"redirect_uri": "http://127.0.0.1:5000"
},
"settings": {
"framebuffer": "/dev/fb1",
"start_screen": "weather",
"fallback_city": "",
"use_gpsd": True,
"use_google_geo": True,
"time_display": True,
"progressbar_display": True,
"enable_current_track_display": True,
"sleep_timeout": 300
},
"wifi": {
"ap_ssid": "Neonwifi-Manager",
"ap_ip": "192.168.42.1",
"rescan_time": 600
},
"auto_start": {
"auto_start_hud": True,
"auto_start_neonwifi": True,
"check_internet": True
},
"clock": {
"type": "analog",
"background": "color",
"color": "black"
},
"buttons": {
"button_a": 5,
"button_b": 6,
"button_x": 16,
"button_y": 24,
"button_a_action": "clock",
"button_b_action": "weather",
"button_x_action": "spotify",
"button_y_action": "toggle_display",
"button_a_command": "",
"button_b_command": "",
"button_x_command": "",
"button_y_command": ""
},
"logging": {
"max_log_lines": 10000,
"max_backup_files": 5
},
"ui": {
"theme": "dark",
"css_file": "colors.css"
},
"api_status": {}
}
hud_process = None
neonwifi_process = None
last_logged_song = None
# ============== HELPER FUNCTIONS ==============
def delete_existing_playlist(playlist_name, sp):
user_id = sp.current_user()["id"]
logger = logging.getLogger('Launcher')
all_playlists = []
results = sp.current_user_playlists(limit=50)
all_playlists.extend(results['items'])
while results['next']:
results = sp.next(results)
all_playlists.extend(results['items'])
matching_playlists = []
for playlist in all_playlists:
if (playlist['name'].lower() == playlist_name.lower() and
playlist['owner']['id'] == user_id):
matching_playlists.append(playlist)
deleted_count = 0
for playlist in matching_playlists:
try:
sp.current_user_unfollow_playlist(playlist['id'])
deleted_count += 1
except Exception as e:
logger.warning(f"Failed to delete playlist via Spotipy: {e}")
try:
headers = {
'Authorization': f'Bearer {sp.auth_manager.get_access_token()["access_token"]}'
}
url = f"https://api.spotify.com/v1/playlists/{playlist['id']}/followers"
response = requests.delete(url, headers=headers)
if response.status_code == 200:
deleted_count += 1
else:
logger.error(f"Direct API deletion failed: {response.status_code}")
except Exception as e2:
logger.error(f"❌ All deletion methods failed: {e2}")
return deleted_count
def generate_chart_data(stats, label_type):
if not stats:
return {'labels': [], 'data': [], 'colors': []}
labels = list(stats.keys())
data = list(stats.values())
colors = []
for i in range(len(labels)):
hue = (i * 137.5) % 360
colors.append(f'hsl({hue}, 70%, 60%)')
return {
'labels': labels,
'data': data,
'colors': colors,
'label_type': label_type
}
def get_active_device(sp):
try:
devices = sp.devices()
if devices and 'devices' in devices:
for device in devices['devices']:
if device.get('is_active', False):
return device['id']
if devices['devices']:
return devices['devices'][0]['id']
except Exception as e:
logger = logging.getLogger('Launcher')
logger.error(f"Error getting active device: {e}")
return None
def get_lastfm_similar_tracks(artist_name, track_name, api_key, limit=50):
if not api_key:
return []
lastfm_url = "http://ws.audioscrobbler.com/2.0/"
params = {
"method": "track.getsimilar",
"artist": artist_name,
"track": track_name,
"api_key": api_key,
"format": "json",
"limit": limit
}
try:
response = requests.get(lastfm_url, params=params, timeout=10)
if response.status_code == 200:
data = response.json()
similar_tracks = data.get("similartracks", {}).get("track", [])
return similar_tracks
else:
logger = logging.getLogger('Launcher')
logger.error(f"Last.fm API error: {response.status_code}")
except Exception as e:
logger = logging.getLogger('Launcher')
logger.error(f"Last.fm request error: {e}")
return []
def parse_track_input(input_string):
separators = [' --- ']
for sep in separators:
if sep in input_string:
parts = input_string.split(sep, 1)
return parts[0].strip(), parts[1].strip()
for sep in [' - ', ' by ']:
if sep in input_string:
idx = input_string.rfind(sep)
if idx != -1:
track_name = input_string[:idx].strip()
artist_name = input_string[idx + len(sep):].strip()
return track_name, artist_name
return input_string.strip(), None
def play_playlist(playlist_uri, sp, device_id=None):
try:
if not device_id:
device_id = get_active_device(sp)
if not device_id:
logger = logging.getLogger('Launcher')
logger.warning("No active Spotify device found")
return False
sp.start_playback(device_id=device_id, context_uri=playlist_uri)
return True
except Exception as e:
logger = logging.getLogger('Launcher')
logger.error(f"Error playing playlist: {e}")
return False
def rate_limit(min_interval=1):
def decorator(f):
last_called = [0.0]
@wraps(f)
def wrapped(*args, **kwargs):
elapsed = time.time() - last_called[0]
left_to_wait = min_interval - elapsed
if left_to_wait > 0:
time.sleep(left_to_wait)
last_called[0] = time.time()
return f(*args, **kwargs)
return wrapped
return decorator
def search_lyrics_for_track(track_name, artist_name):
try:
api_url = "https://lrclib.net/api/search"
params = {
'track_name': track_name,
'artist_name': artist_name
}
logger = logging.getLogger('Launcher')
response = requests.get(api_url, params=params, timeout=10)
if response.status_code == 200:
results = response.json()
if results:
first_result = results[0]
lyrics_id = first_result.get('id')
if lyrics_id:
lyrics_response = requests.get(f"https://lrclib.net/api/get/{lyrics_id}", timeout=10)
if lyrics_response.status_code == 200:
lyrics_data = lyrics_response.json()
return {
'success': True,
'lyrics': lyrics_data.get('syncedLyrics', ''),
'plain_lyrics': lyrics_data.get('plainLyrics', ''),
'track_name': lyrics_data.get('trackName', track_name),
'artist_name': lyrics_data.get('artistName', artist_name),
'album_name': lyrics_data.get('albumName', ''),
'duration': lyrics_data.get('duration', 0)
}
return {'success': False, 'error': 'No lyrics found for this track'}
else:
logger.error(f"LRCLib API error: {response.status_code}")
return {'success': False, 'error': f'API returned status code {response.status_code}'}
except requests.RequestException as e:
logger = logging.getLogger('Launcher')
logger.error(f"Lyrics search network error: {e}")
return {'success': False, 'error': f'Network error: {str(e)}'}
except Exception as e:
logger = logging.getLogger('Launcher')
logger.error(f"Lyrics search unexpected error: {e}")
return {'success': False, 'error': f'Unexpected error: {str(e)}'}
def search_spotify_track(track_name, artist_name, sp):
try:
result = sp.search(q=f"track:{track_name} artist:{artist_name}", type='track', limit=1)
items = result['tracks']['items']
if items:
return items[0]['id']
except Exception as e:
logger = logging.getLogger('Launcher')
logger.error(f"Error searching Spotify track: {e}")
return None
def search_spotify_track_ids(track_list, sp):
spotify_track_ids = []
logger = logging.getLogger('Launcher')
for track in track_list:
name = track.get('name', '')
artist = track.get('artist', {}).get('name', '')
if not name or not artist:
continue
try:
result = sp.search(q=f"track:{name} artist:{artist}", type='track', limit=1)
items = result['tracks']['items']
if items:
track_id = items[0]['id']
spotify_track_ids.append(track_id)
else:
logger.info(f" Not found on Spotify: {name} by {artist}")
except Exception as e:
logger.error(f" Error searching for {name} by {artist}: {e}")
return spotify_track_ids
# ============== CONFIGURATION ROUTES ==============
@app.route('/')
def index():
config = load_config()
auto_config = config.get("auto_start", {})
ui_config = config.get("ui", {"theme": "dark"})
config_ready = is_config_ready()
spotify_configured = bool(config["api_keys"]["client_id"] and config["api_keys"]["client_secret"])
spotify_authenticated = False
if spotify_configured:
if os.path.exists('.spotify_cache'):
try:
with open('.spotify_cache', 'r') as f:
cache = json.load(f)
expires_at = cache.get('expires_at', 0)
spotify_authenticated = expires_at > (time.time() + 300)
except:
spotify_authenticated, _ = check_spotify_auth(timeout=2)
else:
spotify_authenticated = False
hud_running = is_hud_running()
neonwifi_running = is_neonwifi_running()
enable_current_track = config["settings"].get("enable_current_track_display", True)
return render_template(
'setup.html',
config=config,
config_ready=config_ready,
spotify_configured=spotify_configured,
spotify_authenticated=spotify_authenticated,
hud_running=hud_running,
neonwifi_running=neonwifi_running,
auto_config=auto_config,
enable_current_track_display=enable_current_track,
ui_config=ui_config
)
@app.route('/advanced_config')
def advanced_config():
config = load_config()
ui_config = config.get("ui", DEFAULT_CONFIG["ui"])
available_css = get_available_css_files()
spotify_configured = bool(config["api_keys"]["client_id"] and config["api_keys"]["client_secret"])
spotify_authenticated, _ = check_spotify_auth()
token_health = None
if spotify_authenticated:
try:
from spotify_auth_manager import SpotifyAuthManager
auth_manager = SpotifyAuthManager()
status, message = auth_manager.get_token_health()
token_health = {
'status': status,
'message': message,
'time_until_refresh': None
}
if os.path.exists('.spotify_cache'):
try:
with open('.spotify_cache', 'r') as f:
cache = json.load(f)
expires_at = cache.get('expires_at', 0)
if expires_at:
time_left = expires_at - time.time()
if time_left > 0:
if time_left < 60:
token_health['time_until_refresh'] = f"{int(time_left)} seconds"
elif time_left < 3600:
minutes = int(time_left / 60)
token_health['time_until_refresh'] = f"{minutes} minutes"
else:
hours = time_left / 3600
token_health['time_until_refresh'] = f"{hours:.1f} hours"
except:
pass
except Exception as e:
print(f"Error getting token health: {e}")
if 'css_file' not in ui_config or ui_config['css_file'] not in available_css:
ui_config['css_file'] = DEFAULT_CONFIG["ui"]["css_file"]
return render_template('advanced_config.html',
config=config,
ui_config=ui_config,
available_css=available_css,
spotify_configured=spotify_configured,
spotify_authenticated=spotify_authenticated,
token_health=token_health)
@app.route('/check_display_change', methods=['POST'])
def check_display_change():
current_display = load_config().get("display", {}).get("type", "framebuffer")
new_display = request.json.get('new_display_type')
needs_modification = False
message = ""
if current_display != "framebuffer" and new_display == "framebuffer":
needs_modification = True
message = "Switching to framebuffer display will uncomment 'dtoverlay=tft35a:rotate=90' in /boot/config.txt. A reboot will be required for changes to take effect."
elif current_display == "framebuffer" and new_display != "framebuffer":
needs_modification = True
message = "Switching from framebuffer display will comment out 'dtoverlay=tft35a:rotate=90' in /boot/config.txt. A reboot will be required(unless to dummy) for changes to take effect."
elif new_display != current_display:
message = "Changing display type will require a reset of hud for changes to take effect."
return jsonify({
'needs_modification': needs_modification,
'message': message,
'requires_reboot': new_display != current_display
})
@app.route('/reset_advanced_config', methods=['POST'])
def reset_advanced_config():
config = load_config()
config["display"] = DEFAULT_CONFIG["display"].copy()
config["api_keys"] = DEFAULT_CONFIG["api_keys"].copy()
config["settings"] = DEFAULT_CONFIG["settings"].copy()
config["wifi"] = DEFAULT_CONFIG["wifi"].copy()
config["buttons"] = DEFAULT_CONFIG["buttons"].copy()
config["logging"] = DEFAULT_CONFIG["logging"].copy()
config["clock"] = DEFAULT_CONFIG["clock"].copy()
preserved_ui = config.get("ui", {}).copy()
preserved_auto_start = config.get("auto_start", {}).copy()
config["ui"] = preserved_ui
config["auto_start"] = preserved_auto_start
save_config(config)
flash('success', 'Advanced configuration reset to defaults!')
return redirect(url_for('advanced_config'))
@app.route('/save_all_config', methods=['POST'])
def save_all_config():
config = load_config()
auto_start_hud = 'auto_start_hud' in request.form
auto_start_neonwifi = 'auto_start_neonwifi' in request.form
config["auto_start"] = {
"auto_start_hud": auto_start_hud,
"auto_start_neonwifi": auto_start_neonwifi
}
save_config(config)
if is_hud_running():
stop_hud()
time.sleep(3)
if auto_start_hud == True:
start_hud()
if is_neonwifi_running():
stop_neonwifi()
time.sleep(3)
if auto_start_neonwifi == True:
start_neonwifi()
flash('success', 'All settings saved successfully!')
return redirect(url_for('index'))
@app.route('/save_advanced_config', methods=['POST'])
def save_advanced_config():
config = load_config()
auto_start_hud = 'auto_start_hud' in request.form
auto_start_neonwifi = 'auto_start_neonwifi' in request.form
if "ui" not in config:
config["ui"] = {}
if "api_status" not in config:
config["api_status"] = {}
available_css = get_available_css_files()
selected_css = request.form.get('css_file')
if selected_css and selected_css in available_css:
config["ui"]["css_file"] = selected_css
else:
config["ui"]["css_file"] = DEFAULT_CONFIG["ui"]["css_file"]
openweather_key = request.form.get('openweather', '').strip()
google_geo_key = request.form.get('google_geo', '').strip()
fallback_input = request.form.get('fallback_city', '').strip()
normalized_fallback = ""
if fallback_input:
is_valid_fallback, fallback_message, normalized_fallback = validate_fallback_city_input(
fallback_input,
openweather_key or config["api_keys"].get("openweather", "")
)
if not is_valid_fallback:
config["api_status"]["fallback_city"] = _build_api_status("error", fallback_message)
save_config(config)
flash(fallback_message, 'error')
return redirect(url_for('advanced_config'))
config["api_status"]["fallback_city"] = _build_api_status("success", f"Using {normalized_fallback}")
else:
config["api_status"]["fallback_city"] = _build_api_status("info", "No fallback city set")
try:
old_display_type = config.get("display", {}).get("type", "framebuffer")
new_display_type = request.form.get('display_type', 'framebuffer')
modify_boot = False
if old_display_type != new_display_type:
if request.form.get('modify_boot_config') == 'true':
modify_boot = True
config["api_keys"]["openweather"] = openweather_key
config["api_keys"]["google_geo"] = google_geo_key
config["api_keys"]["client_id"] = request.form.get('client_id', '').strip()
config["api_keys"]["client_secret"] = request.form.get('client_secret', '').strip()
config["api_keys"]["redirect_uri"] = request.form.get('redirect_uri', 'http://127.0.0.1:5000').strip()
config["api_keys"]["lastfm"] = request.form.get('lastfm', '').strip()
config["settings"]["fallback_city"] = normalized_fallback
config["display"]["type"] = new_display_type
config["display"]["framebuffer"] = request.form.get('framebuffer_device', '/dev/fb1')
config["display"]["rotation"] = int(request.form.get('rotation', 0))
if "st7789" not in config["display"]:
config["display"]["st7789"] = {}
config["display"]["st7789"]["spi_port"] = int(request.form.get('spi_port', 0))
config["display"]["st7789"]["spi_cs"] = int(request.form.get('spi_cs', 1))
config["display"]["st7789"]["dc_pin"] = int(request.form.get('dc_pin', 9))
config["display"]["st7789"]["backlight_pin"] = int(request.form.get('backlight_pin', 13))
config["display"]["st7789"]["spi_speed"] = int(request.form.get('spi_speed', 60000000))
if "buttons" not in config:
config["buttons"] = {}
config["buttons"]["button_a"] = int(request.form.get('button_a', 5))
config["buttons"]["button_b"] = int(request.form.get('button_b', 6))
config["buttons"]["button_x"] = int(request.form.get('button_x', 16))
config["buttons"]["button_y"] = int(request.form.get('button_y', 24))
config["buttons"]["button_a_action"] = request.form.get('button_a_action', 'clock')
config["buttons"]["button_b_action"] = request.form.get('button_b_action', 'weather')
config["buttons"]["button_x_action"] = request.form.get('button_x_action', 'spotify')
config["buttons"]["button_y_action"] = request.form.get('button_y_action', 'toggle_display')
config["buttons"]["button_a_command"] = request.form.get('button_a_command', '').strip()
config["buttons"]["button_b_command"] = request.form.get('button_b_command', '').strip()
config["buttons"]["button_x_command"] = request.form.get('button_x_command', '').strip()
config["buttons"]["button_y_command"] = request.form.get('button_y_command', '').strip()
config["wifi"]["ap_ssid"] = request.form.get('ap_ssid', 'Neonwifi-Manager')
config["wifi"]["ap_ip"] = request.form.get('ap_ip', '192.168.42.1')
config["wifi"]["rescan_time"] = int(request.form.get('rescan_time', 600))
config["settings"]["progressbar_display"] = 'progressbar_display' in request.form
config["settings"]["time_display"] = 'time_display' in request.form
config["settings"]["start_screen"] = request.form.get('start_screen', 'weather')
config["settings"]["use_gpsd"] = 'use_gpsd' in request.form
config["settings"]["sleep_timeout"] = int(request.form.get('sleep_timeout', 300))
use_google_geo = 'use_google_geo' in request.form
config["settings"]["use_google_geo"] = use_google_geo
config["settings"]["enable_current_track_display"] = 'enable_current_track_display' in request.form
if "logging" not in config:
config["logging"] = {}
config["logging"]["max_log_lines"] = int(request.form.get('max_log_lines', 10000))
config["logging"]["max_backup_files"] = int(request.form.get('max_backup_files', 5))
config["api_keys"]["redirect_uri"] = request.form.get('redirect_uri', 'http://127.0.0.1:5000')
config["clock"]["background"] = request.form.get('clock_background', 'color')
config["clock"]["color"] = request.form.get('clock_color', '#000000')
config["clock"]["type"] = request.form.get('clock_type', 'digital')
config["auto_start"] = {
"auto_start_hud": auto_start_hud,
"auto_start_neonwifi": auto_start_neonwifi,
"check_internet": 'check_internet' in request.form
}
if use_google_geo:
if google_geo_key:
success, status_message = validate_google_geo_api_key(google_geo_key)
status_state = "success" if success else "error"
else:
status_state = "error"
status_message = "Google Geolocation enabled but no API key configured"
else:
if google_geo_key:
status_state = "info"
status_message = "Google Geolocation disabled (key stored but unused)"
else:
status_state = "info"
status_message = "Google Geolocation disabled"
config["api_status"]["google_geo"] = _build_api_status(status_state, status_message)
if modify_boot and old_display_type != new_display_type:
enable_fb = (new_display_type == "framebuffer")
success, message = modify_boot_config(enable_fb)
if success:
flash(f'Configuration saved! {message} Please restart hud for display changes to take effect.', 'success')
else:
flash(f'Configuration saved but boot config modification failed: {message}', 'warning')
elif old_display_type != new_display_type:
flash('Configuration saved! Please restart hud for display changes to take effect.', 'success')
else:
flash('Advanced configuration saved successfully!', 'success')
save_config(config)
restart_processes_after_config()
except Exception as e:
flash(f'Error saving configuration: {str(e)}', 'error')
return redirect(url_for('advanced_config'))
@app.route('/toggle_theme', methods=['POST'])
def toggle_theme():
config = load_config()
new_theme = request.form.get('theme', 'dark')
if 'ui' not in config:
config['ui'] = {}
config['ui']['theme'] = new_theme
save_config(config)
return redirect(request.referrer or url_for('index'))
# ============== APPLICATION CONTROL ROUTES ==============
@app.route('/start_hud', methods=['POST'])
def start_hud_route():
success, message = start_hud()
if success:
flash('success', message)
else:
flash('error', message)
return redirect(url_for('index'))
@app.route('/start_neonwifi', methods=['POST'])
def start_neonwifi_route():
success, message = start_neonwifi()
if success:
flash('success', message)
else:
flash('error', message)
return redirect(url_for('index'))
@app.route('/stop_hud', methods=['POST'])
def stop_hud_route():
success, message = stop_hud()
if success:
flash('success', message)
else:
flash('error', message)
return redirect(url_for('index'))
@app.route('/stop_neonwifi', methods=['POST'])
def stop_neonwifi_route():
success, message = stop_neonwifi()
if success:
flash('success', message)
else:
flash('error', message)
return redirect(url_for('index'))
# ============== SPOTIFY AUTHENTICATION ROUTES ==============
@app.route('/api/token_health')
def token_health():
try:
from spotify_auth_manager import SpotifyAuthManager
auth_manager = SpotifyAuthManager()
status, message = auth_manager.get_token_health()
time_until_refresh = None
if os.path.exists('.spotify_cache'):
try:
with open('.spotify_cache', 'r') as f:
cache = json.load(f)
expires_at = cache.get('expires_at', 0)
if expires_at:
time_left = expires_at - time.time()
if time_left > 0:
if time_left < 60:
time_until_refresh = f"{int(time_left)} seconds"
elif time_left < 3600:
minutes = int(time_left / 60)
time_until_refresh = f"{minutes} minutes"
else:
hours = time_left / 3600
time_until_refresh = f"{hours:.1f} hours"
except:
pass
return jsonify({
'success': True,
'status': status,
'message': message,
'time_until_refresh': time_until_refresh,
'timestamp': datetime.now().isoformat()
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e),
'timestamp': datetime.now().isoformat()
})
@app.route('/spotify_auth')
def spotify_auth_page():
config = load_config()
if not config["api_keys"]["client_id"] or not config["api_keys"]["client_secret"]:
flash('error', 'Please save Spotify Client ID and Secret first.')
return redirect(url_for('index'))
try:
sp_oauth = SpotifyOAuth(
client_id=config["api_keys"]["client_id"],
client_secret=config["api_keys"]["client_secret"],
redirect_uri=config["api_keys"]["redirect_uri"],
scope="user-read-currently-playing user-modify-playback-state user-read-playback-state playlist-modify-private playlist-modify-public playlist-read-private playlist-read-collaborative user-read-private user-library-read user-library-modify",
cache_path=".spotify_cache",
show_dialog=True
)
auth_url = sp_oauth.get_authorize_url()
ui_config = config.get("ui", DEFAULT_CONFIG["ui"])
return render_template('spotify_auth.html', auth_url=auth_url, ui_config=ui_config)
except Exception as e:
flash('error', f'Spotify authentication error: {str(e)}')
return redirect(url_for('index'))
@app.route('/process_callback_url', methods=['POST'])
def process_callback_url():
config = load_config()
callback_url = request.form.get('callback_url', '').strip()
if not callback_url:
flash('error', 'Please paste the callback URL')
return redirect(url_for('spotify_auth_page'))
try:
parsed_url = urllib.parse.urlparse(callback_url)
query_params = urllib.parse.parse_qs(parsed_url.query)
if 'error' in query_params:
error = query_params['error'][0]
flash('error', f'Spotify authentication failed: {error}')
return redirect(url_for('index'))
if 'code' not in query_params:
flash('error', 'No authorization code found in the URL.')
return redirect(url_for('spotify_auth_page'))
code = query_params['code'][0]
sp_oauth = SpotifyOAuth(
client_id=config["api_keys"]["client_id"],
client_secret=config["api_keys"]["client_secret"],
redirect_uri=config["api_keys"]["redirect_uri"],
scope="user-read-currently-playing user-modify-playback-state user-read-playback-state playlist-modify-private playlist-modify-public playlist-read-private playlist-read-collaborative user-read-private user-library-read user-library-modify",
cache_path=".spotify_cache"
)
token_info = sp_oauth.get_access_token(code, as_dict=False)
if token_info:
flash('success', 'Spotify authentication successful!')
else:
flash('error', 'Spotify authentication failed.')
except Exception as e:
flash('error', f'Authentication error: {str(e)}')
if os.path.exists(".spotify_cache"):
os.remove(".spotify_cache")
return redirect(url_for('index'))
# ============== SPOTIFY CONTROL ROUTES ==============
@app.route('/spotify_create_similar_playlist', methods=['POST'])
@rate_limit(2.0)
def spotify_create_similar_playlist():
logger = logging.getLogger('Launcher')
try:
track_name = request.json.get('track_name', '').strip()
artist_name = request.json.get('artist_name', '').strip()
if not track_name or not artist_name:
current_track = get_current_track()
if not current_track.get('has_track'):
return jsonify({'success': False, 'error': 'No track currently playing and no track specified'})
track_name = current_track['song']
artist_name = current_track['artist']
if '(' in artist_name:
artist_name = artist_name.split('(')[0].strip()
logger.info(f"Creating similar playlist for: {track_name} by {artist_name}")
sp, message = get_spotify_client()
if not sp:
return jsonify({'success': False, 'error': message})
config = load_config()
lastfm_key = config["api_keys"].get("lastfm", "")
if not lastfm_key:
return jsonify({'success': False, 'error': 'Last.fm API key not configured'})
original_track_id = search_spotify_track(track_name, artist_name, sp)
if not original_track_id:
return jsonify({'success': False, 'error': f'Track "{track_name}" by {artist_name} not found on Spotify'})
similar_tracks = get_lastfm_similar_tracks(artist_name, track_name, lastfm_key, limit=75)
if not similar_tracks:
logger.warning(f"No similar tracks found on Last.fm for: {track_name} by {artist_name}")
return jsonify({'success': False, 'error': 'No similar tracks found on Last.fm'})
not_found_count = 0
spotify_track_ids = []
logger.info("Searching for similar tracks on Spotify...")
for track in similar_tracks:
name = track.get('name', '')
artist = track.get('artist', {}).get('name', '')
if not name or not artist:
continue
try:
result = sp.search(q=f"track:{name} artist:{artist}", type='track', limit=1)
items = result['tracks']['items']
if items:
track_id = items[0]['id']
spotify_track_ids.append(track_id)
else:
logger.info(f" Not found on Spotify: {name} by {artist}")
not_found_count += 1
except Exception as e:
logger.error(f" Error searching for {name} by {artist}: {e}")
not_found_count += 1
extra_songs_needed = not_found_count
extra_track_ids = []
if extra_songs_needed > 0 and spotify_track_ids:
logger.info(f"Adding {extra_songs_needed} extra song(s) to compensate for {not_found_count} not found")
extra_similar_tracks = get_lastfm_similar_tracks(artist_name, track_name, lastfm_key, limit=75 + extra_songs_needed * 2)
if extra_similar_tracks:
already_tried = {(track.get('name', '').lower(), track.get('artist', {}).get('name', '').lower()) for track in similar_tracks}
for extra_track in extra_similar_tracks:
if len(extra_track_ids) >= extra_songs_needed:
break
name = extra_track.get('name', '')
artist = extra_track.get('artist', {}).get('name', '')
if not name or not artist:
continue
if (name.lower(), artist.lower()) in already_tried:
continue
try:
result = sp.search(q=f"track:{name} artist:{artist}", type='track', limit=1)
items = result['tracks']['items']
if items:
track_id = items[0]['id']
if track_id not in spotify_track_ids and track_id not in extra_track_ids:
extra_track_ids.append(track_id)
logger.info(f" Found extra track: {name} by {artist}")
except Exception as e:
logger.error(f" Error searching for extra track {name} by {artist}: {e}")
all_track_ids = [original_track_id] + spotify_track_ids + extra_track_ids
random.shuffle(spotify_track_ids)
all_track_ids = [original_track_id] + spotify_track_ids + extra_track_ids
playlist_name = f"NeonDisplay Recommends"
deleted_count = delete_existing_playlist(playlist_name, sp)
user_id = sp.current_user()["id"]
description = (f"Tracks similar to {track_name} by {artist_name} - Generated by NeonDisplay ")
playlist = sp.user_playlist_create(
user=user_id,
name=playlist_name,
public=False,
description=description
)
if all_track_ids:
for i in range(0, len(all_track_ids), 100):
batch = all_track_ids[i:i+100]
sp.user_playlist_add_tracks(user_id, playlist["id"], batch)
time.sleep(1)
play_success = play_playlist(playlist['uri'], sp)
return jsonify({
'success': True,
'message': f'Created playlist "{playlist_name}" with {len(all_track_ids)} tracks',
'playlist_name': playlist_name,
'playlist_url': playlist['external_urls']['spotify'],
'track_count': len(all_track_ids),
'found_count': len(spotify_track_ids),
'not_found_count': not_found_count,
'extra_added_count': len(extra_track_ids),
'auto_played': play_success,
'random_order': True
})
else:
return jsonify({'success': False, 'error': 'No tracks to add to playlist'})
except Exception as e:
logger.error(f"Error creating similar playlist: {str(e)}", exc_info=True)
return jsonify({'success': False, 'error': f'Error creating playlist: {str(e)}'})
@app.route('/spotify_generate_from_input', methods=['POST'])
@rate_limit(2.0)
def spotify_generate_from_input():
logger = logging.getLogger('Launcher')
try:
input_string = request.json.get('input_string', '').strip()
if not input_string:
return jsonify({'success': False, 'error': 'No input string provided'})
track_name, artist_name = parse_track_input(input_string)
if artist_name is None:
sp, message = get_spotify_client()
if not sp:
return jsonify({'success': False, 'error': message})
result = sp.search(q=f"track:{track_name}", type='track', limit=1)
items = result['tracks']['items']
if not items:
return jsonify({'success': False, 'error': f'Track "{track_name}" not found on Spotify'})
track_name = items[0]['name']
artist_name = items[0]['artists'][0]['name']
sp, message = get_spotify_client()
if not sp:
return jsonify({'success': False, 'error': message})
config = load_config()
lastfm_key = config["api_keys"].get("lastfm", "")
if not lastfm_key:
return jsonify({'success': False, 'error': 'Last.fm API key not configured'})
original_track_id = search_spotify_track(track_name, artist_name, sp)
if not original_track_id:
return jsonify({'success': False, 'error': f'Track "{track_name}" by {artist_name} not found on Spotify'})
similar_tracks = get_lastfm_similar_tracks(artist_name, track_name, lastfm_key, limit=75)
if not similar_tracks:
logger.warning(f"No similar tracks found on Last.fm for: {track_name} by {artist_name}")
return jsonify({'success': False, 'error': 'No similar tracks found on Last.fm'})
not_found_count = 0
spotify_track_ids = []
logger.info("Searching for similar tracks on Spotify...")
for track in similar_tracks:
name = track.get('name', '')
artist = track.get('artist', {}).get('name', '')
if not name or not artist:
continue
try:
result = sp.search(q=f"track:{name} artist:{artist}", type='track', limit=1)
items = result['tracks']['items']
if items:
track_id = items[0]['id']
spotify_track_ids.append(track_id)
else:
logger.info(f" Not found on Spotify: {name} by {artist}")
not_found_count += 1
except Exception as e:
logger.error(f" Error searching for {name} by {artist}: {e}")
not_found_count += 1
extra_songs_needed = not_found_count
extra_track_ids = []
if extra_songs_needed > 0 and spotify_track_ids:
logger.info(f"Adding {extra_songs_needed} extra song(s) to compensate for {not_found_count} not found")
extra_similar_tracks = get_lastfm_similar_tracks(artist_name, track_name, lastfm_key, limit=75 + extra_songs_needed * 2)
if extra_similar_tracks:
already_tried = {(track.get('name', '').lower(), track.get('artist', {}).get('name', '').lower()) for track in similar_tracks}
for extra_track in extra_similar_tracks:
if len(extra_track_ids) >= extra_songs_needed:
break
name = extra_track.get('name', '')
artist = extra_track.get('artist', {}).get('name', '')
if not name or not artist:
continue
if (name.lower(), artist.lower()) in already_tried:
continue
try:
result = sp.search(q=f"track:{name} artist:{artist}", type='track', limit=1)
items = result['tracks']['items']
if items:
track_id = items[0]['id']
if track_id not in spotify_track_ids and track_id not in extra_track_ids:
extra_track_ids.append(track_id)
logger.info(f" Found extra track: {name} by {artist}")
except Exception as e:
logger.error(f" Error searching for extra track {name} by {artist}: {e}")
all_track_ids = [original_track_id] + spotify_track_ids + extra_track_ids
random.shuffle(spotify_track_ids)
all_track_ids = [original_track_id] + spotify_track_ids + extra_track_ids
playlist_name = f"NeonDisplay Recommends"
deleted_count = delete_existing_playlist(playlist_name, sp)
user_id = sp.current_user()["id"]
description = (f"Tracks similar to {track_name} by {artist_name} - Generated by NeonDisplay ")
playlist = sp.user_playlist_create(
user=user_id,
name=playlist_name,
public=False,
description=description
)
if all_track_ids:
for i in range(0, len(all_track_ids), 100):
batch = all_track_ids[i:i+100]
sp.user_playlist_add_tracks(user_id, playlist["id"], batch)
time.sleep(1)
play_success = play_playlist(playlist['uri'], sp)
return jsonify({
'success': True,
'message': f'Created playlist "{playlist_name}" with {len(all_track_ids)} tracks',
'playlist_name': playlist_name,
'playlist_url': playlist['external_urls']['spotify'],
'track_count': len(all_track_ids),
'found_count': len(spotify_track_ids),
'not_found_count': not_found_count,
'extra_added_count': len(extra_track_ids),
'auto_played': play_success,
'random_order': True
})
else:
return jsonify({'success': False, 'error': 'No tracks to add to playlist'})
except Exception as e:
logger.error(f"Error generating playlist from input: {str(e)}", exc_info=True)
return jsonify({'success': False, 'error': f'Error: {str(e)}'})
@app.route('/spotify_like_track', methods=['POST'])
@rate_limit(1.0)
def spotify_like_track():
try:
track_id = request.json.get('track_id', '').strip()
if not track_id:
return jsonify({'success': False, 'error': 'No track ID provided'})
sp, message = get_spotify_client()
if not sp:
return jsonify({'success': False, 'error': message})
sp.current_user_saved_tracks_add([track_id])
return jsonify({'success': True, 'message': 'Track added to Liked Songs'})
except Exception as e:
logger = logging.getLogger('Launcher')
logger.error(f"Error liking track: {str(e)}")
return jsonify({'success': False, 'error': str(e)})
@app.route('/spotify_next', methods=['POST'])
@rate_limit(0.5)
def spotify_next():
if not check_internet_connection(timeout=3):
return {'success': False, 'error': 'No internet connection'}
try:
sp, message = get_spotify_client()
if not sp:
return {'success': False, 'error': message}
sp.next_track()
return {'success': True, 'message': 'Skipped to next track'}
except Exception as e:
logger = logging.getLogger('Launcher')
logger.error(f"Next track error: {str(e)}")
return {'success': False, 'error': str(e)}
@app.route('/spotify_pause', methods=['POST'])
@rate_limit(0.5)
def spotify_pause():
try:
sp, message = get_spotify_client()
if not sp:
return {'success': False, 'error': message}
sp.pause_playback()
return {'success': True, 'message': 'Playback paused'}
except Exception as e:
logger = logging.getLogger('Launcher')