home · contact · privacy
Try retrieving thumbnails if not stored locally yet. master
authorChristian Heller <c.heller@plomlompom.de>
Tue, 19 Nov 2024 05:19:39 +0000 (06:19 +0100)
committerChristian Heller <c.heller@plomlompom.de>
Tue, 19 Nov 2024 05:19:39 +0000 (06:19 +0100)
ytplom.py

index c1a4238a936e981ee78d4048ad92455d64034c76..3bb9df0554f6f49d325bf48d51cec3176ddbd1f6 100755 (executable)
--- a/ytplom.py
+++ b/ytplom.py
@@ -13,6 +13,7 @@ from threading import Thread
 from http.server import HTTPServer, BaseHTTPRequestHandler
 from urllib.parse import urlparse, parse_qs
 from urllib.request import urlretrieve
+from urllib.error import HTTPError
 from sqlite3 import connect as sql_connect, Cursor, Row
 from jinja2 import Template
 from mpv import MPV  # type: ignore
@@ -66,6 +67,8 @@ YT_DOWNLOAD_FORMAT = 'bestvideo[height<=1080][width<=1920]+bestaudio'\
 YT_DL_PARAMS = {'paths': {'home': PATH_DIR_DOWNLOADS,
                           'temp': NAME_DIR_TEMP},
                 'format': YT_DOWNLOAD_FORMAT}
+THUMBNAIL_URL_PREFIX = PathStr('https://i.ytimg.com/vi/')
+THUMBNAIL_URL_SUFFIX = PathStr('/default.jpg')
 
 QUOTA_COST_YOUTUBE_SEARCH = QuotaCost(100)
 QUOTA_COST_YOUTUBE_DETAILS = QuotaCost(1)
@@ -619,7 +622,15 @@ class TaskHandler(BaseHTTPRequestHandler):
     def _send_thumbnail(self, filename: PathStr) -> None:
         path_thumbnail = path_join(PATH_DIR_THUMBNAILS, filename)
         if not path_exists(path_thumbnail):
-            raise NotFoundException
+            video_id = splitext(filename)[0]
+            url = f'{THUMBNAIL_URL_PREFIX}{video_id}{THUMBNAIL_URL_SUFFIX}'
+            try:
+                urlretrieve(url,
+                            path_join(PATH_DIR_THUMBNAILS, f'{video_id}.jpg'))
+            except HTTPError as e:
+                if 404 == e.code:
+                    raise NotFoundException from e
+                raise e
         with open(path_thumbnail, 'rb') as f:
             img = f.read()
         self._send_http(img, [('Content-type', 'image/jpg')])