-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
790 lines (694 loc) · 28.3 KB
/
Copy pathapp.py
File metadata and controls
790 lines (694 loc) · 28.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
from flask import Flask, render_template, request, redirect, url_for, flash, send_from_directory, jsonify, Response
import os
from werkzeug.utils import secure_filename
from pathlib import Path
import sys
from flask_sqlalchemy import SQLAlchemy
from utils.crop_image import crop_image_file, CropImageError, get_preset_crop_box, CROP_PRESETS
from samsungtvws.exceptions import HttpApiError, ResponseError
from const import CONNECTION_NAME
from typing import Tuple, Optional
from datetime import datetime
from flask_migrate import Migrate
import importlib
from media_provider_routes import media_provider_routes
from provider_config_routes import provider_config_routes
try:
from PIL import Image as PILImage
except ImportError:
PILImage = None
# Load environment variables from .env if present
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
# Import TV control functions from the integration
REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
from utils.frame_tv import (
SamsungTVWS,
DEFAULT_PORT,
upload_artwork,
is_art_mode_on,
is_tv_reachable,
power_on,
power_off,
enable_art_mode,
FrameTVError,
FrameTVConnectionError,
FrameTVTimeoutError,
delete_all_images_from_tv,
get_tv_gallery_images,
delete_tv_image,
play_uploaded_content,
get_tv_gallery_thumbnail,
)
DATA_DIR = os.environ.get("FRAME_TV_DATA", "data")
UPLOAD_FOLDER = os.path.join(DATA_DIR, "uploads")
INSTANCE_FOLDER = os.path.join(DATA_DIR, "instance")
# Ensure directories exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(INSTANCE_FOLDER, exist_ok=True)
frametv_db_path = os.path.abspath(os.path.join(INSTANCE_FOLDER, 'frametv.db'))
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
app = Flask(__name__, static_folder="frontend/build/client")
app.secret_key = os.environ.get('SECRET_KEY', 'frameartsecretkey')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = int(os.environ.get('MAX_UPLOAD_SIZE_BYTES', str(20 * 1024 * 1024)))
# allow cross-origin requests from the dev server or any other origin when
# talking to the API directly. This is useful during front-end development when the frontend runs on a different port/host.
try:
from flask_cors import CORS
CORS(app, resources={r"/api/*": {"origins": "*"}})
except ImportError:
pass
# Fallback CORS headers for any route, so front-end dev or production can call /api and /uploads without CORS blocking.
@app.after_request
def add_cors_headers(response):
response.headers.setdefault('Access-Control-Allow-Origin', '*')
response.headers.setdefault('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.setdefault('Access-Control-Allow-Methods', 'GET,HEAD,POST,OPTIONS,PUT,PATCH,DELETE')
# Basic browser hardening headers to reduce XSS and related client-side risks.
response.headers.setdefault('X-Content-Type-Options', 'nosniff')
response.headers.setdefault('X-Frame-Options', 'DENY')
response.headers.setdefault('Referrer-Policy', 'strict-origin-when-cross-origin')
return response
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{frametv_db_path}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
from models import db, Album, Image, TV, UploadedImage, ProviderConfig
db.init_app(app)
# Import blueprints
app.register_blueprint(media_provider_routes)
app.register_blueprint(provider_config_routes)
# ...models are now imported from models.py...
# Create database
def init_db():
"""Ensure database and all tables exist."""
with app.app_context():
app.logger.info("Initializing database")
db.create_all()
app.logger.info("Database initialized")
# Initialize database on startup
init_db()
migrate = Migrate(app, db)
# --- Helpers ---
def allowed_file(filename: str) -> bool:
return isinstance(filename, str) and '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
UPLOAD_ROOT = Path(app.config['UPLOAD_FOLDER']).resolve()
STATIC_ROOT = Path(app.static_folder).resolve() if app.static_folder else None
def _log_exception(context: str, exc: Exception):
app.logger.error("%s: %s", context, exc, exc_info=True)
def _error_response(public_message: str, status_code: int = 500):
return {'error': public_message}, status_code
def _normalized_upload_path(filename: str, must_exist: bool = False) -> Tuple[str, str]:
if not filename or not isinstance(filename, str):
raise ValueError('Invalid filename')
normalized_name = secure_filename(filename)
if not normalized_name or normalized_name != os.path.basename(normalized_name):
raise ValueError('Invalid filename')
if not allowed_file(normalized_name):
raise ValueError('Invalid file type')
candidate = (UPLOAD_ROOT / normalized_name).resolve()
if candidate.parent != UPLOAD_ROOT:
raise ValueError('Invalid filename')
if must_exist and not candidate.is_file():
raise FileNotFoundError('Image not found')
return normalized_name, str(candidate)
def _normalized_static_path(path: str) -> Path:
if STATIC_ROOT is None:
raise ValueError('Static path not configured')
normalized = (STATIC_ROOT / path).resolve()
# Ensure the resulting path is the static root or contained within it
if not (normalized == STATIC_ROOT or STATIC_ROOT in normalized.parents):
raise ValueError('Invalid path')
return normalized
def _guess_image_mimetype(image_bytes: bytes) -> str:
if image_bytes.startswith(b'\xff\xd8\xff'):
return 'image/jpeg'
if image_bytes.startswith(b'\x89PNG\r\n\x1a\n'):
return 'image/png'
if image_bytes.startswith(b'GIF87a') or image_bytes.startswith(b'GIF89a'):
return 'image/gif'
if image_bytes.startswith(b'RIFF') and image_bytes[8:12] == b'WEBP':
return 'image/webp'
return 'application/octet-stream'
# --- Media Provider Integration ---
media_provider = None
def load_media_provider():
global media_provider
with app.app_context():
config = ProviderConfig.query.filter_by(provider='immich', enabled=True).first()
if config and config.api_key and config.host:
try:
ImmichProvider = importlib.import_module("utils.immich_provider").ImmichProvider
port = config.port or 443
media_provider = ImmichProvider(config.api_key, config.host, port)
app.logger.info("Loaded Immich provider from DB config")
except Exception as e:
app.logger.exception("Failed to initialize Immich provider")
else:
media_provider = None
# Load provider at startup
load_media_provider()
app.media_provider = media_provider
# --- API Endpoints ---
# List all uploaded images (not album-specific)
@app.route('/api/images', methods=['GET'])
def api_list_images():
files = [f for f in os.listdir(app.config['UPLOAD_FOLDER']) if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], f))]
return {'images': files}
@app.route('/api/images/added_this_month', methods=['GET'])
def api_images_added_this_month():
now = datetime.now()
start_of_month = datetime(now.year, now.month, 1)
count = Image.query.filter(Image.created_at >= start_of_month).count()
return {'count': count}
@app.route('/api/images/<filename>', methods=['DELETE'])
def api_delete_image(filename):
try:
filename, file_path = _normalized_upload_path(filename)
except ValueError:
return {'error': 'Invalid filename'}, 400
image = Image.query.filter_by(filename=filename).first()
if not image:
return {'error': 'Image not found'}, 404
try:
if os.path.exists(file_path):
os.remove(file_path)
except Exception as e:
_log_exception(f"Failed to delete file {file_path}", e)
UploadedImage.query.filter_by(image_id=image.id).delete()
db.session.delete(image)
db.session.commit()
return {'success': True}
@app.route('/api/images/<filename>/crop', methods=['POST'])
def api_crop_image(filename):
"""Crop an image using direct coordinates or a preset.
Accepts one of:
- Direct crop: {x, y, width, height}
- Preset crop: {preset: "640x480"}
"""
# Get crop parameters from request
data = request.get_json(silent=True) or {}
try:
_, image_path = _normalized_upload_path(filename, must_exist=True)
except ValueError:
return {'error': 'Invalid filename'}, 400
except FileNotFoundError:
return {'error': 'Image not found'}, 404
try:
# Check if using preset-based crop
if 'preset' in data:
preset_name = data.get('preset')
x, y, width, height = get_preset_crop_box(image_path, preset_name)
else:
# Use direct coordinates
x = data.get('x')
y = data.get('y')
width = data.get('width')
height = data.get('height')
# Perform the crop
crop_image_file(image_path, x, y, width, height)
return {'success': True}
except FileNotFoundError:
return {'error': 'Image not found'}, 404
except ValueError as e:
return {'error': str(e)}, 400
except CropImageError as e:
return {'error': str(e)}, 400
except Exception as e:
_log_exception('Failed to crop image', e)
return _error_response('Failed to crop image', 500)
@app.route('/api/crop-presets', methods=['GET'])
def api_get_crop_presets():
"""Get available crop presets."""
presets = [
{'id': name, 'label': info['label'], 'width': info['width'], 'height': info['height']}
for name, info in CROP_PRESETS.items()
]
return {'presets': presets}
# Album API
@app.route('/api/albums', methods=['GET'])
def api_list_albums():
albums = Album.query.all()
result = []
for album in albums:
result.append({
'id': album.id,
'name': album.name,
'images': [img.filename for img in album.images]
})
return {'albums': result}
@app.route('/api/albums', methods=['POST'])
def api_create_album():
data = request.get_json()
name = data.get('name', '').strip()
if not name:
return {'error': 'Album name required'}, 400
if Album.query.filter_by(name=name).first():
return {'error': 'Album already exists'}, 400
album = Album(name=name)
db.session.add(album)
db.session.commit()
return api_list_albums()
@app.route('/api/albums/<album_name>/add', methods=['POST'])
def api_add_image_to_album(album_name):
data = request.get_json()
image_filename = data.get('image')
if not image_filename:
return {'error': 'Image required'}, 400
album = Album.query.filter_by(name=album_name).first()
if not album:
return {'error': 'Album not found'}, 404
existing_image = Image.query.filter_by(filename=image_filename).first()
if existing_image and existing_image.album_id == album.id:
return api_list_albums()
if existing_image:
existing_image.album = album
else:
existing_image = Image(filename=image_filename, album=album)
db.session.add(existing_image)
db.session.commit()
return api_list_albums()
@app.route('/api/albums/<int:album_id>', methods=['GET'])
def api_get_album(album_id):
album = Album.query.get(album_id)
if not album:
return {'error': 'Album not found'}, 404
return {
'album': {
'id': album.id,
'name': album.name,
'images': [
{
'id': img.id,
'filename': img.filename
} for img in album.images
]
}
}
@app.route('/api/albums/<int:album_id>/images/<int:image_id>', methods=['DELETE'])
def api_remove_image_from_album(album_id, image_id):
album = Album.query.get(album_id)
if not album:
return {'error': 'Album not found'}, 404
image = Image.query.get(image_id)
if not image or image.album_id != album.id:
return {'error': 'Image not found in album'}, 404
image.album_id = None
db.session.commit()
return api_get_album(album_id)
@app.route('/api/albums/<album_name>', methods=['DELETE'])
def api_delete_album(album_name):
album = Album.query.filter_by(name=album_name).first()
if not album:
return {'error': 'Album not found'}, 404
db.session.delete(album)
db.session.commit()
return api_list_albums()
@app.route('/api/upload', methods=['POST'])
def upload():
""" Upload image to the gallery """
if 'file' not in request.files:
return {'error': 'No file part'}, 400
file = request.files['file']
if file.filename == '':
return {'error': 'No selected file'}, 400
if file and allowed_file(file.filename):
try:
filename, file_path = _normalized_upload_path(file.filename)
except ValueError as e:
return {'error': str(e)}, 400
file.save(file_path)
# Track image in DB
img = Image(filename=filename, album_id=None)
db.session.add(img)
db.session.commit()
return {'success': True, 'filename': filename}
else:
return {'error': 'Invalid file type'}, 400
# --- Play Uploaded Image on TV ---
@app.route('/api/tv/play_uploaded', methods=['POST'])
def api_play_uploaded_image():
"""
Play an image on a TV using the stored content_id, without re-uploading.
Expects JSON: {"ip": ..., "filename": ...}
"""
data = request.get_json()
ip = data.get('ip')
filename = data.get('filename')
if not ip or not filename:
return {'error': 'TV IP and filename required'}, 400
tv = TV.query.filter_by(ip=ip).first()
image = Image.query.filter_by(filename=filename).first()
if not tv or not image:
return {'error': 'TV or image not found'}, 404
uploaded = UploadedImage.query.filter_by(tv_id=tv.id, image_id=image.id).first()
if not uploaded:
return {'error': 'Image not uploaded to this TV'}, 404
content_id = uploaded.content_id
token = tv.token if tv else None
try:
# Use frame_tv API to play by content_id (assume function exists)
from utils.frame_tv import play_uploaded_content
play_uploaded_content(ip, content_id, token=token)
return {'success': True}
except FrameTVError as e:
_log_exception('Failed to play uploaded content', e)
return _error_response('Failed to play uploaded content', 500)
@app.route('/uploads/<filename>')
def uploaded_file(filename):
try:
safe_name, _ = _normalized_upload_path(filename, must_exist=True)
except ValueError:
return {'error': 'Invalid filename'}, 400
except FileNotFoundError:
return {'error': 'Image not found'}, 404
return send_from_directory(app.config['UPLOAD_FOLDER'], safe_name)
# --- TV API endpoints ---
from flask import jsonify
# TV management endpoints
@app.route('/api/tvs', methods=['GET'])
def api_get_tvs():
tvs = TV.query.all()
return {'tvs': [
{
'ip': tv.ip,
'name': tv.name,
'mac': tv.mac,
'delete_other_images_on_upload': getattr(tv, 'delete_other_images_on_upload', False)
} for tv in tvs
]}
@app.route('/api/tvs/<ip>', methods=['PATCH'])
def api_update_tv(ip):
tv = TV.query.filter_by(ip=ip).first()
if not tv:
return {'error': 'TV not found'}, 404
data = request.get_json()
if 'delete_other_images_on_upload' in data:
tv.delete_other_images_on_upload = bool(data['delete_other_images_on_upload'])
db.session.commit()
return {'success': True}
@app.route('/api/tvs', methods=['POST'])
def api_add_tv():
data = request.get_json()
if not data or not data.get('ip'):
return {'error': 'TV IP required'}, 400
ip = data['ip']
if TV.query.filter_by(ip=ip).first():
return {'error': 'TV already exists'}, 400
mac = data.get('mac')
name = data.get('name')
# Attempt to connect to TV and obtain token
try:
tvws = SamsungTVWS(host=ip, port=DEFAULT_PORT, name=CONNECTION_NAME)
tvws.open()
# Wait for pairing and token
token = tvws.token
tvws.close()
# Extract token string if needed
if isinstance(token, dict) and 'token' in token:
token = token['token']
elif hasattr(token, 'token'):
token = token.token
elif not isinstance(token, str):
token = str(token)
if not token or not isinstance(token, str) or not token.isdigit():
return {'error': 'Token not obtained or invalid. Please accept pairing on your TV.'}, 403
except FrameTVError as e:
_log_exception('Failed to connect to TV', e)
return _error_response('Failed to connect to TV', 500)
except Exception as e:
_log_exception('Unexpected error while adding TV', e)
return _error_response('Unexpected error while adding TV', 500)
tv = TV(ip=ip, name=name, mac=mac, token=token)
db.session.add(tv)
db.session.commit()
return api_get_tvs()
@app.route('/api/tvs', methods=['DELETE'])
def api_remove_tv():
data = request.get_json()
ip = data.get('ip')
if not ip:
return {'error': 'TV IP required'}, 400
tv = TV.query.filter_by(ip=ip).first()
if not tv:
return {'error': 'TV not found'}, 404
db.session.delete(tv)
db.session.commit()
return api_get_tvs()
@app.route('/api/tv/send', methods=['POST'])
def api_send_to_tv():
""" Upload an image to the TV """
data = request.get_json()
ip = data.get('ip')
filename = data.get('filename')
brightness = data.get('brightness')
display = data.get('display', True)
provider = data.get('provider')
provider_id = data.get('provider_id')
# provider_url is deprecated, but fallback if present
provider_url = data.get('provider_url')
if not ip or not filename:
return {'error': 'TV IP and filename required'}, 400
tv = TV.query.filter_by(ip=ip).first()
token = tv.token if tv else None
try:
filename, art_path = _normalized_upload_path(filename)
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# If the file does not exist locally, try to fetch from media provider
if not os.path.isfile(art_path) and (provider_id or provider_url):
if not hasattr(app, 'media_provider') or not app.media_provider:
return {'error': 'No media provider configured'}, 400
try:
# If provider is specified and is 'immich', use download_image_by_id
if provider == 'immich' and provider_id:
app.media_provider.download_image_by_id_sync(provider_id, art_path)
elif provider_url:
app.media_provider.download_image(provider_url, art_path)
elif provider_id:
# fallback for other providers
app.media_provider.download_image_by_id_sync(provider_id, art_path)
except Exception as e:
_log_exception('Failed to fetch image from provider', e)
return _error_response('Failed to fetch image from provider', 500)
# Check TV option for deleting other images on upload
delete_others = False
if tv and hasattr(tv, 'delete_other_images_on_upload'):
delete_others = bool(tv.delete_other_images_on_upload)
# upload_artwork should return content_id
content_id = upload_artwork(
ip, art_path, brightness=brightness, display=display, token=token, delete_others=delete_others
)
# Store UploadedImage record
image = Image.query.filter_by(filename=filename).first()
if image and tv and content_id:
from sqlalchemy import and_
exists = UploadedImage.query.filter(
and_(UploadedImage.image_id == image.id, UploadedImage.tv_id == tv.id)
).first()
if not exists:
uploaded = UploadedImage(image_id=image.id, tv_id=tv.id, content_id=str(content_id))
db.session.add(uploaded)
db.session.commit()
return jsonify({'success': True, 'content_id': content_id})
except (FrameTVError, HttpApiError) as e:
_log_exception('Failed to send artwork to TV', e)
return jsonify({'error': 'Failed to send artwork to TV'}), 500
except (ResponseError) as e:
_log_exception('TV rejected request while sending artwork', e)
return jsonify({'error': 'TV rejected the request'}), 400
except Exception as e:
_log_exception('Unexpected error while sending artwork to TV', e)
return jsonify({'error': 'Unexpected error'}), 500
@app.route("/api/tv/<ip>/images", methods=['DELETE'])
def api_remove_all_tv_images(ip):
tv = TV.query.filter_by(ip=ip).first()
if not tv:
return jsonify({'error': 'TV not found'}), 404
try:
delete_all_images_from_tv(ip, token=tv.token)
return jsonify({'success': True})
except Exception as e:
db.session.rollback()
_log_exception('Failed to remove all images from TV', e)
return jsonify({'error': 'Failed to remove all images from TV'}), 500
@app.route("/api/tv/<ip>/gallery", methods=['GET'])
def api_get_tv_gallery(ip):
"""Get list of images currently on the TV."""
tv = TV.query.filter_by(ip=ip).first()
if not tv:
return jsonify({'error': 'TV not found'}), 404
try:
images = get_tv_gallery_images(ip, token=tv.token)
return jsonify({'images': images, 'tv_ip': ip})
except FrameTVTimeoutError as e:
_log_exception('Timeout while fetching TV gallery', e)
return jsonify({'error': 'TV request timed out'}), 504
except FrameTVConnectionError as e:
_log_exception('TV gallery connection failed', e)
return jsonify({'error': 'TV is unavailable'}), 503
except Exception as e:
_log_exception('Failed to fetch TV gallery', e)
return jsonify({'error': 'Failed to fetch TV gallery'}), 500
@app.route("/api/tv/<ip>/gallery/<content_id>/play", methods=['POST'])
def api_play_tv_image(ip, content_id):
"""Play a specific image from the TV gallery."""
tv = TV.query.filter_by(ip=ip).first()
if not tv:
return jsonify({'error': 'TV not found'}), 404
try:
# Enable art mode first
enable_art_mode(ip, token=tv.token)
# Play the image
play_uploaded_content(ip, content_id, token=tv.token)
return jsonify({'success': True})
except FrameTVTimeoutError as e:
_log_exception('Timeout while playing TV image', e)
return jsonify({'error': 'TV request timed out'}), 504
except FrameTVConnectionError as e:
_log_exception('TV connection failed while playing image', e)
return jsonify({'error': 'TV is unavailable'}), 503
except FrameTVError as e:
_log_exception('Failed to play TV image', e)
return jsonify({'error': 'Failed to play image'}), 500
except Exception as e:
_log_exception('Unexpected error playing TV image', e)
return jsonify({'error': 'Unexpected error'}), 500
@app.route("/api/tv/<ip>/gallery/<content_id>/thumbnail", methods=['GET'])
def api_tv_gallery_thumbnail(ip, content_id):
"""Return a thumbnail image for a TV gallery item."""
tv = TV.query.filter_by(ip=ip).first()
if not tv:
return jsonify({'error': 'TV not found'}), 404
try:
thumbnail = get_tv_gallery_thumbnail(ip, content_id, token=tv.token)
if not thumbnail:
return jsonify({'error': 'Thumbnail not found'}), 404
return Response(thumbnail, mimetype=_guess_image_mimetype(thumbnail))
except FrameTVTimeoutError as e:
_log_exception('Timeout while fetching TV thumbnail', e)
return jsonify({'error': 'TV request timed out'}), 504
except FrameTVConnectionError as e:
_log_exception('TV connection failed while fetching thumbnail', e)
return jsonify({'error': 'TV is unavailable'}), 503
except Exception as e:
_log_exception('Failed to fetch TV thumbnail', e)
return jsonify({'error': 'Failed to fetch thumbnail'}), 500
@app.route("/api/tv/<ip>/gallery/<content_id>", methods=['DELETE'])
def api_delete_tv_image(ip, content_id):
"""Delete a specific image from the TV gallery."""
tv = TV.query.filter_by(ip=ip).first()
if not tv:
return jsonify({'error': 'TV not found'}), 404
try:
delete_tv_image(ip, content_id, token=tv.token)
return jsonify({'success': True})
except FrameTVTimeoutError as e:
_log_exception('Timeout while deleting TV image', e)
return jsonify({'error': 'TV request timed out'}), 504
except FrameTVConnectionError as e:
_log_exception('TV connection failed while deleting TV image', e)
return jsonify({'error': 'TV is unavailable'}), 503
except Exception as e:
_log_exception('Failed to delete TV image', e)
return jsonify({'error': 'Failed to delete image'}), 500
@app.route('/api/tv/<ip>/on', methods=['POST'])
def api_tv_power_on(ip):
data = request.get_json(silent=True) or {}
mac = data.get('mac')
tv = TV.query.filter_by(ip=ip).first()
token = tv.token if tv else None
try:
power_on(ip, mac, token=token)
return {'success': True}
except FrameTVError as e:
_log_exception('Failed to power on TV', e)
return _error_response('Failed to power on TV', 500)
@app.route('/api/tv/<ip>/off', methods=['POST'])
def api_tv_power_off(ip):
tv = TV.query.filter_by(ip=ip).first()
token = tv.token if tv else None
try:
power_off(ip, token=token)
return {'success': True}
except FrameTVError as e:
_log_exception('Failed to power off TV', e)
return _error_response('Failed to power off TV', 500)
@app.route('/api/tv/<ip>/artmode', methods=['POST'])
def api_tv_art_mode(ip):
tv = TV.query.filter_by(ip=ip).first()
token = tv.token if tv else None
try:
enable_art_mode(ip, token=token)
return {'success': True}
except FrameTVError as e:
_log_exception('Failed to enable art mode', e)
return _error_response('Failed to enable art mode', 500)
@app.route('/api/tv/<ip>/status', methods=['GET'])
def api_tv_status(ip):
tv = TV.query.filter_by(ip=ip).first()
token = tv.token if tv else None
try:
art_mode = is_art_mode_on(ip, token=token)
screen_on = is_tv_reachable(ip, token=token)
return {'art_mode': art_mode, 'screen_on': screen_on}
except FrameTVError as e:
_log_exception('Failed to get TV status', e)
return _error_response('Failed to get TV status', 500)
@app.route('/tv/<ip>/on', methods=['POST'])
def tv_power_on(ip):
mac = request.form.get('mac')
try:
power_on(ip, mac)
flash(f'TV {ip} powered on')
except FrameTVError as e:
flash(f'Error: {e}')
return redirect(url_for('index'))
@app.route('/tv/<ip>/off', methods=['POST'])
def tv_power_off(ip):
try:
power_off(ip)
flash(f'TV {ip} powered off')
except FrameTVError as e:
flash(f'Error: {e}')
return redirect(url_for('index'))
@app.route('/tv/<ip>/artmode', methods=['POST'])
def tv_art_mode(ip):
try:
enable_art_mode(ip)
flash(f'TV {ip} set to art mode')
except FrameTVError as e:
flash(f'Error: {e}')
return redirect(url_for('index'))
@app.route('/tv/<ip>/status')
def tv_status(ip):
try:
art_mode = is_art_mode_on(ip)
screen_on = is_tv_reachable(ip)
return {
'art_mode': art_mode,
'screen_on': screen_on
}
except FrameTVError as e:
_log_exception('Failed to get TV status', e)
return _error_response('Failed to get TV status', 500)
# Place at the bottom for lowest priority
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
try:
static_file_path = _normalized_static_path(path)
except ValueError:
return _error_response('Invalid path', 400)
if os.path.isfile(static_file_path):
return send_from_directory(app.static_folder, path)
# Always serve index.html for any unknown route (client-side routing)
return send_from_directory(app.static_folder, 'index.html')
if __name__ == '__main__':
# Use DEBUG env variable ("1", "true", "True" = True)
debug_env = os.environ.get('DEBUG', '').lower()
debug = debug_env in ('1', 'true', 'yes')
app.run(debug=debug, host="0.0.0.0")