Update streamlit_app.py
Browse files- streamlit_app.py +26 -15
streamlit_app.py
CHANGED
|
@@ -26,13 +26,11 @@ CUSTOM_STREAM_KEY = os.getenv("CUSTOM_STREAM_KEY", "skqf-rd92-dfa7-74cx-bxr2")
|
|
| 26 |
# دالة تنظيف وتجهيز الكوكيز الحساسة فقط لمنع خطأ 400 Bad Request
|
| 27 |
# ══════════════════════════════════════════════════════════════════════════════ #
|
| 28 |
def get_clean_tiktok_cookies():
|
| 29 |
-
"""تستخلص فقط الكوكيز الضرورية لتخطي الحظر لمنع تضخم الـ Header وحظر الـ CDN"""
|
| 30 |
raw_cookies = os.getenv("TIKTOK_COOKIES")
|
| 31 |
if not raw_cookies:
|
| 32 |
return ""
|
| 33 |
|
| 34 |
important_cookies = {}
|
| 35 |
-
# الفلاتر الأساسية لتخطي الحظر
|
| 36 |
target_keys = ["sessionid", "ttwid", "passport_csrf_token", "sid_guard"]
|
| 37 |
|
| 38 |
for line in raw_cookies.splitlines():
|
|
@@ -40,7 +38,6 @@ def get_clean_tiktok_cookies():
|
|
| 40 |
if not line or line.startswith("#"):
|
| 41 |
continue
|
| 42 |
|
| 43 |
-
# إذا كانت بصيغة Netscape (ملف نصي مفرغ بـ Tabs)
|
| 44 |
parts = line.split("\t")
|
| 45 |
if len(parts) >= 7:
|
| 46 |
name = parts[5]
|
|
@@ -48,7 +45,6 @@ def get_clean_tiktok_cookies():
|
|
| 48 |
if name.lower() in target_keys or name.startswith("store-"):
|
| 49 |
important_cookies[name] = value
|
| 50 |
elif "=" in line:
|
| 51 |
-
# إذا كانت بصيغة سطر واحد، نقوم بتفكيكها وفلترتها
|
| 52 |
pairs = line.split(";")
|
| 53 |
for pair in pairs:
|
| 54 |
if "=" in pair:
|
|
@@ -59,7 +55,6 @@ def get_clean_tiktok_cookies():
|
|
| 59 |
if important_cookies:
|
| 60 |
return "; ".join([f"{k}={v}" for k, v in important_cookies.items()])
|
| 61 |
|
| 62 |
-
# إذا لم يجد الفلاتر، يمرر أول 200 حرف كحد أقصى لتجنب خطأ الـ 400
|
| 63 |
return raw_cookies[:200] if len(raw_cookies) > 200 else raw_cookies
|
| 64 |
|
| 65 |
# ══════════════════════════════════════════════════════════════════════════════ #
|
|
@@ -88,19 +83,30 @@ def update_youtube_broadcast_title():
|
|
| 88 |
print(f"Error updating YouTube title: {e}")
|
| 89 |
|
| 90 |
# ══════════════════════════════════════════════════════════════════════════════ #
|
| 91 |
-
# دالة الإغلاق الاحترافي عبر API
|
| 92 |
# ══════════════════════════════════════════════════════════════════════════════ #
|
| 93 |
def finalize_broadcast_via_api():
|
| 94 |
try:
|
| 95 |
if not os.path.exists(TOKEN): return
|
| 96 |
creds = pickle.load(open(TOKEN, "rb"))
|
| 97 |
yt = build('youtube', 'v3', credentials=creds)
|
| 98 |
-
|
|
|
|
|
|
|
| 99 |
if broadcasts.get("items"):
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
# ══════════════════════════════════════════════════════════════════════════════ #
|
| 106 |
# محرك المراقبة المدمج
|
|
@@ -110,6 +116,12 @@ def run_monitor():
|
|
| 110 |
try: fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 111 |
except: return
|
| 112 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
is_streaming = False
|
| 114 |
process = None
|
| 115 |
offline_start_time = None
|
|
@@ -131,11 +143,9 @@ def run_monitor():
|
|
| 131 |
# تحديث عنوان البث على يوتيوب بالتاريخ أولاً
|
| 132 |
update_youtube_broadcast_title()
|
| 133 |
|
| 134 |
-
# استخلاص الكوكيز المفلترة والخفيفة تماماً لضمان رضا الـ CDN
|
| 135 |
cookie_string = get_clean_tiktok_cookies()
|
| 136 |
header_option = f'--http-header "Cookie={cookie_string}"' if cookie_string else ""
|
| 137 |
|
| 138 |
-
# الأمر الموزون والمستقر
|
| 139 |
cmd = (
|
| 140 |
f'streamlink --loglevel error {header_option} "https://www.tiktok.com/{TIKTOK_USERNAME}/live" best --hls-live-edge 3 --stdout | '
|
| 141 |
f"ffmpeg -hide_banner -loglevel error -thread_queue_size 8192 -i pipe:0 "
|
|
@@ -146,13 +156,14 @@ def run_monitor():
|
|
| 146 |
)
|
| 147 |
process = subprocess.Popen(cmd, shell=True)
|
| 148 |
is_streaming = True
|
| 149 |
-
with open(STATUS, "w") as f: json.dump({"live": True},
|
| 150 |
|
| 151 |
else:
|
| 152 |
if is_streaming:
|
| 153 |
if offline_start_time is None: offline_start_time = time.time()
|
| 154 |
if time.time() - offline_start_time >= GRACE_PERIOD_SECONDS:
|
| 155 |
if process: process.terminate()
|
|
|
|
| 156 |
finalize_broadcast_via_api()
|
| 157 |
is_streaming = False
|
| 158 |
offline_start_time = None
|
|
@@ -170,7 +181,7 @@ if "core_monitor_initialized" not in st.session_state:
|
|
| 170 |
# ══════════════════════════════════════════════════════════════════════════════ #
|
| 171 |
# الواجهة
|
| 172 |
# ══════════════════════════════════════════════════════════════════════════════ #
|
| 173 |
-
st.set_page_config(page_title="
|
| 174 |
st.title("📡 رادار بث أحمد عبدالله - المدمج الاحترافي")
|
| 175 |
|
| 176 |
def get_status():
|
|
|
|
| 26 |
# دالة تنظيف وتجهيز الكوكيز الحساسة فقط لمنع خطأ 400 Bad Request
|
| 27 |
# ══════════════════════════════════════════════════════════════════════════════ #
|
| 28 |
def get_clean_tiktok_cookies():
|
|
|
|
| 29 |
raw_cookies = os.getenv("TIKTOK_COOKIES")
|
| 30 |
if not raw_cookies:
|
| 31 |
return ""
|
| 32 |
|
| 33 |
important_cookies = {}
|
|
|
|
| 34 |
target_keys = ["sessionid", "ttwid", "passport_csrf_token", "sid_guard"]
|
| 35 |
|
| 36 |
for line in raw_cookies.splitlines():
|
|
|
|
| 38 |
if not line or line.startswith("#"):
|
| 39 |
continue
|
| 40 |
|
|
|
|
| 41 |
parts = line.split("\t")
|
| 42 |
if len(parts) >= 7:
|
| 43 |
name = parts[5]
|
|
|
|
| 45 |
if name.lower() in target_keys or name.startswith("store-"):
|
| 46 |
important_cookies[name] = value
|
| 47 |
elif "=" in line:
|
|
|
|
| 48 |
pairs = line.split(";")
|
| 49 |
for pair in pairs:
|
| 50 |
if "=" in pair:
|
|
|
|
| 55 |
if important_cookies:
|
| 56 |
return "; ".join([f"{k}={v}" for k, v in important_cookies.items()])
|
| 57 |
|
|
|
|
| 58 |
return raw_cookies[:200] if len(raw_cookies) > 200 else raw_cookies
|
| 59 |
|
| 60 |
# ══════════════════════════════════════════════════════════════════════════════ #
|
|
|
|
| 83 |
print(f"Error updating YouTube title: {e}")
|
| 84 |
|
| 85 |
# ══════════════════════════════════════════════════════════════════════════════ #
|
| 86 |
+
# دالة الإغلاق الاحترافي عبر API (تنهي أي بث معلق تماماً)
|
| 87 |
# ══════════════════════════════════════════════════════════════════════════════ #
|
| 88 |
def finalize_broadcast_via_api():
|
| 89 |
try:
|
| 90 |
if not os.path.exists(TOKEN): return
|
| 91 |
creds = pickle.load(open(TOKEN, "rb"))
|
| 92 |
yt = build('youtube', 'v3', credentials=creds)
|
| 93 |
+
|
| 94 |
+
# جلب البثوث الـ persistent المفتوحة أو المعلقة
|
| 95 |
+
broadcasts = yt.liveBroadcasts().list(broadcastType="persistent", mine=True, part="id,status").execute()
|
| 96 |
if broadcasts.get("items"):
|
| 97 |
+
for item in broadcasts["items"]:
|
| 98 |
+
b_id = item["id"]
|
| 99 |
+
life_status = item["status"].get("lifeCycleStatus")
|
| 100 |
+
|
| 101 |
+
# إذا كان البث في وضع نشط أو جاهز أو معلق، نقوم بإنهائه إجبارياً لتهيئة السيرفر
|
| 102 |
+
if life_status in ["live", "testing", "ready"]:
|
| 103 |
+
try:
|
| 104 |
+
yt.liveBroadcasts().transition(broadcastStatus="complete", id=b_id, part="status").execute()
|
| 105 |
+
print(f"Successfully finalized stuck broadcast: {b_id}")
|
| 106 |
+
except Exception:
|
| 107 |
+
pass
|
| 108 |
+
except Exception as e:
|
| 109 |
+
print(f"Error in finalize_broadcast_via_api: {e}")
|
| 110 |
|
| 111 |
# ══════════════════════════════════════════════════════════════════════════════ #
|
| 112 |
# محرك المراقبة المدمج
|
|
|
|
| 116 |
try: fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 117 |
except: return
|
| 118 |
|
| 119 |
+
# 🔥 التعديل الجوهري: تنظيف وإنهاء أي بث معلق في يوتيوب فور إقلاع السيرفر
|
| 120 |
+
# هذا يغنيك تماماً عن الدخول اليدوي الظاهر في صورة 1000052057.jpg أو عمل إعادة مصنع
|
| 121 |
+
with open(STATUS, "w") as f: json.dump({"live": False, "msg": "جاري تنظيف وتصفير البثوث السابقة..."}, f)
|
| 122 |
+
finalize_broadcast_via_api()
|
| 123 |
+
time.sleep(5) # مهلة قصيرة ليستقر سيرفر يوتيوب بعد الإغلاق
|
| 124 |
+
|
| 125 |
is_streaming = False
|
| 126 |
process = None
|
| 127 |
offline_start_time = None
|
|
|
|
| 143 |
# تحديث عنوان البث على يوتيوب بالتاريخ أولاً
|
| 144 |
update_youtube_broadcast_title()
|
| 145 |
|
|
|
|
| 146 |
cookie_string = get_clean_tiktok_cookies()
|
| 147 |
header_option = f'--http-header "Cookie={cookie_string}"' if cookie_string else ""
|
| 148 |
|
|
|
|
| 149 |
cmd = (
|
| 150 |
f'streamlink --loglevel error {header_option} "https://www.tiktok.com/{TIKTOK_USERNAME}/live" best --hls-live-edge 3 --stdout | '
|
| 151 |
f"ffmpeg -hide_banner -loglevel error -thread_queue_size 8192 -i pipe:0 "
|
|
|
|
| 156 |
)
|
| 157 |
process = subprocess.Popen(cmd, shell=True)
|
| 158 |
is_streaming = True
|
| 159 |
+
with open(STATUS, "w") as f: json.dump({"live": True}, True)
|
| 160 |
|
| 161 |
else:
|
| 162 |
if is_streaming:
|
| 163 |
if offline_start_time is None: offline_start_time = time.time()
|
| 164 |
if time.time() - offline_start_time >= GRACE_PERIOD_SECONDS:
|
| 165 |
if process: process.terminate()
|
| 166 |
+
# إنهاء البث الحالي برمجياً فور انتهاء مهلة غياب المذيع
|
| 167 |
finalize_broadcast_via_api()
|
| 168 |
is_streaming = False
|
| 169 |
offline_start_time = None
|
|
|
|
| 181 |
# ══════════════════════════════════════════════════════════════════════════════ #
|
| 182 |
# الواجهة
|
| 183 |
# ══════════════════════════════════════════════════════════════════════════════ #
|
| 184 |
+
st.set_page_config(page_title="AutoStream Pro", page_icon="📡")
|
| 185 |
st.title("📡 رادار بث أحمد عبدالله - المدمج الاحترافي")
|
| 186 |
|
| 187 |
def get_status():
|