-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2017 lines (1618 loc) · 64.3 KB
/
app.py
File metadata and controls
2017 lines (1618 loc) · 64.3 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
"""
Pi Photo Frame - A web-based photo display system for Raspberry Pi
Upload photos via web interface, display on TV with customizable mat colors
"""
import os
import json
import uuid
import secrets
import hashlib
import fcntl
import re
import random
import time
import subprocess
import threading
import logging
from datetime import datetime
from pathlib import Path
from functools import wraps
from flask import Flask, render_template, request, jsonify, send_from_directory, redirect, url_for, session
import bcrypt
from flask_wtf.csrf import CSRFProtect
from werkzeug.utils import secure_filename
import tempfile
from PIL import Image, ImageOps
from apscheduler.schedulers.background import BackgroundScheduler
import imagehash
from render_display import (
render_snapshot as _render_snapshot,
render_group_snapshot as _render_group_snapshot,
delete_snapshot as _delete_snapshot,
delete_group_snapshot as _delete_group_snapshot,
get_groups_containing,
backfill_snapshots as _backfill_snapshots,
regenerate_all_snapshots as _regenerate_all_snapshots,
)
app = Flask(__name__)
csrf = CSRFProtect(app)
# Configuration
UPLOAD_FOLDER = Path(__file__).parent / 'uploads'
DATA_FOLDER = Path(__file__).parent / 'data'
SETTINGS_FILE = DATA_FOLDER / 'settings.json'
USERS_FILE = DATA_FOLDER / 'users.json'
GALLERY_FILE = DATA_FOLDER / 'gallery.json'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp'}
THUMBNAIL_FOLDER = UPLOAD_FOLDER / 'thumbnails'
THUMBNAIL_MAX_SIZE = (400, 400)
RCLONE_CONFIG_DIR = DATA_FOLDER / 'rclone'
RCLONE_CONFIG_FILE = RCLONE_CONFIG_DIR / 'rclone.conf'
BACKUP_LOG_FILE = DATA_FOLDER / 'backup_log.json'
BACKUP_LOCK_FILE = DATA_FOLDER / '.backup.lock'
SNAPSHOT_FOLDER = DATA_FOLDER / 'display_snapshots'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 # 50MB max upload
# Ensure folders exist
UPLOAD_FOLDER.mkdir(exist_ok=True)
THUMBNAIL_FOLDER.mkdir(exist_ok=True)
DATA_FOLDER.mkdir(exist_ok=True)
SNAPSHOT_FOLDER.mkdir(exist_ok=True)
# Generate a secret key for sessions (persisted so sessions survive restarts)
SECRET_KEY_FILE = DATA_FOLDER / '.secret_key'
if SECRET_KEY_FILE.exists():
app.secret_key = SECRET_KEY_FILE.read_text().strip()
else:
app.secret_key = secrets.token_hex(32)
SECRET_KEY_FILE.write_text(app.secret_key)
os.chmod(SECRET_KEY_FILE, 0o600)
# Display token for kiosk mode
DISPLAY_TOKEN_FILE = DATA_FOLDER / '.display_token'
if DISPLAY_TOKEN_FILE.exists():
DISPLAY_TOKEN = DISPLAY_TOKEN_FILE.read_text().strip()
else:
DISPLAY_TOKEN = secrets.token_urlsafe(32)
DISPLAY_TOKEN_FILE.write_text(DISPLAY_TOKEN)
try:
os.chmod(DISPLAY_TOKEN_FILE, 0o600)
except OSError:
pass
# Session cookie security
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
# Enable Secure flag when behind HTTPS (set env var SECURE_COOKIES=1)
if os.environ.get('SECURE_COOKIES', '').lower() in ('1', 'true'):
app.config['SESSION_COOKIE_SECURE'] = True
# Reverse proxy support — enable with BEHIND_PROXY=1
if os.environ.get('BEHIND_PROXY', '').lower() in ('1', 'true'):
from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)
# ============ User Management ============
def hash_password(password: str, salt: str = None) -> tuple:
"""Hash a password using bcrypt.
The salt parameter is accepted for backwards compatibility with legacy
SHA-256 hashes but is ignored for new bcrypt hashes.
"""
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
return hashed, None
def _verify_legacy_sha256(password: str, stored_hash: str, salt: str) -> bool:
"""Verify a password against a legacy salted SHA-256 hash."""
candidate = hashlib.sha256((salt + password).encode()).hexdigest()
return secrets.compare_digest(candidate, stored_hash)
def _is_bcrypt_hash(stored_hash: str) -> bool:
"""Check if a stored hash is in bcrypt format."""
return stored_hash.startswith('$2b$') or stored_hash.startswith('$2a$')
def load_users():
"""Load users from JSON file, create default admin if none exist"""
if USERS_FILE.exists():
with open(USERS_FILE, 'r') as f:
return json.load(f)
# Create default admin user
hashed, salt = hash_password('password')
users = {
'admin': {
'password_hash': hashed,
'salt': salt,
'role': 'admin',
'created': datetime.now().isoformat()
}
}
save_users(users)
return users
def save_users(users):
"""Save users to JSON file"""
with open(USERS_FILE, 'w') as f:
json.dump(users, f, indent=2)
os.chmod(USERS_FILE, 0o600)
def verify_user(username: str, password: str) -> bool:
"""Verify username and password, auto-migrating legacy SHA-256 hashes to bcrypt."""
users = load_users()
if username not in users:
return False
user = users[username]
if _is_bcrypt_hash(user['password_hash']):
if not bcrypt.checkpw(password.encode(), user['password_hash'].encode()):
return False
else:
# Legacy salted SHA-256
if not _verify_legacy_sha256(password, user['password_hash'], user.get('salt', '')):
return False
# Auto-migrate to bcrypt on successful login
new_hash, _ = hash_password(password)
user['password_hash'] = new_hash
user['salt'] = None
save_users(users)
return True
def has_default_password(username):
"""Check if user still has the default password."""
users = load_users()
if username not in users:
return False
user = users[username]
if _is_bcrypt_hash(user['password_hash']):
return bcrypt.checkpw(b'password', user['password_hash'].encode())
return _verify_legacy_sha256('password', user['password_hash'], user.get('salt', ''))
def get_user_role(username: str) -> str:
"""Get user's role"""
users = load_users()
if username in users:
return users[username].get('role', 'user')
return None
def create_user(username: str, password: str, role: str = 'user') -> tuple:
"""Create a new user. Returns (success, message)"""
users = load_users()
if username in users:
return False, 'Username already exists'
if len(username) < 3:
return False, 'Username must be at least 3 characters'
if len(password) < 4:
return False, 'Password must be at least 4 characters'
if role not in ['admin', 'user']:
return False, 'Invalid role'
hashed, salt = hash_password(password)
users[username] = {
'password_hash': hashed,
'salt': salt,
'role': role,
'created': datetime.now().isoformat()
}
save_users(users)
return True, 'User created successfully'
def delete_user(username: str) -> tuple:
"""Delete a user. Returns (success, message)"""
users = load_users()
if username not in users:
return False, 'User not found'
if username == 'admin':
return False, 'Cannot delete the admin user'
del users[username]
save_users(users)
return True, 'User deleted successfully'
def change_user_password(username: str, new_password: str) -> tuple:
"""Change a user's password. Returns (success, message)"""
users = load_users()
if username not in users:
return False, 'User not found'
if len(new_password) < 4:
return False, 'Password must be at least 4 characters'
hashed, salt = hash_password(new_password)
users[username]['password_hash'] = hashed
users[username]['salt'] = salt
save_users(users)
return True, 'Password changed successfully'
# ============ Authentication Decorators ============
def is_authenticated():
"""Check if current session is authenticated"""
return session.get('authenticated', False)
def is_admin():
"""Check if current user is admin"""
if not is_authenticated():
return False
username = session.get('username')
return get_user_role(username) == 'admin'
def login_required(f):
"""Decorator to require authentication"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not is_authenticated():
return redirect(url_for('login'))
if has_default_password(session.get('username')) and request.path != '/change-password':
return redirect(url_for('change_password', forced=1))
return f(*args, **kwargs)
return decorated_function
def admin_required(f):
"""Decorator to require admin role"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not is_authenticated():
return redirect(url_for('login'))
if not is_admin():
return render_template('error.html', message='Admin access required'), 403
return f(*args, **kwargs)
return decorated_function
def api_login_required(f):
"""Decorator for API endpoints - returns 401 instead of redirect"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not is_authenticated():
return jsonify({'error': 'Authentication required'}), 401
return f(*args, **kwargs)
return decorated_function
def api_admin_required(f):
"""Decorator for admin API endpoints"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not is_authenticated():
return jsonify({'error': 'Authentication required'}), 401
if not is_admin():
return jsonify({'error': 'Admin access required'}), 403
return f(*args, **kwargs)
return decorated_function
# ============ Gallery Management ============
def load_gallery():
"""Load gallery metadata"""
if GALLERY_FILE.exists():
with open(GALLERY_FILE, 'r') as f:
data = json.load(f)
if 'groups' not in data:
data['groups'] = {}
return data
return {'images': {}, 'groups': {}}
def save_gallery(gallery):
"""Save gallery metadata"""
with open(GALLERY_FILE, 'w') as f:
json.dump(gallery, f, indent=2)
def get_image_metadata(filename):
"""Get metadata for a single image"""
gallery = load_gallery()
return gallery['images'].get(filename, {
'enabled': True,
'title': '',
'uploaded_at': None,
'uploaded_by': None,
'width': None,
'height': None,
'mat_color': None,
'phash': None,
'scale': 1.0,
'mat_finish': None,
'bevel_width': None,
'border_effect': None,
'crop': None
})
def update_image_metadata(filename, **kwargs):
"""Update metadata for an image"""
gallery = load_gallery()
if filename not in gallery['images']:
gallery['images'][filename] = {
'enabled': True,
'title': '',
'uploaded_at': None,
'uploaded_by': None,
'width': None,
'height': None,
'mat_color': None,
'phash': None,
'scale': 1.0,
'mat_finish': None,
'bevel_width': None,
'border_effect': None,
'crop': None
}
gallery['images'][filename].update(kwargs)
save_gallery(gallery)
def remove_image_metadata(filename):
"""Remove metadata for an image"""
gallery = load_gallery()
if filename in gallery['images']:
del gallery['images'][filename]
save_gallery(gallery)
def get_grouped_filenames():
"""Get set of all filenames that belong to a group"""
gallery = load_gallery()
grouped = set()
for group in gallery['groups'].values():
grouped.update(group.get('images', []))
return grouped
def remove_filename_from_groups(filename):
"""Remove a filename from any groups it belongs to, delete empty groups"""
gallery = load_gallery()
groups_to_delete = []
for group_id, group in gallery['groups'].items():
if filename in group.get('images', []):
group['images'].remove(filename)
if len(group['images']) < 2:
groups_to_delete.append(group_id)
for gid in groups_to_delete:
del gallery['groups'][gid]
if groups_to_delete or any(filename in g.get('images', []) for g in gallery['groups'].values()):
save_gallery(gallery)
def allowed_file(filename):
"""Check if file extension is allowed"""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def compute_phash(filepath):
"""Compute perceptual hash of an image file. Returns hex string or None."""
try:
with Image.open(filepath) as img:
oriented = ImageOps.exif_transpose(img)
return str(imagehash.phash(oriented))
except Exception:
return None
def generate_thumbnail(filepath, filename):
"""Generate a thumbnail for an image. Returns True on success."""
thumb_path = THUMBNAIL_FOLDER / filename
if thumb_path.exists():
return True
try:
with Image.open(filepath) as img:
oriented = ImageOps.exif_transpose(img)
oriented.thumbnail(THUMBNAIL_MAX_SIZE, Image.Resampling.LANCZOS)
# Save as JPEG for smaller file size (unless PNG with transparency)
if oriented.mode in ('RGBA', 'LA', 'P'):
# PNG doesn't accept quality param; use optimize for smaller size
oriented.save(thumb_path, 'PNG', optimize=True)
else:
thumb_path = thumb_path.with_suffix('.jpg')
oriented = oriented.convert('RGB')
oriented.save(thumb_path, 'JPEG', quality=85)
return True
except Exception:
return False
def backfill_thumbnails():
"""Generate thumbnails for any uploaded images missing them."""
if not UPLOAD_FOLDER.exists():
return 0
count = 0
for f in UPLOAD_FOLDER.iterdir():
if f.is_file() and allowed_file(f.name):
# Check both original extension and .jpg fallback
thumb_path = THUMBNAIL_FOLDER / f.name
thumb_jpg = thumb_path.with_suffix('.jpg')
if not thumb_path.exists() and not thumb_jpg.exists():
if generate_thumbnail(f, f.name):
count += 1
return count
def generate_display_snapshot(filename):
"""Generate a display snapshot for a single image."""
try:
gallery = load_gallery()
settings = load_settings()
return _render_snapshot(filename, gallery, settings, UPLOAD_FOLDER, SNAPSHOT_FOLDER)
except Exception as e:
logging.warning('Snapshot render failed for %s: %s', filename, e)
return None
def generate_group_display_snapshot(group_id):
"""Generate a display snapshot for a group."""
try:
gallery = load_gallery()
settings = load_settings()
return _render_group_snapshot(group_id, gallery, settings, UPLOAD_FOLDER, SNAPSHOT_FOLDER)
except Exception as e:
logging.warning('Group snapshot render failed for %s: %s', group_id, e)
return None
def regenerate_snapshots_for_groups_containing(filename):
"""Re-render snapshots for all groups that contain the given image."""
gallery = load_gallery()
for group_id in get_groups_containing(filename, gallery):
generate_group_display_snapshot(group_id)
def get_uploaded_images():
"""Get list of all uploaded images with metadata"""
if not UPLOAD_FOLDER.exists():
return []
gallery = load_gallery()
images = []
for f in sorted(UPLOAD_FOLDER.iterdir()):
if f.is_file() and allowed_file(f.name):
meta = gallery['images'].get(f.name, {
'enabled': True,
'title': '',
'uploaded_at': None,
'uploaded_by': None,
'width': None,
'height': None,
'mat_color': None,
'phash': None,
'scale': 1.0,
'mat_finish': None,
'bevel_width': None,
'border_effect': None,
'crop': None
})
images.append({
'filename': f.name,
'size': f.stat().st_size,
'modified': datetime.fromtimestamp(f.stat().st_mtime).isoformat(),
**meta
})
return images
def get_enabled_images():
"""Get list of enabled images only (for display)"""
return [img for img in get_uploaded_images() if img.get('enabled', True)]
# ============ Settings ============
DEFAULT_SETTINGS = {
'mat_color': '#ffffff',
'mat_finish': 'eggshell',
'bevel_width': 4,
'border_effect': 'bevel',
'slideshow_interval': 60,
'transition_duration': 1,
'fit_mode': 'contain',
'shuffle': False,
'image_order': [],
'target_aspect_ratio': '16:9',
'tv_schedules': []
}
def load_settings():
"""Load settings from JSON file"""
if SETTINGS_FILE.exists():
with open(SETTINGS_FILE, 'r') as f:
settings = json.load(f)
return {**DEFAULT_SETTINGS, **settings}
return DEFAULT_SETTINGS.copy()
def save_settings(settings):
"""Save settings to JSON file"""
with open(SETTINGS_FILE, 'w') as f:
json.dump(settings, f, indent=2)
# ============ Display State (server-controlled slideshow) ============
_display_state = {
'index': 0,
'paused': False,
'last_advanced_at': time.time(),
}
def _get_effective_index(total_slides):
"""Compute current slide index with lazy auto-advance."""
if total_slides == 0:
return 0
state = _display_state
if state['paused'] or total_slides <= 1:
return state['index'] % total_slides
settings = load_settings()
interval = settings.get('slideshow_interval', 10)
elapsed = time.time() - state['last_advanced_at']
advances = int(elapsed / interval)
return (state['index'] + advances) % total_slides
# ============ Backup Management ============
backup_lock = threading.Lock()
backup_in_progress = False
def load_backup_log():
"""Load backup log from JSON file"""
if BACKUP_LOG_FILE.exists():
with open(BACKUP_LOG_FILE, 'r') as f:
return json.load(f)
return {'last_backup': None, 'last_result': None, 'last_error': None, 'history': []}
def save_backup_log(log_data):
"""Save backup log to JSON file"""
# Keep only last 30 history entries
if len(log_data.get('history', [])) > 30:
log_data['history'] = log_data['history'][-30:]
with open(BACKUP_LOG_FILE, 'w') as f:
json.dump(log_data, f, indent=2)
def is_backup_configured():
"""Check if rclone is configured for Dropbox"""
if not RCLONE_CONFIG_FILE.exists():
return False
content = RCLONE_CONFIG_FILE.read_text()
return '[dropbox]' in content
def generate_rclone_config(token):
"""Generate rclone.conf for Dropbox with the given token"""
RCLONE_CONFIG_DIR.mkdir(parents=True, exist_ok=True)
config_content = f"""[dropbox]
type = dropbox
token = {token}
"""
RCLONE_CONFIG_FILE.write_text(config_content)
os.chmod(RCLONE_CONFIG_FILE, 0o600)
def get_backup_settings():
"""Get backup-specific settings"""
settings = load_settings()
return {
'backup_time': settings.get('backup_time', os.environ.get('BACKUP_TIME', '03:00')),
'backup_path': settings.get('backup_path', 'PhotoFrameBackup')
}
def run_backup():
"""Run rclone backup to Dropbox"""
global backup_in_progress
if not is_backup_configured():
return {'success': False, 'error': 'Backup not configured'}
# File-based lock to prevent concurrent runs across workers
try:
lock_fd = open(BACKUP_LOCK_FILE, 'w')
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except (IOError, OSError):
return {'success': False, 'error': 'Backup already in progress'}
backup_in_progress = True
start_time = datetime.now()
log = load_backup_log()
try:
backup_settings = get_backup_settings()
remote_path = backup_settings['backup_path']
config = str(RCLONE_CONFIG_FILE)
# Sync uploads
result1 = subprocess.run(
['rclone', 'sync', str(UPLOAD_FOLDER), f'dropbox:{remote_path}/uploads',
'--config', config],
capture_output=True, text=True, timeout=3600
)
# Sync data (excluding secrets, credentials, and lock files)
result2 = subprocess.run(
['rclone', 'sync', str(DATA_FOLDER), f'dropbox:{remote_path}/data',
'--config', config,
'--exclude', 'rclone/**',
'--exclude', '.backup.lock',
'--exclude', '.secret_key',
'--exclude', '.display_token',
'--exclude', 'users.json'],
capture_output=True, text=True, timeout=3600
)
duration = (datetime.now() - start_time).total_seconds()
if result1.returncode != 0 or result2.returncode != 0:
error_msg = (result1.stderr or '') + (result2.stderr or '')
error_msg = error_msg.strip()[:500]
log['last_backup'] = start_time.isoformat()
log['last_result'] = 'error'
log['last_error'] = error_msg
log['history'].append({
'timestamp': start_time.isoformat(),
'result': 'error',
'error': error_msg,
'duration_seconds': round(duration, 1)
})
save_backup_log(log)
return {'success': False, 'error': error_msg}
log['last_backup'] = start_time.isoformat()
log['last_result'] = 'success'
log['last_error'] = None
log['history'].append({
'timestamp': start_time.isoformat(),
'result': 'success',
'duration_seconds': round(duration, 1)
})
save_backup_log(log)
return {'success': True, 'duration_seconds': round(duration, 1)}
except subprocess.TimeoutExpired:
log['last_backup'] = start_time.isoformat()
log['last_result'] = 'error'
log['last_error'] = 'Backup timed out after 1 hour'
log['history'].append({
'timestamp': start_time.isoformat(),
'result': 'error',
'error': 'Backup timed out after 1 hour'
})
save_backup_log(log)
return {'success': False, 'error': 'Backup timed out'}
except Exception as e:
error_msg = str(e)[:500]
log['last_backup'] = start_time.isoformat()
log['last_result'] = 'error'
log['last_error'] = error_msg
log['history'].append({
'timestamp': start_time.isoformat(),
'result': 'error',
'error': error_msg
})
save_backup_log(log)
return {'success': False, 'error': error_msg}
finally:
backup_in_progress = False
try:
fcntl.flock(lock_fd, fcntl.LOCK_UN)
lock_fd.close()
except Exception:
pass
def run_backup_async():
"""Run backup in a background thread"""
thread = threading.Thread(target=run_backup, daemon=True)
thread.start()
restore_in_progress = False
def run_restore():
"""Restore photos and data from Dropbox backup"""
global restore_in_progress
if not is_backup_configured():
return {'success': False, 'error': 'Backup not configured'}
# Reuse the same file lock to prevent backup and restore from running concurrently
try:
lock_fd = open(BACKUP_LOCK_FILE, 'w')
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except (IOError, OSError):
return {'success': False, 'error': 'A backup or restore is already in progress'}
restore_in_progress = True
start_time = datetime.now()
try:
backup_settings = get_backup_settings()
remote_path = backup_settings['backup_path']
config = str(RCLONE_CONFIG_FILE)
# Restore uploads (use copy so we don't delete local files missing from remote)
result1 = subprocess.run(
['rclone', 'copy', f'dropbox:{remote_path}/uploads', str(UPLOAD_FOLDER),
'--config', config],
capture_output=True, text=True, timeout=3600
)
# Restore data (excluding rclone config, lock file, secret key, and users)
result2 = subprocess.run(
['rclone', 'copy', f'dropbox:{remote_path}/data', str(DATA_FOLDER),
'--config', config,
'--exclude', 'rclone/**',
'--exclude', '.backup.lock',
'--exclude', '.secret_key',
'--exclude', 'users.json'],
capture_output=True, text=True, timeout=3600
)
duration = (datetime.now() - start_time).total_seconds()
if result1.returncode != 0 or result2.returncode != 0:
error_msg = (result1.stderr or '') + (result2.stderr or '')
return {'success': False, 'error': error_msg.strip()[:500]}
return {'success': True, 'duration_seconds': round(duration, 1)}
except subprocess.TimeoutExpired:
return {'success': False, 'error': 'Restore timed out after 1 hour'}
except Exception as e:
return {'success': False, 'error': str(e)[:500]}
finally:
restore_in_progress = False
try:
fcntl.flock(lock_fd, fcntl.LOCK_UN)
lock_fd.close()
except Exception:
pass
def run_restore_async():
"""Run restore in a background thread"""
thread = threading.Thread(target=run_restore, daemon=True)
thread.start()
# ============ Backup Scheduler ============
scheduler = BackgroundScheduler(daemon=True)
def init_scheduler():
"""Initialize the daily backup scheduler"""
backup_settings = get_backup_settings()
backup_time = backup_settings['backup_time']
try:
hour, minute = map(int, backup_time.split(':'))
except ValueError:
hour, minute = 3, 0
scheduler.add_job(
run_backup,
'cron',
hour=hour,
minute=minute,
id='daily_backup',
replace_existing=True,
misfire_grace_time=3600
)
if not scheduler.running:
scheduler.start()
def reschedule_backup(time_str):
"""Reschedule the daily backup to a new time"""
try:
hour, minute = map(int, time_str.split(':'))
except ValueError:
return
if scheduler.get_job('daily_backup'):
scheduler.reschedule_job(
'daily_backup',
trigger='cron',
hour=hour,
minute=minute
)
# Start scheduler on module load
init_scheduler()
# ============ CEC TV Control ============
# In split backend/display mode, cec-ctl is not available on the server.
# Commands are queued here and picked up by the cec-agent running on the Pi.
_cec_queue = [] # pending commands waiting for a remote display to execute
_cec_display_has_cec = False # True once a CEC-capable display has registered
def is_cec_available():
"""Check if CEC control is available — either locally or via a registered remote display."""
if _cec_display_has_cec:
return True
try:
result = subprocess.run(
['cec-ctl', '-d0', '--phys-addr'],
capture_output=True, text=True, timeout=5
)
return result.returncode == 0
except (FileNotFoundError, subprocess.TimeoutExpired):
return False
def cec_send_command(command):
"""Send a CEC command. Runs locally if cec-ctl is available, otherwise queues
for a remote display running the cec-agent (split backend/display mode)."""
cec_args = {
'on': ['cec-ctl', '-d0', '--playback', '--image-view-on'],
'standby': ['cec-ctl', '-d0', '--playback', '--standby'],
}
if command not in cec_args:
return {'success': False, 'error': f'Unknown command: {command}'}
try:
result = subprocess.run(
cec_args[command], capture_output=True, text=True, timeout=10
)
return {'success': result.returncode == 0,
'error': result.stderr.strip()[:200] if result.returncode != 0 else None}
except FileNotFoundError:
pass # no local cec-ctl — fall through to queue
except subprocess.TimeoutExpired:
return {'success': False, 'error': 'CEC command timed out'}
# No local cec-ctl available — queue for remote display agent
_cec_queue.append(command)
return {'success': True, 'queued': True}
def schedule_cec_jobs():
"""(Re-)schedule all CEC on/off jobs from settings."""
for job in scheduler.get_jobs():
if job.id.startswith('cec_'):
scheduler.remove_job(job.id)
settings = load_settings()
for sched in settings.get('tv_schedules', []):
if not sched.get('enabled', True):
continue
sched_id = sched.get('id', '')
days = sched.get('days', [])
if not days:
continue
day_of_week = ','.join(str(d) for d in sorted(days))
on_h, on_m = map(int, sched['on_time'].split(':'))
scheduler.add_job(
cec_send_command, 'cron',
args=['on'],
day_of_week=day_of_week,
hour=on_h, minute=on_m,
id=f'cec_{sched_id}_on',
replace_existing=True,
misfire_grace_time=300
)
off_h, off_m = map(int, sched['off_time'].split(':'))
scheduler.add_job(
cec_send_command, 'cron',
args=['standby'],
day_of_week=day_of_week,
hour=off_h, minute=off_m,
id=f'cec_{sched_id}_off',
replace_existing=True,
misfire_grace_time=300
)
schedule_cec_jobs()
# ============ Routes ============
# --- Authentication Routes ---
@app.route('/login', methods=['GET', 'POST'])
def login():
"""Login page"""
if is_authenticated():
return redirect(url_for('upload_page'))
if request.method == 'POST':
username = request.form.get('username', '').strip().lower()
password = request.form.get('password', '')
if verify_user(username, password):
session['authenticated'] = True
session['username'] = username
session.permanent = True
if has_default_password(username):
return redirect(url_for('change_password', forced=1))
return redirect(url_for('upload_page'))
return render_template('login.html', error='Invalid username or password')
return render_template('login.html')
@app.route('/logout')
def logout():
"""Logout and clear session"""
session.clear()
return redirect(url_for('login'))
@app.route('/change-password', methods=['GET', 'POST'])
@login_required
def change_password():
"""Change own password"""
forced = request.args.get('forced') == '1'
username = session.get('username')
if request.method == 'POST':
forced = request.form.get('forced') == '1'