216 lines
9.2 KiB
Python
216 lines
9.2 KiB
Python
import re
|
||
import threading
|
||
from core.metadata import format_duration
|
||
|
||
_KICK_URL_RE = re.compile(
|
||
r"^https?://(?:www\.)?kick\.com/"
|
||
r"(?P<channel>[\w-]+)"
|
||
r"(?:(?P<rest>/videos/[\da-f-]+|/clips/clip_[\w-]+|/?\?(?:[^#]+&)?clip=clip_[\w-]+))?",
|
||
re.IGNORECASE
|
||
)
|
||
|
||
|
||
def parse_kick_input(raw_input: str) -> dict:
|
||
"""
|
||
Kullanıcı girdisini ayrıştırır:
|
||
- Kanal adı (örn: 'elraenn', '@xqc', 'https://kick.com/xqc') -> {'type': 'channel', 'channel': 'xqc', 'url': 'https://kick.com/xqc'}
|
||
- VOD URL -> {'type': 'vod', 'channel': '...', 'url': '...'}
|
||
- Clip URL -> {'type': 'clip', 'channel': '...', 'url': '...'}
|
||
"""
|
||
text = (raw_input or "").strip()
|
||
if not text:
|
||
return {"type": "empty", "channel": "", "url": ""}
|
||
|
||
# Doğrudan URL kontrolü
|
||
if text.startswith(("http://", "https://", "kick.com/", "www.kick.com/")):
|
||
if not text.startswith(("http://", "https://")):
|
||
text = "https://" + text
|
||
|
||
m = _KICK_URL_RE.match(text)
|
||
if m:
|
||
channel = m.group("channel").lower()
|
||
rest = (m.group("rest") or "").lower()
|
||
if "/videos/" in rest:
|
||
return {"type": "vod", "channel": channel, "url": text}
|
||
if "clip_" in rest:
|
||
return {"type": "clip", "channel": channel, "url": text}
|
||
if channel not in ("video", "categories", "search", "auth"):
|
||
return {"type": "channel", "channel": channel, "url": f"https://kick.com/{channel}"}
|
||
return {"type": "url", "channel": "", "url": text}
|
||
|
||
# Kanal kullanıcı adı (örn: 'xqc' veya '@xqc')
|
||
slug = text.lstrip("@").strip("/").split("/")[0].strip()
|
||
if re.match(r"^[\w-]+$", slug):
|
||
return {"type": "channel", "channel": slug.lower(), "url": f"https://kick.com/{slug.lower()}"}
|
||
|
||
return {"type": "unknown", "channel": "", "url": text}
|
||
|
||
|
||
def _kick_api_get(endpoint: str, proxy: str = None, timeout: int = 15):
|
||
"""
|
||
Kick API v2 endpoint'ine Cloudflare TLS parmak izi (impersonate) ile istek atar.
|
||
Öncelikle curl_cffi kullanır, yoksa yt_dlp üzerinden fallback yapar.
|
||
"""
|
||
url = f"https://kick.com/api/{endpoint.lstrip('/')}"
|
||
headers = {
|
||
"Accept": "application/json, text/plain, */*",
|
||
"Accept-Language": "tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7",
|
||
"Referer": "https://kick.com/",
|
||
}
|
||
|
||
# 1. Yöntem: curl_cffi (Chrome TLS Impersonation - Cloudflare Bypass)
|
||
try:
|
||
from curl_cffi import requests as creq
|
||
proxies = {"http": proxy, "https": proxy} if proxy else None
|
||
resp = creq.get(
|
||
url,
|
||
headers=headers,
|
||
impersonate="chrome",
|
||
proxies=proxies,
|
||
timeout=timeout
|
||
)
|
||
if resp.status_code == 200:
|
||
return resp.json()
|
||
if resp.status_code == 404:
|
||
raise ValueError("Kick kanalı veya içerik bulunamadı (404).")
|
||
except ValueError:
|
||
raise
|
||
except Exception:
|
||
pass
|
||
|
||
# 2. Yöntem: yt_dlp içsel impersonate istemcisi
|
||
import yt_dlp
|
||
from yt_dlp.networking.impersonate import ImpersonateTarget
|
||
ydl_opts = {
|
||
"quiet": True,
|
||
"no_warnings": True,
|
||
"socket_timeout": timeout,
|
||
"impersonate": ImpersonateTarget.from_str("chrome"),
|
||
}
|
||
if proxy:
|
||
ydl_opts["proxy"] = proxy
|
||
|
||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
||
return ydl._download_json(url, endpoint, note=False, headers=headers)
|
||
|
||
|
||
def fetch_kick_channel_Async(channel_slug: str, proxy: str = None, callback=None, error_callback=None):
|
||
"""
|
||
Kick kanalının canlı yayın durumunu, geçmiş yayınlarını (VODs) ve kliplerini (Clips)
|
||
arka planda tek seferde çeker.
|
||
"""
|
||
slug = (channel_slug or "").strip().lstrip("@").lower()
|
||
if not slug:
|
||
if error_callback:
|
||
error_callback("Geçerli bir Kick kanal adı girin.")
|
||
return
|
||
|
||
def _worker():
|
||
try:
|
||
ch_data = _kick_api_get(f"v2/channels/{slug}", proxy=proxy)
|
||
if not ch_data or not isinstance(ch_data, dict):
|
||
raise ValueError(f"'{slug}' kanalı bulunamadı.")
|
||
|
||
user_obj = ch_data.get("user") or {}
|
||
username = user_obj.get("username") or ch_data.get("slug") or slug
|
||
followers = ch_data.get("followers_count") or 0
|
||
avatar_url = user_obj.get("profile_pic") or ""
|
||
|
||
livestream = ch_data.get("livestream")
|
||
is_live = bool(livestream and isinstance(livestream, dict))
|
||
live_info = None
|
||
if is_live:
|
||
cats = livestream.get("categories") or []
|
||
cat_name = cats[0].get("name", "Canlı Yayın") if cats and isinstance(cats[0], dict) else "Canlı Yayın"
|
||
thumb_obj = livestream.get("thumbnail")
|
||
thumb_url = thumb_obj.get("url") if isinstance(thumb_obj, dict) else (thumb_obj if isinstance(thumb_obj, str) else "")
|
||
live_info = {
|
||
"id": str(livestream.get("id") or slug),
|
||
"title": livestream.get("session_title") or f"{username} Canlı Yayını",
|
||
"viewers": livestream.get("viewer_count") or 0,
|
||
"category": cat_name,
|
||
"created_at": (livestream.get("created_at") or "")[:16].replace("T", " "),
|
||
"thumbnail": thumb_url,
|
||
"url": f"https://kick.com/{slug}",
|
||
}
|
||
|
||
# 2. VOD (Geçmiş Yayınlar) çek
|
||
vods_list = []
|
||
try:
|
||
raw_vods = _kick_api_get(f"v2/channels/{slug}/videos", proxy=proxy) or []
|
||
if isinstance(raw_vods, list):
|
||
for v in raw_vods:
|
||
if not isinstance(v, dict):
|
||
continue
|
||
vid_obj = v.get("video") or {}
|
||
uuid = vid_obj.get("uuid") or v.get("uuid")
|
||
if not uuid:
|
||
continue
|
||
dur_ms = v.get("duration") or 0
|
||
# Kick API VOD duration milisaniye cinsindendir
|
||
dur_sec = dur_ms / 1000.0 if dur_ms > 36000 else dur_ms
|
||
cats = v.get("categories") or []
|
||
cat_name = cats[0].get("name", "—") if cats and isinstance(cats[0], dict) else "—"
|
||
created_raw = (v.get("created_at") or v.get("start_time") or "")[:16].replace("T", " ")
|
||
vods_list.append({
|
||
"uuid": uuid,
|
||
"title": v.get("session_title") or "İsimsiz Yayın Tekrarı (VOD)",
|
||
"duration": format_duration(dur_sec),
|
||
"views": v.get("views") or 0,
|
||
"date": created_raw or "—",
|
||
"category": cat_name,
|
||
"is_live": bool(v.get("is_live")),
|
||
"url": f"https://kick.com/{slug}/videos/{uuid}",
|
||
})
|
||
except Exception:
|
||
pass
|
||
|
||
# 3. Klipleri (Clips) çek
|
||
clips_list = []
|
||
try:
|
||
raw_clips_resp = _kick_api_get(f"v2/channels/{slug}/clips", proxy=proxy) or {}
|
||
raw_clips = raw_clips_resp.get("clips") if isinstance(raw_clips_resp, dict) else []
|
||
if isinstance(raw_clips, list):
|
||
for c in raw_clips:
|
||
if not isinstance(c, dict):
|
||
continue
|
||
clip_id = c.get("id")
|
||
if not clip_id:
|
||
continue
|
||
cat_obj = c.get("category") or {}
|
||
creator_obj = c.get("creator") or {}
|
||
created_raw = (c.get("created_at") or "")[:16].replace("T", " ")
|
||
clips_list.append({
|
||
"id": clip_id,
|
||
"title": c.get("title") or "İsimsiz Klip",
|
||
"duration": format_duration(c.get("duration") or 0),
|
||
"views": c.get("view_count") if c.get("view_count") is not None else (c.get("views") or 0),
|
||
"likes": c.get("likes_count") if c.get("likes_count") is not None else (c.get("likes") or 0),
|
||
"creator": creator_obj.get("username") or slug,
|
||
"category": cat_obj.get("name") or "—",
|
||
"date": created_raw or "—",
|
||
"url": f"https://kick.com/{slug}/clips/{clip_id}",
|
||
})
|
||
except Exception:
|
||
pass
|
||
|
||
result = {
|
||
"slug": slug,
|
||
"username": username,
|
||
"followers": followers,
|
||
"avatar_url": avatar_url,
|
||
"is_live": is_live,
|
||
"live_info": live_info,
|
||
"vods": vods_list,
|
||
"clips": clips_list,
|
||
"channel_url": f"https://kick.com/{slug}",
|
||
}
|
||
|
||
if callback:
|
||
callback(result)
|
||
|
||
except Exception as ex:
|
||
if error_callback:
|
||
error_callback(str(ex))
|
||
|
||
threading.Thread(target=_worker, daemon=True).start()
|