347 lines
11 KiB
Python
347 lines
11 KiB
Python
from __future__ import annotations
|
||
|
||
import re
|
||
from datetime import datetime
|
||
from typing import Any, Optional
|
||
|
||
from pydantic import BaseModel, Field
|
||
|
||
from .timeutil import push_date_from_ts # Beijing (Asia/Shanghai)
|
||
|
||
|
||
|
||
def extract_room_id(url_or_id: str) -> str:
|
||
text = (url_or_id or "").strip()
|
||
if not text:
|
||
return ""
|
||
if re.fullmatch(r"\d{6,}", text):
|
||
return text
|
||
m = re.search(r"live\.douyin\.com/([A-Za-z0-9_\-]+)", text)
|
||
if m:
|
||
return m.group(1).split("?")[0]
|
||
m = re.search(r"/(\d{8,})", text)
|
||
return m.group(1) if m else ""
|
||
|
||
|
||
def normalize_room_url(url_or_id: str) -> str:
|
||
rid = extract_room_id(url_or_id)
|
||
if rid:
|
||
return f"https://live.douyin.com/{rid}"
|
||
text = (url_or_id or "").strip()
|
||
if text.startswith("http"):
|
||
return text.split("?")[0].rstrip("/")
|
||
return text
|
||
|
||
|
||
def extract_youtube_channel(url_or_id: str) -> dict[str, str]:
|
||
"""
|
||
Parse YouTube channel identity from common URL forms.
|
||
Returns {channel_id, handle, key, kind} where key is the stable-ish identifier.
|
||
"""
|
||
text = (url_or_id or "").strip()
|
||
if not text:
|
||
return {"channel_id": "", "handle": "", "key": "", "kind": ""}
|
||
# bare UC… id
|
||
if re.fullmatch(r"UC[\w-]{20,}", text):
|
||
return {"channel_id": text, "handle": "", "key": text, "kind": "id"}
|
||
# bare @handle
|
||
if text.startswith("@") and len(text) > 1:
|
||
handle = text[1:].split("/")[0].split("?")[0]
|
||
return {"channel_id": "", "handle": handle, "key": f"@{handle}", "kind": "handle"}
|
||
|
||
m = re.search(r"(?:youtube\.com|youtu\.be)", text, re.I)
|
||
if not m and not text.startswith("http"):
|
||
# treat as handle without @
|
||
if re.fullmatch(r"[\w.-]{2,}", text):
|
||
return {"channel_id": "", "handle": text, "key": f"@{text}", "kind": "handle"}
|
||
return {"channel_id": "", "handle": "", "key": "", "kind": ""}
|
||
|
||
# /channel/UCxxx
|
||
m = re.search(r"youtube\.com/channel/(UC[\w-]{20,})", text, re.I)
|
||
if m:
|
||
cid = m.group(1)
|
||
return {"channel_id": cid, "handle": "", "key": cid, "kind": "id"}
|
||
# /@handle
|
||
m = re.search(r"youtube\.com/@([\w.-]+)", text, re.I)
|
||
if m:
|
||
handle = m.group(1).split("/")[0].split("?")[0]
|
||
return {"channel_id": "", "handle": handle, "key": f"@{handle}", "kind": "handle"}
|
||
# /c/name or /user/name
|
||
m = re.search(r"youtube\.com/(?:c|user)/([\w.-]+)", text, re.I)
|
||
if m:
|
||
name = m.group(1).split("/")[0].split("?")[0]
|
||
return {"channel_id": "", "handle": name, "key": f"@{name}", "kind": "custom"}
|
||
return {"channel_id": "", "handle": "", "key": "", "kind": ""}
|
||
|
||
|
||
def normalize_youtube_channel_url(url_or_id: str) -> str:
|
||
info = extract_youtube_channel(url_or_id)
|
||
if info.get("channel_id"):
|
||
return f"https://www.youtube.com/channel/{info['channel_id']}"
|
||
if info.get("handle"):
|
||
return f"https://www.youtube.com/@{info['handle']}"
|
||
text = (url_or_id or "").strip()
|
||
if text.startswith("http"):
|
||
return text.split("?")[0].rstrip("/")
|
||
return text
|
||
|
||
|
||
def normalize_url_list(raw: Any) -> list[str]:
|
||
"""Split multiline / comma URLs; drop blanks and #comments; dedupe preserve order."""
|
||
if raw is None:
|
||
return []
|
||
if isinstance(raw, list):
|
||
parts = [str(x) for x in raw]
|
||
else:
|
||
text = str(raw).replace("\r\n", "\n").replace("\r", "\n").replace(",", ",")
|
||
parts = []
|
||
for line in text.split("\n"):
|
||
line = line.strip()
|
||
if not line or line.startswith("#"):
|
||
continue
|
||
for token in re.split(r"[,\s]+", line):
|
||
token = token.strip()
|
||
if token:
|
||
parts.append(token)
|
||
seen: set[str] = set()
|
||
out: list[str] = []
|
||
for p in parts:
|
||
if p in seen:
|
||
continue
|
||
seen.add(p)
|
||
out.append(p)
|
||
return out
|
||
|
||
|
||
class RoomCreate(BaseModel):
|
||
url: str
|
||
note: str = ""
|
||
enabled: bool = True
|
||
tags: str = ""
|
||
|
||
|
||
class RoomBatchCreate(BaseModel):
|
||
urls: str = Field(..., description="多行直播间 URL / 房间号,每行一个")
|
||
note: str = ""
|
||
enabled: bool = True
|
||
tags: str = ""
|
||
|
||
|
||
class RoomUpdate(BaseModel):
|
||
url: Optional[str] = None
|
||
note: Optional[str] = None
|
||
enabled: Optional[bool] = None
|
||
tags: Optional[str] = None
|
||
|
||
|
||
class RoomBulkAction(BaseModel):
|
||
action: str = Field(..., description="enable|disable|delete|set_tags|add_tags|remove_tags|check_queue")
|
||
ids: list[str]
|
||
tags: str = ""
|
||
|
||
|
||
class RoomQuickAction(BaseModel):
|
||
action: str = Field(..., description="favorite|unfavorite|ban")
|
||
room_pk: str = ""
|
||
room_id: str = ""
|
||
url: str = ""
|
||
reason: str = ""
|
||
|
||
|
||
class ChannelGroupCreate(BaseModel):
|
||
name: str = Field(..., description="分组名称")
|
||
channel_url: str = Field(..., description="YouTube 频道主 URL / @handle / channelId")
|
||
urls: str = Field("", description="分组内相关 URL,多行")
|
||
note: str = ""
|
||
platform: str = "youtube"
|
||
enabled: bool = True
|
||
|
||
|
||
class ChannelGroupUpdate(BaseModel):
|
||
name: Optional[str] = None
|
||
channel_url: Optional[str] = None
|
||
urls: Optional[str] = None
|
||
note: Optional[str] = None
|
||
platform: Optional[str] = None
|
||
enabled: Optional[bool] = None
|
||
|
||
|
||
class ChannelGroupBulkAction(BaseModel):
|
||
action: str = Field(..., description="enable|disable|delete")
|
||
ids: list[str]
|
||
|
||
|
||
class BlacklistCreate(BaseModel):
|
||
value: str = Field(..., description="房间号、URL 或关键词")
|
||
reason: str = ""
|
||
|
||
|
||
class SettingsUpdate(BaseModel):
|
||
max_concurrency: Optional[int] = None
|
||
min_request_gap_sec: Optional[float] = None
|
||
request_jitter_sec: Optional[float] = None
|
||
offline_interval_sec: Optional[float] = None
|
||
live_interval_sec: Optional[float] = None
|
||
error_backoff_base_sec: Optional[float] = None
|
||
error_backoff_max_sec: Optional[float] = None
|
||
global_pause_on_risk_sec: Optional[float] = None
|
||
capture_cover_on_start: Optional[bool] = None
|
||
monitor_enabled: Optional[bool] = None
|
||
dy_cookie: Optional[str] = None
|
||
http_proxy: Optional[str] = None
|
||
notify_webhook_url: Optional[str] = None
|
||
notify_on_live: Optional[bool] = None
|
||
notify_on_offline: Optional[bool] = None
|
||
notify_on_risk: Optional[bool] = None
|
||
notify_on_shorts_fail: Optional[bool] = None
|
||
notify_on_shorts_ok: Optional[bool] = None
|
||
notify_on_shorts_quota: Optional[bool] = None
|
||
quiet_hours_enabled: Optional[bool] = None
|
||
quiet_hours_start: Optional[int] = None
|
||
quiet_hours_end: Optional[int] = None
|
||
quiet_hours_allow_priority: Optional[bool] = None
|
||
priority_interval_sec: Optional[float] = None
|
||
yt_monitor_enabled: Optional[bool] = None
|
||
yt_offline_interval_sec: Optional[float] = None
|
||
yt_live_interval_sec: Optional[float] = None
|
||
yt_batch_size: Optional[int] = None
|
||
yt_request_gap_sec: Optional[float] = None
|
||
shorts_enabled: Optional[bool] = None
|
||
shorts_clip_sec: Optional[int] = None
|
||
shorts_trigger: Optional[str] = None
|
||
shorts_tag: Optional[str] = None
|
||
shorts_dedupe_room_day: Optional[bool] = None
|
||
shorts_max_concurrent: Optional[int] = None
|
||
shorts_auto_upload: Optional[bool] = None
|
||
shorts_live_sample: Optional[bool] = None
|
||
shorts_live_sample_interval_sec: Optional[float] = None
|
||
shorts_live_sample_batch: Optional[int] = None
|
||
shorts_sample_any_live: Optional[bool] = None
|
||
shorts_upload_spread: Optional[bool] = None
|
||
shorts_upload_min_gap_sec: Optional[float] = None
|
||
shorts_channel_min_gap_sec: Optional[float] = None
|
||
shorts_delete_clip_after_upload: Optional[bool] = None
|
||
shorts_auto_retry_failed: Optional[bool] = None
|
||
shorts_auto_retry_max_attempts: Optional[int] = None
|
||
shorts_auto_retry_interval_sec: Optional[float] = None
|
||
shorts_oauth_check_interval_sec: Optional[float] = None
|
||
shorts_oauth_client_id: Optional[str] = None
|
||
shorts_oauth_client_secret: Optional[str] = None
|
||
shorts_oauth_redirect_uri: Optional[str] = None
|
||
shorts_oauth_profiles: Optional[list[dict[str, Any]]] = None
|
||
shorts_gcp_project_id: Optional[str] = None
|
||
shorts_upload_socks_enabled: Optional[bool] = None
|
||
shorts_upload_socks_profile_id: Optional[str] = None
|
||
shorts_upload_socks_profiles: Optional[list[dict[str, Any]]] = None
|
||
|
||
|
||
class ShortsChannelCreate(BaseModel):
|
||
name: str
|
||
youtube_channel_id: str = ""
|
||
client_id: str = ""
|
||
client_secret: str = ""
|
||
refresh_token: str = ""
|
||
enabled: bool = True
|
||
daily_min: int = 9
|
||
daily_max: int = 9
|
||
title_template: str = "{anchor} 直播瞬间 #Shorts"
|
||
description_template: str = "{anchor}\n{url}\n#Shorts #直播"
|
||
privacy: str = "public"
|
||
note: str = ""
|
||
oauth_profile_id: str = ""
|
||
|
||
|
||
class ShortsChannelUpdate(BaseModel):
|
||
name: Optional[str] = None
|
||
youtube_channel_id: Optional[str] = None
|
||
client_id: Optional[str] = None
|
||
client_secret: Optional[str] = None
|
||
refresh_token: Optional[str] = None
|
||
enabled: Optional[bool] = None
|
||
daily_min: Optional[int] = None
|
||
daily_max: Optional[int] = None
|
||
title_template: Optional[str] = None
|
||
description_template: Optional[str] = None
|
||
privacy: Optional[str] = None
|
||
note: Optional[str] = None
|
||
oauth_profile_id: Optional[str] = None
|
||
|
||
|
||
class ShortsJobsBulkBody(BaseModel):
|
||
job_ids: list[str]
|
||
action: str = "retry" # retry | upload_now
|
||
|
||
|
||
class TikTokOAuthConfig(BaseModel):
|
||
client_key: str = ""
|
||
client_secret: str = ""
|
||
|
||
|
||
class TikTokSessionBody(BaseModel):
|
||
sessionid: str = ""
|
||
dc_id: str = "useast2a"
|
||
tiktok_username: str = ""
|
||
|
||
|
||
class TikTokChannelCreate(BaseModel):
|
||
name: str = "TikTok 账号"
|
||
enabled: bool = True
|
||
title_template: str = ""
|
||
description_template: str = ""
|
||
privacy_level: str = "PUBLIC_TO_EVERYONE"
|
||
note: str = ""
|
||
socks_enabled: bool = False
|
||
socks_profile_id: str = ""
|
||
|
||
|
||
class TikTokChannelUpdate(BaseModel):
|
||
name: Optional[str] = None
|
||
enabled: Optional[bool] = None
|
||
title_template: Optional[str] = None
|
||
description_template: Optional[str] = None
|
||
privacy_level: Optional[str] = None
|
||
note: Optional[str] = None
|
||
socks_enabled: Optional[bool] = None
|
||
socks_profile_id: Optional[str] = None
|
||
|
||
|
||
class TikTokSocksProfilesBody(BaseModel):
|
||
profiles: list[dict[str, Any]] = Field(default_factory=list)
|
||
|
||
|
||
class TikTokJobsBulkBody(BaseModel):
|
||
job_ids: list[str]
|
||
action: str = "retry" # retry | upload_now
|
||
|
||
|
||
class TikTokUploadNowBody(BaseModel):
|
||
channel_pk: str = ""
|
||
|
||
|
||
class YouTubeVideoUpdate(BaseModel):
|
||
title: Optional[str] = None
|
||
description: Optional[str] = None
|
||
tags: Optional[list[str]] = None
|
||
category_id: Optional[str] = None
|
||
privacy_status: Optional[str] = None
|
||
publish_at: Optional[str] = None
|
||
embeddable: Optional[bool] = None
|
||
|
||
|
||
class PurgeEventsBody(BaseModel):
|
||
older_than_days: float = 7
|
||
kind: str = ""
|
||
|
||
|
||
class MonitorStatus(BaseModel):
|
||
running: bool
|
||
monitor_enabled: bool
|
||
checked_total: int = 0
|
||
live_count: int = 0
|
||
room_count: int = 0
|
||
blacklist_count: int = 0
|
||
risk_paused_until: float = 0
|
||
last_error: str = ""
|
||
last_check_at: float = 0
|
||
config: dict[str, Any] = Field(default_factory=dict)
|