-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload_server.py
More file actions
2273 lines (1911 loc) · 91.6 KB
/
upload_server.py
File metadata and controls
2273 lines (1911 loc) · 91.6 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
"""
Web management server for e-ink display system.
Provides both API endpoints and web interface for file management.
"""
import os
import time
import json
import base64
import hashlib
import random
from pathlib import Path
from flask import Flask, request, jsonify, render_template, send_from_directory, url_for, session, redirect, flash
from werkzeug.utils import secure_filename
from PIL import Image
import logging
from functools import wraps
# Load environment variables from .env file if it exists (robust path handling)
# Define candidate env file locations
PROJECT_DIR = Path(__file__).resolve().parent
PROJECT_ENV_PATH = PROJECT_DIR / '.env'
HOME_ENV_PATH = Path.home() / 'RpiEinky' / '.env'
ENV_PATH_USED = None
def _load_env_file_manual(env_path: Path) -> bool:
try:
if not env_path.exists():
return False
with open(env_path, 'r') as f:
for raw_line in f:
line = raw_line.strip()
if not line or line.startswith('#'):
continue
if '=' not in line:
continue
key, value = line.split('=', 1)
key = key.strip()
value = value.strip().strip('"').strip("'")
os.environ[key] = value
return True
except Exception as e:
logger.warning(f"Manual .env load failed from {env_path}: {e}")
return False
try:
from dotenv import load_dotenv
# Try project directory .env first, then user's RpiEinky folder
if PROJECT_ENV_PATH.exists():
load_dotenv(dotenv_path=str(PROJECT_ENV_PATH))
ENV_PATH_USED = str(PROJECT_ENV_PATH)
elif HOME_ENV_PATH.exists():
load_dotenv(dotenv_path=str(HOME_ENV_PATH))
ENV_PATH_USED = str(HOME_ENV_PATH)
else:
# Fallback to default discovery (current working dir)
load_dotenv()
ENV_PATH_USED = 'auto'
except ImportError:
# Fallback: try manual loader
if PROJECT_ENV_PATH.exists() and _load_env_file_manual(PROJECT_ENV_PATH):
ENV_PATH_USED = str(PROJECT_ENV_PATH)
elif HOME_ENV_PATH.exists() and _load_env_file_manual(HOME_ENV_PATH):
ENV_PATH_USED = str(HOME_ENV_PATH)
else:
ENV_PATH_USED = 'none'
# Configure logging
import os
# Use the user's home directory for log files
log_dir = os.path.expanduser('~/logs')
os.makedirs(log_dir, exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(os.path.join(log_dir, 'eink_upload.log')), # Log to file
logging.StreamHandler() # Also log to console
]
)
logger = logging.getLogger(__name__)
# Simple localization support
MESSAGES = {
'en': {
'file_uploaded': 'File uploaded successfully',
'file_deleted': 'File deleted successfully',
'display_cleared': 'Display cleared',
'settings_saved': 'Settings saved successfully',
'playlist_saved': 'Playlist saved successfully',
'playlist_started': 'Playlist started',
'playlist_stopped': 'Playlist stopped',
'playlist_resumed': 'Playlist resumed',
'welcome_screen_displayed': 'Welcome screen displayed',
'files_refreshed': 'File list refreshed',
'folder_cleaned': 'All files deleted successfully',
'connection_lost': 'Connection lost',
'connection_restored': 'Connection restored',
'upload_failed': 'Failed to upload file',
'delete_failed': 'Failed to delete file',
'settings_failed': 'Failed to save settings',
'playlist_failed': 'Failed to save playlist'
},
'hu': {
'file_uploaded': 'Fájl sikeresen feltöltve',
'file_deleted': 'Fájl sikeresen törölve',
'display_cleared': 'Kijelző törölve',
'settings_saved': 'Beállítások sikeresen mentve',
'playlist_saved': 'Lejátszási lista sikeresen mentve',
'playlist_started': 'Lejátszási lista elindítva',
'playlist_stopped': 'Lejátszási lista leállítva',
'playlist_resumed': 'Lejátszási lista folytatva',
'welcome_screen_displayed': 'Üdvözlő képernyő megjelenítve',
'files_refreshed': 'Fájllista frissítve',
'folder_cleaned': 'Minden fájl sikeresen törölve',
'connection_lost': 'Kapcsolat megszakadt',
'connection_restored': 'Kapcsolat helyreállt',
'upload_failed': 'Fájl feltöltése sikertelen',
'delete_failed': 'Fájl törlése sikertelen',
'settings_failed': 'Beállítások mentése sikertelen',
'playlist_failed': 'Lejátszási lista mentése sikertelen'
}
}
def get_message(key, lang='en'):
"""Get localized message"""
return MESSAGES.get(lang, {}).get(key, MESSAGES['en'].get(key, key))
def get_client_language():
"""Get client language from request headers or session"""
# Try to get from session first
lang = session.get('language')
if lang and lang in MESSAGES:
return lang
# Try to get from Accept-Language header
if request.headers.get('Accept-Language'):
for lang_code in request.headers.get('Accept-Language', '').split(','):
lang = lang_code.split('-')[0].strip()
if lang in MESSAGES:
return lang
return 'en' # Default to English
app = Flask(__name__, template_folder='templates', static_folder='static')
app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # 100MB max file size
# Security configuration
app.config['SECRET_KEY'] = os.environ.get('FLASK_SECRET_KEY', 'your-secret-key-change-this-in-production')
# Only require secure cookies in production (HTTPS)
app.config['SESSION_COOKIE_SECURE'] = os.environ.get('FLASK_ENV') == 'production'
app.config['SESSION_COOKIE_HTTPONLY'] = True # Prevent JavaScript access to session cookie
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' # CSRF protection
# Admin password configuration
ADMIN_PASSWORD_HASH = (os.environ.get('ADMIN_PASSWORD_HASH') or '').strip().lower()
# Support plaintext ADMIN_PASSWORD if provided (hash it), otherwise fall back to default
if not ADMIN_PASSWORD_HASH:
if os.environ.get('ADMIN_PASSWORD'):
ADMIN_PASSWORD_HASH = hashlib.sha256(os.environ.get('ADMIN_PASSWORD', '').strip().encode()).hexdigest()
else:
ADMIN_PASSWORD_HASH = hashlib.sha256('admin123'.encode()).hexdigest() # Default password: admin123
# Log auth/config status at startup (non-sensitive)
_default_hash = hashlib.sha256('admin123'.encode()).hexdigest()
IS_DEFAULT_PASSWORD = (ADMIN_PASSWORD_HASH == _default_hash)
# Log environment loading status at import time as well (works even if run via a wrapper)
try:
logger.info(f"dotenv path used: {globals().get('ENV_PATH_USED', 'none')}")
logger.info(f"ADMIN_PASSWORD_HASH loaded: {'set' if ADMIN_PASSWORD_HASH else 'missing'}; default: {IS_DEFAULT_PASSWORD}")
except Exception:
pass
# API key for TouchDesigner (generate a secure random key)
API_KEY = os.environ.get('API_KEY', 'td-api-key-change-this-in-production')
# Configuration
UPLOAD_FOLDER = os.path.expanduser('~/watched_files')
THUMBNAILS_FOLDER = os.path.join(UPLOAD_FOLDER, '.thumbnails')
APP_CONFIG_DIR = os.path.expanduser('~/.config/rpi-einky')
SETTINGS_FILE = os.path.join(APP_CONFIG_DIR, 'settings.json')
COMMANDS_DIR = os.path.join(APP_CONFIG_DIR, 'commands')
ALLOWED_EXTENSIONS = {
'txt', 'md', 'py', 'js', 'html', 'css', # Text files
'jpg', 'jpeg', 'png', 'bmp', 'gif', # Images
'pdf', # PDFs
'json', 'xml', 'csv' # Data files
}
# Default settings
DEFAULT_SETTINGS = {
'image_crop_mode': 'center_crop', # 'center_crop' or 'fit_with_letterbox'
'auto_display_upload': True, # Automatically display uploaded files
'thumbnail_quality': 85, # JPEG quality for thumbnails
'max_file_size_mb': 16, # Maximum file size in MB
'startup_delay_minutes': 1, # Startup delay before displaying latest file
'refresh_interval_hours': 24, # Refresh interval to prevent ghosting
'enable_startup_timer': True, # Enable automatic startup display timer
'enable_refresh_timer': True, # Enable automatic refresh timer
'enable_manufacturer_timing': False, # Enable manufacturer timing requirements (180s minimum)
'enable_sleep_mode': True, # Enable sleep mode between operations (power efficiency)
'orientation': 'landscape', # Display orientation: 'landscape', 'portrait', 'landscape_flipped', 'portrait_flipped'
'language': 'en', # Interface language: 'en', 'hu'
# Playlist settings
'playlist_enabled': True, # Enable playlist mode
'playlist_interval_minutes': 5, # Minutes between playlist image changes
'playlist_current_name': 'default', # Name of currently active playlist
'playlists': { # Dictionary of named playlists
'default': {
'name': 'Default Playlist',
'files': [],
'current_index': 0,
'last_change': 0,
'randomize': False,
'shuffled_order': [],
'shuffle_index': 0
}
},
'display_mode': 'playlist', # 'manual', 'playlist', or 'live' (TouchDesigner upload)
'live_mode_timeout_minutes': 30, # Minutes to wait before returning to playlist from live mode (0 = no timeout)
'live_mode_start_time': 0 # Timestamp when live mode started
}
# Image extensions for thumbnail generation
IMAGE_EXTENSIONS = {'jpg', 'jpeg', 'png', 'bmp', 'gif'}
# Authentication functions
def login_required(f):
"""Decorator to require authentication for routes"""
@wraps(f)
def decorated_function(*args, **kwargs):
# Check for API key authentication (TouchDesigner)
api_key = request.headers.get('X-API-Key') or request.headers.get('Authorization')
if api_key:
# Remove "Bearer " prefix if present
if api_key.startswith('Bearer '):
api_key = api_key[7:]
if api_key == API_KEY:
return f(*args, **kwargs)
else:
return jsonify({'error': 'Invalid API key'}), 401
# Check for session authentication (web interface)
if not session.get('logged_in'):
if request.is_json:
return jsonify({'error': 'Authentication required. Use X-API-Key header or login via web interface.'}), 401
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
def check_password(password):
"""Check if provided password matches admin password"""
return hashlib.sha256(password.encode()).hexdigest() == ADMIN_PASSWORD_HASH
def allowed_file(filename):
"""Check if file extension is allowed"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def ensure_upload_folder():
"""Create upload folder and thumbnails folder if they don't exist"""
Path(UPLOAD_FOLDER).mkdir(parents=True, exist_ok=True)
Path(THUMBNAILS_FOLDER).mkdir(parents=True, exist_ok=True)
Path(APP_CONFIG_DIR).mkdir(parents=True, exist_ok=True)
Path(COMMANDS_DIR).mkdir(parents=True, exist_ok=True)
def load_settings():
"""Load settings from file or return defaults"""
try:
if os.path.exists(SETTINGS_FILE):
try:
with open(SETTINGS_FILE, 'r') as f:
content = f.read().strip()
if content: # File is not empty
saved_settings = json.loads(content)
logger.info(f"Settings loaded from {SETTINGS_FILE}")
else:
# File is empty
logger.warning(f"Settings file {SETTINGS_FILE} is empty, using defaults")
saved_settings = {}
except (json.JSONDecodeError, FileNotFoundError) as e:
# File is corrupted or can't be read
logger.warning(f"Settings file {SETTINGS_FILE} is corrupted or unreadable: {e}, using defaults")
saved_settings = {}
else:
logger.info(f"Settings file not found at {SETTINGS_FILE}, using defaults")
saved_settings = {}
# Check if all required settings are present
settings_need_update = False
for key, default_value in DEFAULT_SETTINGS.items():
if key not in saved_settings:
logger.warning(f"Missing setting '{key}' in settings file, using default: {default_value}")
settings_need_update = True
break
# Merge with defaults to ensure all settings exist
settings = DEFAULT_SETTINGS.copy()
settings.update(saved_settings)
# Update settings file if it was missing, empty, corrupted, or had missing fields
if settings_need_update:
try:
os.makedirs(os.path.dirname(SETTINGS_FILE), exist_ok=True)
with open(SETTINGS_FILE, 'w') as f:
json.dump(settings, f, indent=2)
logger.info(f"Updated settings file with complete values: {list(settings.keys())}")
except Exception as e:
logger.error(f"Error updating settings file: {e}")
return settings
except Exception as e:
logger.error(f"Error loading settings: {e}")
return DEFAULT_SETTINGS.copy()
def save_settings(settings):
"""Save settings to file atomically with rolling backups.
Strategy:
- Write to SETTINGS_FILE.tmp then os.replace() -> atomic on POSIX/Win10+
- Keep up to 5 timestamped backups in the same directory
"""
try:
settings_dir = os.path.dirname(SETTINGS_FILE)
os.makedirs(settings_dir, exist_ok=True)
# Create a timestamped backup if the file exists and is non-empty
if os.path.exists(SETTINGS_FILE):
try:
if os.path.getsize(SETTINGS_FILE) > 0:
ts = datetime.now().strftime('%Y%m%d-%H%M%S')
backup_file = os.path.join(settings_dir, f"settings.{ts}.bak.json")
try:
# Best-effort copy existing file
with open(SETTINGS_FILE, 'r') as src, open(backup_file, 'w') as dst:
dst.write(src.read())
logger.info(f"Created settings backup: {backup_file}")
except Exception as e:
logger.warning(f"Failed to create settings backup: {e}")
# Prune old backups, keep last 5
try:
backups = sorted([
p for p in Path(settings_dir).glob('settings.*.bak.json')
], key=lambda p: p.stat().st_mtime, reverse=True)
for old in backups[5:]:
old.unlink(missing_ok=True)
except Exception as e:
logger.warning(f"Failed to prune old backups: {e}")
except Exception:
pass
# Atomic write via temp + replace
tmp_path = SETTINGS_FILE + '.tmp'
with open(tmp_path, 'w') as f:
json.dump(settings, f, indent=2)
f.flush()
os.fsync(f.fileno()) if hasattr(os, 'fsync') else None
os.replace(tmp_path, SETTINGS_FILE)
logger.info("Settings saved successfully (atomic)")
return True
except Exception as e:
logger.error(f"Error saving settings: {e}")
try:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
except Exception:
pass
return False
def get_setting(key, default=None):
"""Get a specific setting value"""
settings = load_settings()
return settings.get(key, default)
def get_file_type(filename):
"""Determine file type category"""
ext = filename.rsplit('.', 1)[1].lower() if '.' in filename else ''
if ext in IMAGE_EXTENSIONS:
return 'image'
elif ext in {'txt', 'md', 'py', 'js', 'html', 'css', 'json', 'xml', 'csv'}:
return 'text'
elif ext == 'pdf':
return 'pdf'
else:
return 'other'
def generate_thumbnail(filepath, filename):
"""Generate thumbnail for image files"""
try:
file_ext = filename.rsplit('.', 1)[1].lower() if '.' in filename else ''
if file_ext not in IMAGE_EXTENSIONS:
return None
# Create thumbnail filename
name_without_ext = filename.rsplit('.', 1)[0]
thumb_filename = f"{name_without_ext}_thumb.jpg"
thumb_path = os.path.join(THUMBNAILS_FOLDER, thumb_filename)
# Skip if thumbnail already exists and is newer than original
if os.path.exists(thumb_path):
if os.path.getmtime(thumb_path) >= os.path.getmtime(filepath):
return thumb_filename
# Generate thumbnail
with Image.open(filepath) as img:
# Convert to RGB if necessary (for PNG with transparency)
if img.mode in ('RGBA', 'LA', 'P'):
# Create white background
rgb_img = Image.new('RGB', img.size, (255, 255, 255))
if img.mode == 'P':
img = img.convert('RGBA')
rgb_img.paste(img, mask=img.split()[-1] if img.mode == 'RGBA' else None)
img = rgb_img
elif img.mode != 'RGB':
img = img.convert('RGB')
# Create thumbnail (max 200x200)
img.thumbnail((200, 200), Image.Resampling.LANCZOS)
img.save(thumb_path, 'JPEG', quality=85)
logger.info(f"Generated thumbnail: {thumb_filename}")
return thumb_filename
except Exception as e:
logger.error(f"Thumbnail generation failed for {filename}: {e}")
return None
def _is_valid_image_file(filepath: str) -> bool:
"""Return True if filepath is a readable image with PIL verify()."""
try:
with Image.open(filepath) as img:
img.verify()
return True
except Exception as e:
logger.warning(f"Invalid image file detected, removing: {filepath} ({e})")
return False
def _cleanup_recent_variants(prefix: str, ext: str, current_ts: int, current_filepath: str, window_seconds: int = 5) -> int:
"""Remove older variant files with the same prefix within a short time window.
Files are expected to be named as: f"{prefix}_{timestamp}{ext}" where timestamp is an int.
Keeps the current file and deletes older variants within window_seconds.
Returns number of files removed.
"""
try:
removed = 0
folder = Path(UPLOAD_FOLDER)
for f in folder.glob(f"{prefix}_*{ext}"):
try:
# Skip the current file
if str(f) == str(current_filepath):
continue
# Parse timestamp suffix
stem = f.stem # e.g., prefix_1699999999
if '_' not in stem:
continue
ts_part = stem.rsplit('_', 1)[-1]
if not ts_part.isdigit():
continue
ts = int(ts_part)
# Only consider close-in-time predecessors
if 0 <= (current_ts - ts) <= window_seconds:
f.unlink(missing_ok=True)
removed += 1
except Exception as e:
logger.warning(f"Variant cleanup skip for {f}: {e}")
if removed:
logger.info(f"Removed {removed} recent variant(s) for prefix '{prefix}' within {window_seconds}s window")
return removed
except Exception as e:
logger.warning(f"Variant cleanup error for prefix '{prefix}': {e}")
return 0
def trigger_settings_reload_and_redisplay():
"""Trigger a settings reload and re-display of current content when settings change"""
try:
logger.info("Starting settings reload and redisplay process")
# Brief delay to ensure settings file is written
import time
time.sleep(0.5)
# Send a refresh command to the main handler
command_file = Path(COMMANDS_DIR) / 'refresh_display.json'
command_data = {
'action': 'refresh_display',
'timestamp': time.time()
}
with open(command_file, 'w') as f:
json.dump(command_data, f)
logger.info(f"Sent refresh display command to {command_file}")
return True
except Exception as e:
logger.error(f"Error in trigger_settings_reload_and_redisplay: {e}")
return False
def display_file_on_eink(filename, mode='manual'):
"""Display a specific file on the e-ink display"""
try:
# Save the selected image setting and display mode
settings = load_settings()
old_selected = settings.get('selected_image')
settings['selected_image'] = filename
settings['display_mode'] = mode
# Set live mode start time if entering live mode
if mode == 'live':
settings['live_mode_start_time'] = time.time()
save_success = save_settings(settings)
logger.info(f"display_file_on_eink: Updated selected_image from '{old_selected}' to '{filename}' (mode: {mode}): save_success={save_success}")
# Verify the save worked
if save_success:
verification_settings = load_settings()
verification_selected = verification_settings.get('selected_image')
if verification_selected != filename:
logger.error(f"display_file_on_eink VERIFICATION FAILED: Expected '{filename}', got '{verification_selected}'")
else:
logger.info(f"display_file_on_eink: Verified selected_image correctly saved as '{filename}'")
# Small delay to ensure settings file is written
time.sleep(0.1)
# Write a display command for the main handler to execute
command_file = Path(COMMANDS_DIR) / 'display_file.json'
command_data = {
'action': 'display_file',
'filename': filename,
'mode': mode,
'timestamp': time.time()
}
with open(command_file, 'w') as f:
json.dump(command_data, f)
logger.info(f"Sent display command for: {filename} (mode: {mode})")
return True
except Exception as e:
logger.error(f"Failed to send display command for {filename}: {e}")
return False
def get_playlist_files():
"""Get list of image files suitable for playlist"""
try:
folder = Path(UPLOAD_FOLDER)
files = [f for f in folder.glob('*') if f.is_file() and not f.name.startswith('.')]
# Filter to only image files
image_files = []
for file in files:
if file.suffix.lower().lstrip('.') in IMAGE_EXTENSIONS:
image_files.append({
'filename': file.name,
'size': file.stat().st_size,
'modified': file.stat().st_mtime
})
# Sort by modification time (latest first)
image_files.sort(key=lambda f: f['modified'], reverse=True)
return image_files
except Exception as e:
logger.error(f"Error getting playlist files: {e}")
return []
def get_all_image_filenames():
"""Return a deterministic list of all image filenames available for playlists.
This is used to make the 'default' playlist virtual so it always
includes all available image files without manual maintenance.
"""
try:
folder = Path(UPLOAD_FOLDER)
files = [
f.name
for f in folder.glob('*')
if f.is_file() and not f.name.startswith('.') and f.suffix.lower().lstrip('.') in IMAGE_EXTENSIONS
]
# Use alphabetical order for determinism in sequential mode
files.sort(key=lambda n: n.lower())
return files
except Exception as e:
logger.error(f"Error getting all image filenames: {e}")
return []
def advance_playlist():
"""Advance to next item in playlist and display it"""
try:
settings = load_settings()
if not settings.get('playlist_enabled', False):
return False
# Get current playlist
current_playlist_name = settings.get('playlist_current_name', 'default')
playlists = settings.get('playlists', {})
if current_playlist_name not in playlists:
logger.warning(f"Current playlist '{current_playlist_name}' not found")
return False
current_playlist = playlists[current_playlist_name]
# Determine effective file list (virtual for default)
if current_playlist_name == 'default':
playlist_files = get_all_image_filenames()
else:
playlist_files = current_playlist.get('files', [])
if not playlist_files:
logger.warning(f"Playlist '{current_playlist_name}' is enabled but has no files")
return False
# Verify files still exist
existing_files = []
folder = Path(UPLOAD_FOLDER)
for filename in playlist_files:
if (folder / filename).exists():
existing_files.append(filename)
if not existing_files:
logger.warning(f"No files in playlist '{current_playlist_name}' exist anymore")
return False
# Update playlist if files were removed
if current_playlist_name != 'default' and len(existing_files) != len(playlist_files):
current_playlist['files'] = existing_files
settings['playlists'][current_playlist_name] = current_playlist
logger.info(f"Updated playlist '{current_playlist_name}', removed {len(playlist_files) - len(existing_files)} missing files")
# Get current index and advance
current_index = current_playlist.get('current_index', 0)
randomize = current_playlist.get('randomize', False)
if randomize:
# Shuffle approach - ensure every file is shown once before repeating
shuffled_order = current_playlist.get('shuffled_order', [])
shuffle_index = current_playlist.get('shuffle_index', 0)
new_len = len(existing_files)
full_set = set(range(new_len))
# Initialize if empty or index out of bounds
needs_full_regen = (
not shuffled_order or
shuffle_index >= len(shuffled_order) or
any((idx < 0 or idx >= new_len) for idx in shuffled_order)
)
if needs_full_regen:
shuffled_order = list(range(new_len))
random.shuffle(shuffled_order)
shuffle_index = 0
logger.info(f"Generated new shuffled order for playlist '{current_playlist_name}': {shuffled_order}")
else:
# Insert newly added files at random positions AFTER the current pointer
current_set = set(shuffled_order)
missing = list(full_set - current_set)
if missing:
random.shuffle(missing)
insert_start = max(0, min(shuffle_index, len(shuffled_order)))
for new_idx in missing:
insert_pos = random.randint(insert_start, len(shuffled_order))
shuffled_order.insert(insert_pos, new_idx)
logger.info(f"Inserted {len(missing)} new items into shuffle for '{current_playlist_name}' starting at pos {insert_start}: {missing}")
# Get the current file from shuffled order
current_index = shuffled_order[shuffle_index]
# Advance shuffle index for next time
shuffle_index = (shuffle_index + 1) % len(shuffled_order)
# If we've completed a full pass, reshuffle for the next cycle
if shuffle_index == 0:
new_order = list(range(len(existing_files)))
random.shuffle(new_order)
logger.info(f"Completed full shuffle pass for '{current_playlist_name}'. New order: {new_order}")
shuffled_order = new_order
# Store the updated shuffle state
current_playlist['shuffled_order'] = shuffled_order
current_playlist['shuffle_index'] = shuffle_index
else:
# Sequential selection - advance to next file
current_index = (current_index + 1) % len(existing_files)
filename = existing_files[current_index]
# Display the file
success = display_file_on_eink(filename, mode='playlist')
if success:
# Reload settings to get the updated display_mode from display_file_on_eink
settings = load_settings()
playlists = settings.get('playlists', {})
current_playlist = playlists.get(current_playlist_name, {})
# Update playlist with current index and timestamp
# current_index should always point to the currently displayed file
current_playlist['current_index'] = current_index
current_playlist['last_change'] = time.time()
settings['playlists'][current_playlist_name] = current_playlist
playlist_save_success = save_settings(settings)
if randomize:
shuffle_pos = current_playlist.get('shuffle_index', 0)
total_in_shuffle = len(current_playlist.get('shuffled_order', []))
mode_text = f"shuffle ({shuffle_pos}/{total_in_shuffle})"
else:
mode_text = "sequential"
logger.info(f"Playlist '{current_playlist_name}' advanced to: {filename} (index {current_index}, {mode_text} mode)")
logger.info(f"Playlist settings save result: {playlist_save_success}")
# Verify that selected_image was updated correctly
verification_settings = load_settings()
verification_selected = verification_settings.get('selected_image')
if verification_selected != filename:
logger.error(f"SYNC ERROR: Expected selected_image='{filename}', but got '{verification_selected}' after save!")
else:
logger.info(f"Verified: selected_image correctly set to '{filename}'")
return True
else:
logger.error(f"Failed to display playlist file: {filename}")
return False
except Exception as e:
logger.error(f"Error advancing playlist: {e}")
return False
def check_playlist_timer():
"""Check if it's time to advance the playlist or timeout from live mode"""
try:
settings = load_settings()
if not settings.get('playlist_enabled', False):
return False
# Check if we should timeout from live mode back to playlist
if settings.get('display_mode') == 'live':
live_timeout_minutes = settings.get('live_mode_timeout_minutes', 30)
live_start_time = settings.get('live_mode_start_time', 0)
# If timeout is disabled (0), stay in live mode
if live_timeout_minutes == 0:
return False
# Check if live mode has timed out
if time.time() - live_start_time >= (live_timeout_minutes * 60):
logger.info(f"Live mode timed out after {live_timeout_minutes} minutes, returning to playlist")
# Force advance playlist to resume playlist mode
return advance_playlist()
else:
return False
# Get current playlist for timing check
current_playlist_name = settings.get('playlist_current_name', 'default')
playlists = settings.get('playlists', {})
if current_playlist_name not in playlists:
return False
current_playlist = playlists[current_playlist_name]
interval_minutes = settings.get('playlist_interval_minutes', 5)
last_change = current_playlist.get('last_change', 0)
# Check if enough time has passed for playlist advance
if time.time() - last_change >= (interval_minutes * 60):
return advance_playlist()
return False
except Exception as e:
logger.error(f"Error checking playlist timer: {e}")
return False
@app.route('/upload', methods=['POST', 'PUT'])
@login_required
def upload_file():
"""Handle file upload from TouchDesigner"""
try:
if request.method == 'POST':
# Handle both multipart form data and raw binary data
# Check if this is raw binary data (TouchDesigner tunnel upload)
if request.headers.get('Content-Type') == 'application/octet-stream' and request.headers.get('X-Filename'):
# Handle raw binary data from TouchDesigner
filename = request.headers.get('X-Filename', 'uploaded_file')
file_data = request.get_data()
logger.info(f"POST raw binary upload: {filename}, size: {len(file_data)} bytes")
if not file_data or len(file_data) == 0:
logger.error("No file data received in POST request")
return jsonify({'error': 'No file data received'}), 400
if not allowed_file(filename):
return jsonify({'error': 'File type not allowed'}), 400
# Secure the filename
filename = secure_filename(filename)
# Add timestamp to avoid conflicts
timestamp = int(time.time())
name, ext = os.path.splitext(filename)
filename = f"{name}_{timestamp}{ext}"
# Save file data using atomic operation
filepath = os.path.join(UPLOAD_FOLDER, filename)
temp_filepath = filepath + '.tmp'
# Write to temporary file first
logger.info(f"Starting raw data write to temp: {temp_filepath}, data size: {len(file_data)} bytes")
with open(temp_filepath, 'wb') as f:
f.write(file_data)
logger.info(f"Raw data write completed, file size: {os.path.getsize(temp_filepath)} bytes")
# Atomically move to final location
logger.info(f"Performing atomic rename from {temp_filepath} to {filepath}")
os.rename(temp_filepath, filepath)
logger.info(f"Atomic rename completed")
# Validate image; discard if corrupt (no thumbnail will be generated for invalid)
if not _is_valid_image_file(filepath):
try:
os.remove(filepath)
logger.warning(f"Discarded invalid image file: {filename}")
finally:
return jsonify({'error': 'Invalid image file'}), 400
# Remove older variants with close timestamps (TouchDesigner duplicate mitigation)
try:
_cleanup_recent_variants(name, ext, timestamp, filepath, window_seconds=10)
except Exception as e:
logger.warning(f"Variant cleanup failed: {e}")
# Generate thumbnail
try:
generate_thumbnail(filepath)
logger.info(f"Thumbnail generated for {filename}")
except Exception as e:
logger.error(f"Thumbnail generation failed for {filename}: {e}")
# Auto-display if enabled
settings = load_settings()
if settings.get('auto_display_upload', True):
logger.info(f"Auto-display enabled, displaying uploaded file: {filename}")
result = display_file_on_eink(filename, mode='live')
logger.info(f"Auto-display result for {filename}: {result}")
else:
logger.info(f"Auto-display disabled, not displaying uploaded file: {filename}")
logger.info(f"File uploaded (POST binary): {filename}")
return jsonify({
'message': 'File uploaded successfully',
'filename': filename,
'size': os.path.getsize(filepath)
}), 200
# Handle multipart form data (traditional upload)
elif 'file' in request.files:
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No file selected'}), 400
if file and allowed_file(file.filename):
# Secure the filename
filename = secure_filename(file.filename)
# Add timestamp to avoid conflicts
timestamp = int(time.time())
name, ext = os.path.splitext(filename)
filename = f"{name}_{timestamp}{ext}"
# Save file to watched folder using atomic operation
filepath = os.path.join(UPLOAD_FOLDER, filename)
temp_filepath = filepath + '.tmp'
# Write to temporary file first
logger.info(f"Starting file save to temp: {temp_filepath}")
file.save(temp_filepath)
logger.info(f"File save completed, size: {os.path.getsize(temp_filepath)} bytes")
# Atomically move to final location (only then will watcher see it)
logger.info(f"Performing atomic rename from {temp_filepath} to {filepath}")
os.rename(temp_filepath, filepath)
logger.info(f"Atomic rename completed")
# Validate image; discard if corrupt
if not _is_valid_image_file(filepath):
try:
os.remove(filepath)
logger.warning(f"Discarded invalid image file: {filename}")
finally:
return jsonify({'error': 'Invalid image file'}), 400
# Remove older variants with close timestamps (TouchDesigner duplicate mitigation)
try:
_cleanup_recent_variants(name, ext, timestamp, filepath, window_seconds=10)
except Exception as e:
logger.warning(f"Variant cleanup failed: {e}")
# Generate thumbnail if it's an image
generate_thumbnail(filepath, filename)
# Check if auto-display is enabled and display the file
settings = load_settings()
if settings.get('auto_display_upload', True):
logger.info(f"Auto-display enabled, displaying uploaded file: {filename}")
success = display_file_on_eink(filename, mode='live')
logger.info(f"Auto-display result for {filename}: {success}")
else:
logger.info(f"Auto-display disabled, not displaying uploaded file: {filename}")
logger.info(f"File uploaded (POST): {filename}")
return jsonify({
'message': 'File uploaded successfully',
'filename': filename,
'size': os.path.getsize(filepath)
}), 200
else:
return jsonify({'error': 'File type not allowed'}), 400
else:
return jsonify({'error': 'No file provided'}), 400
elif request.method == 'PUT':
# Handle raw file data (TouchDesigner WebclientDAT uploadFile)
# TouchDesigner sends data differently, try multiple approaches
# Debug: Log all request details
logger.info(f"PUT request debug:")
logger.info(f" Headers: {dict(request.headers)}")
logger.info(f" Content-Type: {request.content_type}")
logger.info(f" Content-Length: {request.content_length}")
logger.info(f" Has files: {bool(request.files)}")
logger.info(f" Files keys: {list(request.files.keys()) if request.files else 'None'}")
logger.info(f" Form data: {dict(request.form) if request.form else 'None'}")
logger.info(f" Raw data length: {len(request.data) if request.data else 0}")
logger.info(f" Via Cloudflare: {'CF-Ray' in request.headers}")
logger.info(f" Remote addr: {request.remote_addr}")
logger.info(f" X-Forwarded-For: {request.headers.get('X-Forwarded-For', 'None')}")
# Get filename from headers or use a default
filename = request.headers.get('X-Filename', 'uploaded_file')
# Try to get file data from different sources
file_data = None
data_source = "unknown"
# Method 1: Check if there's form data with file
if request.files:
logger.info("Trying method 1: form files")
file_obj = list(request.files.values())[0] # Get first file
file_data = file_obj.read()
data_source = "form_files"
if not filename or filename == 'uploaded_file':
filename = file_obj.filename or 'uploaded_file'
logger.info(f"Form files method: got {len(file_data)} bytes")
# Method 2: Check raw request data
elif request.data and len(request.data) > 0:
logger.info("Trying method 2: request.data")
file_data = request.data
data_source = "request_data"
logger.info(f"Request data method: got {len(file_data)} bytes")
# Method 3: Check if it's in the request stream
elif hasattr(request, 'stream'):
logger.info("Trying method 3: request.stream")
try:
file_data = request.stream.read()
data_source = "request_stream"
logger.info(f"Request stream method: got {len(file_data) if file_data else 0} bytes")
except Exception as e:
logger.info(f"Request stream method failed: {e}")
pass
# Method 4: Try to read from request directly
if not file_data:
logger.info("Trying method 4: request.get_data()")
try:
file_data = request.get_data()
data_source = "get_data"
logger.info(f"Get data method: got {len(file_data) if file_data else 0} bytes")
except Exception as e:
logger.info(f"Get data method failed: {e}")
pass