Enabled all Ruff lint rules and resolved findings with justified inline suppressions.
CI / Formatting (push) Successful in 5s
CI / Linting (push) Successful in 5s
CI / Tests (Python 3.12) (push) Successful in 14s
CI / Tests (Python 3.13) (push) Successful in 14s
CI / Tests (Python 3.14) (push) Successful in 11s
CI / Type Checking (push) Successful in 10s
CI / Spelling (push) Successful in 5s
CI / Formatting (push) Successful in 5s
CI / Linting (push) Successful in 5s
CI / Tests (Python 3.12) (push) Successful in 14s
CI / Tests (Python 3.13) (push) Successful in 14s
CI / Tests (Python 3.14) (push) Successful in 11s
CI / Type Checking (push) Successful in 10s
CI / Spelling (push) Successful in 5s
This commit is contained in:
@@ -20,6 +20,7 @@ stream in real time and provides a browser-based clip editor.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
@@ -95,7 +96,7 @@ async def setup(ctx: ModuleContext) -> None:
|
||||
processor = VideoProcessor(ctx.logger)
|
||||
|
||||
clips_dir = Path(str(ctx.config.get("clips_dir")))
|
||||
clips_dir.mkdir(parents=True, exist_ok=True) # noqa: ASYNC240
|
||||
await asyncio.to_thread(clips_dir.mkdir, parents=True, exist_ok=True)
|
||||
|
||||
manager = ClipManager(ctx, repo, processor, clips_dir)
|
||||
ctx.state["manager"] = manager
|
||||
@@ -106,7 +107,7 @@ async def setup(ctx: ModuleContext) -> None:
|
||||
if status.get("online", False):
|
||||
ctx.logger.info("Stream is already live. Starting HLS cache.")
|
||||
await manager.start_caching()
|
||||
except Exception:
|
||||
except Exception: # noqa: BLE001 # best-effort; non-fatal if Owncast is unreachable during setup
|
||||
ctx.logger.warning(
|
||||
"Could not check Owncast status during setup.", exc_info=True
|
||||
)
|
||||
|
||||
@@ -27,6 +27,7 @@ import re
|
||||
import shutil
|
||||
import tempfile
|
||||
from contextlib import asynccontextmanager
|
||||
from http import HTTPStatus
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
from urllib.parse import urljoin
|
||||
@@ -140,7 +141,7 @@ class ChunkCache:
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await self._task
|
||||
self._task = None
|
||||
await asyncio.to_thread(shutil.rmtree, self._cache_dir, True)
|
||||
await asyncio.to_thread(shutil.rmtree, self._cache_dir, ignore_errors=True)
|
||||
self._sequences.clear()
|
||||
|
||||
async def _download_segment(self, segment_url: str, seq: int) -> bool:
|
||||
@@ -152,7 +153,7 @@ class ChunkCache:
|
||||
"""
|
||||
try:
|
||||
async with self._http.get(segment_url) as seg_resp:
|
||||
if seg_resp.status != 200:
|
||||
if seg_resp.status != HTTPStatus.OK:
|
||||
return False
|
||||
data = await seg_resp.read()
|
||||
except asyncio.CancelledError:
|
||||
@@ -177,7 +178,7 @@ class ChunkCache:
|
||||
while True:
|
||||
try:
|
||||
async with self._http.get(self._variant_url) as resp:
|
||||
if resp.status != 200:
|
||||
if resp.status != HTTPStatus.OK:
|
||||
self._logger.warning(
|
||||
"Variant playlist returned HTTP %d.", resp.status
|
||||
)
|
||||
@@ -233,7 +234,7 @@ class ChunkCache:
|
||||
oldest = min(self._sequences)
|
||||
self._sequences.discard(oldest)
|
||||
path = self._segment_path(oldest)
|
||||
await asyncio.to_thread(path.unlink, True)
|
||||
await asyncio.to_thread(path.unlink, missing_ok=True)
|
||||
if len(self._sequences) < pre_prune:
|
||||
self._logger.debug(
|
||||
"Pruned %d segment(s). Cache: %d chunks, %.1fs total.",
|
||||
@@ -245,7 +246,7 @@ class ChunkCache:
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
self._logger.error("Error in HLS polling loop.", exc_info=True)
|
||||
self._logger.exception("Error in HLS polling loop.")
|
||||
|
||||
await asyncio.sleep(self._target_duration)
|
||||
|
||||
@@ -338,11 +339,12 @@ async def start_caching(
|
||||
|
||||
cache.start()
|
||||
logger.info("HLS caching started. Cache dir: %s", cache_dir)
|
||||
return cache
|
||||
|
||||
except BaseException:
|
||||
shutil.rmtree(cache_dir, ignore_errors=True)
|
||||
raise
|
||||
else:
|
||||
return cache
|
||||
|
||||
|
||||
async def _fetch_playlist(
|
||||
@@ -364,7 +366,7 @@ async def _fetch_playlist(
|
||||
exc_info = False
|
||||
try:
|
||||
async with http.get(url) as resp:
|
||||
if resp.status != 200:
|
||||
if resp.status != HTTPStatus.OK:
|
||||
reason = f"HTTP {resp.status}"
|
||||
else:
|
||||
content = await resp.text()
|
||||
@@ -409,7 +411,7 @@ async def _download_init_segment(
|
||||
exc_info = False
|
||||
try:
|
||||
async with http.get(init_url) as resp:
|
||||
if resp.status != 200:
|
||||
if resp.status != HTTPStatus.OK:
|
||||
reason = f"HTTP {resp.status}"
|
||||
else:
|
||||
data = await resp.read()
|
||||
|
||||
@@ -45,7 +45,7 @@ async def clip_command(ctx: CommandContext) -> None:
|
||||
"Not enough stream data is available yet. Please try again later."
|
||||
)
|
||||
return
|
||||
except Exception:
|
||||
except Exception: # noqa: BLE001 # catch-all after specific exceptions; ffmpeg/IO failures are unpredictable
|
||||
await ctx.owncast_client.send_message(
|
||||
"Failed to create clip preview. Please try again."
|
||||
)
|
||||
|
||||
@@ -192,8 +192,8 @@ class ClipManager:
|
||||
preview_path, self._cache
|
||||
)
|
||||
except Exception:
|
||||
self._ctx.logger.error("Failed to generate clip preview.", exc_info=True)
|
||||
await asyncio.to_thread(shutil.rmtree, work_dir, True)
|
||||
self._ctx.logger.exception("Failed to generate clip preview.")
|
||||
await asyncio.to_thread(shutil.rmtree, work_dir, ignore_errors=True)
|
||||
raise
|
||||
|
||||
token = secrets.token_urlsafe(32)
|
||||
@@ -303,7 +303,7 @@ class ClipManager:
|
||||
thumbnail_path,
|
||||
duration=actual_duration,
|
||||
)
|
||||
except Exception:
|
||||
except Exception: # noqa: BLE001 # best-effort; clip already saved, thumbnail is optional
|
||||
self._ctx.logger.warning(
|
||||
"Thumbnail generation failed for clip %d.",
|
||||
clip.id,
|
||||
@@ -311,14 +311,12 @@ class ClipManager:
|
||||
)
|
||||
thumbnail_path.unlink(missing_ok=True)
|
||||
|
||||
return clip
|
||||
|
||||
except Exception:
|
||||
# Clean up partial state to avoid orphaned DB rows or files.
|
||||
if clip_id is not None:
|
||||
try:
|
||||
await self._repo.delete(clip_id)
|
||||
except Exception:
|
||||
except Exception: # noqa: BLE001 # last-resort; cleanup itself failed, just log it
|
||||
self._ctx.logger.warning(
|
||||
"Failed to clean up DB row for clip %d.",
|
||||
clip_id,
|
||||
@@ -327,8 +325,10 @@ class ClipManager:
|
||||
if clip_path is not None:
|
||||
clip_path.unlink(missing_ok=True)
|
||||
raise
|
||||
else:
|
||||
return clip
|
||||
finally:
|
||||
await asyncio.to_thread(shutil.rmtree, session.work_dir, True)
|
||||
await asyncio.to_thread(shutil.rmtree, session.work_dir, ignore_errors=True)
|
||||
|
||||
async def cleanup_session(self, token: str) -> None:
|
||||
"""Remove a session and clean up its working directory.
|
||||
@@ -339,7 +339,7 @@ class ClipManager:
|
||||
if session is not None:
|
||||
if session.expiry_task is not None:
|
||||
session.expiry_task.cancel()
|
||||
await asyncio.to_thread(shutil.rmtree, session.work_dir, True)
|
||||
await asyncio.to_thread(shutil.rmtree, session.work_dir, ignore_errors=True)
|
||||
|
||||
async def start_caching(self) -> None:
|
||||
"""Start HLS caching from the Owncast stream.
|
||||
@@ -357,7 +357,7 @@ class ClipManager:
|
||||
logger=self._ctx.logger,
|
||||
)
|
||||
except Exception:
|
||||
self._ctx.logger.error("Failed to start HLS caching.", exc_info=True)
|
||||
self._ctx.logger.exception("Failed to start HLS caching.")
|
||||
|
||||
async def stop_caching(self) -> None:
|
||||
"""Stop HLS caching and clean up cached files."""
|
||||
@@ -434,5 +434,5 @@ def get_manager(ctx: ModuleContext) -> ClipManager:
|
||||
manager = ctx.state.get("manager")
|
||||
if not isinstance(manager, ClipManager):
|
||||
msg = "ClipManager is not initialized."
|
||||
raise RuntimeError(msg)
|
||||
raise RuntimeError(msg) # noqa: TRY004 # state error, not a type error
|
||||
return manager
|
||||
|
||||
@@ -113,7 +113,7 @@ async def editor_preview_video(ctx: RouteContext) -> web.StreamResponse:
|
||||
|
||||
|
||||
@on_route("/static/editor.js", methods=["GET"])
|
||||
async def editor_js(ctx: RouteContext) -> web.StreamResponse:
|
||||
async def editor_js(ctx: RouteContext) -> web.StreamResponse: # noqa: ARG001 # required by route handler signature
|
||||
"""Serve the clip editor JavaScript.
|
||||
|
||||
:param ctx: The route context.
|
||||
@@ -155,7 +155,7 @@ async def editor_submit(ctx: RouteContext) -> web.Response:
|
||||
except InvalidClipParamsError as e:
|
||||
return _error_page(ctx, 400, e.reason)
|
||||
except Exception:
|
||||
ctx.logger.error("Failed to create clip.", exc_info=True)
|
||||
ctx.logger.exception("Failed to create clip.")
|
||||
return _error_page(ctx, 500, "Clip processing failed.")
|
||||
|
||||
clip_url = ctx.routes.url_for(f"/view/{clip.id}")
|
||||
|
||||
Reference in New Issue
Block a user