| 1 | from __future__ import annotations |
| 2 | |
| 3 | from datetime import datetime, timedelta |
| 4 | from pathlib import Path |
| 5 | |
| 6 | |
| 7 | class BaseVideoUploader: |
| 8 | SUPPORTED_VIDEO_EXTENSIONS = { |
| 9 | ".mp4", |
| 10 | ".mov", |
| 11 | ".avi", |
| 12 | ".mkv", |
| 13 | ".m4v", |
| 14 | ".webm", |
| 15 | ".flv", |
| 16 | ".wmv", |
| 17 | } |
| 18 | SUPPORTED_IMAGE_EXTENSIONS = { |
| 19 | ".jpg", |
| 20 | ".jpeg", |
| 21 | ".png", |
| 22 | ".webp", |
| 23 | ".bmp", |
| 24 | } |
| 25 | MIN_SCHEDULE_LEAD_TIME = timedelta(hours=2) |
| 26 | |
| 27 | @classmethod |
| 28 | def validate_video_file(cls, file_path: str | Path) -> Path: |
| 29 | path = Path(file_path).expanduser().resolve() |
| 30 | if not path.exists(): |
| 31 | raise FileNotFoundError(f"视频文件不存在: {path}") |
| 32 | if not path.is_file(): |
| 33 | raise ValueError(f"视频路径不是文件: {path}") |
| 34 | if path.suffix.lower() not in cls.SUPPORTED_VIDEO_EXTENSIONS: |
| 35 | raise ValueError( |
| 36 | f"不支持的视频格式: {path.suffix},当前支持: {', '.join(sorted(cls.SUPPORTED_VIDEO_EXTENSIONS))}" |
| 37 | ) |
| 38 | |
| 39 | return path |
| 40 | |
| 41 | @classmethod |
| 42 | def validate_image_file(cls, file_path: str | Path) -> Path: |
| 43 | path = Path(file_path).expanduser().resolve() |
| 44 | if not path.exists(): |
| 45 | raise FileNotFoundError(f"图片文件不存在: {path}") |
| 46 | if not path.is_file(): |
| 47 | raise ValueError(f"图片路径不是文件: {path}") |
| 48 | if path.suffix.lower() not in cls.SUPPORTED_IMAGE_EXTENSIONS: |
| 49 | raise ValueError( |
| 50 | f"不支持的图片格式: {path.suffix},当前支持: {', '.join(sorted(cls.SUPPORTED_IMAGE_EXTENSIONS))}" |
| 51 | ) |
| 52 | return path |
| 53 | |
| 54 | @classmethod |
| 55 | def validate_publish_date(cls, publish_date: datetime | int | None) -> datetime | int: |
| 56 | if publish_date in (None, 0): |
| 57 | return 0 |
| 58 | |
| 59 | if not isinstance(publish_date, datetime): |
| 60 | raise TypeError("publish_date 必须是 datetime 类型或 0") |
| 61 | |
| 62 | now = datetime.now(tz=publish_date.tzinfo) if publish_date.tzinfo else datetime.now() |
| 63 | if publish_date <= now: |
| 64 | raise ValueError("定时发布时间必须晚于当前时间") |
| 65 | |
| 66 | min_publish_time = now + cls.MIN_SCHEDULE_LEAD_TIME |
| 67 | if publish_date <= min_publish_time: |
| 68 | raise ValueError("定时发布时间必须大于当前时间 2 小时") |
| 69 | |
| 70 | return publish_date |
| 71 |