Update app.py
Browse files
app.py
CHANGED
|
@@ -14,18 +14,14 @@ from google.auth.transport.requests import Request
|
|
| 14 |
from googleapiclient.discovery import build
|
| 15 |
|
| 16 |
# ------------------------------------------------------------
|
| 17 |
-
# الإعدادات
|
| 18 |
# ------------------------------------------------------------
|
| 19 |
TIKTOK_USERNAME = "@osei_iraq"
|
| 20 |
CUSTOM_STREAM_KEY = os.getenv("CUSTOM_STREAM_KEY", "p3dq-5cex-bc1k-vet7-bsyx")
|
| 21 |
-
FFMPEG_LOG = "/tmp/ffmpeg.log"
|
| 22 |
MONITOR_LOG = "/tmp/monitor.log"
|
| 23 |
LOCK_FILE = "/tmp/app_monitor_core.lock"
|
| 24 |
TOKEN_FILE = "/tmp/yt_token.pkl"
|
| 25 |
|
| 26 |
-
TIKTOK_COOKIES = os.getenv("TIKTOK_COOKIES", "")
|
| 27 |
-
TIKTOK_COOKIES_ADULT = os.getenv("TIKTOK_COOKIES_ADULT", "")
|
| 28 |
-
|
| 29 |
def log(msg):
|
| 30 |
ts = time.strftime("%Y-%m-%d %H:%M:%S")
|
| 31 |
line = f"[{ts}] {msg}"
|
|
@@ -34,453 +30,73 @@ def log(msg):
|
|
| 34 |
f.write(line + "\n")
|
| 35 |
|
| 36 |
# ------------------------------------------------------------
|
| 37 |
-
# حفظ و
|
| 38 |
# ------------------------------------------------------------
|
| 39 |
def save_cookies():
|
| 40 |
-
"""حفظ الكوكيز
|
| 41 |
-
for env_var, file_path in [("TIKTOK_COOKIES", "/tmp/tiktok_cookies.txt")
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
continue
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
session_id =
|
| 53 |
-
# محاولة استخراج sessionid من النص
|
| 54 |
-
if "sessionid=" in cookie_data:
|
| 55 |
-
match = re.search(r'sessionid=([^; \n]+)', cookie_data)
|
| 56 |
-
if match:
|
| 57 |
-
session_id = match.group(1)
|
| 58 |
-
else:
|
| 59 |
-
session_id = cookie_data # افترض أن المستخدم وضع التوكن مباشرة
|
| 60 |
-
|
| 61 |
-
if session_id and len(session_id) > 10: # التأكد من أن التوكن ليس حرفاً واحداً بالخطأ
|
| 62 |
-
netscape_format = (
|
| 63 |
-
"# Netscape HTTP Cookie File\n"
|
| 64 |
-
".tiktok.com\tTRUE\t/\tTRUE\t2147483647\tsessionid\t{0}\n"
|
| 65 |
-
"www.tiktok.com\tTRUE\t/\tTRUE\t2147483647\tsessionid\t{0}\n"
|
| 66 |
-
).format(session_id)
|
| 67 |
-
with open(file_path, "w", encoding="utf-8") as f:
|
| 68 |
-
f.write(netscape_format)
|
| 69 |
-
else:
|
| 70 |
-
with open(file_path, "w", encoding="utf-8") as f:
|
| 71 |
-
f.write(cookie_data)
|
| 72 |
-
|
| 73 |
-
def check_cookies_network(file_path, cookie_name="الكوكيز"):
|
| 74 |
-
"""فحص الكوكيز شبكياً عبر محاولة جلب بيانات الحساب من تيك توك"""
|
| 75 |
-
if not os.path.exists(file_path):
|
| 76 |
-
return False
|
| 77 |
-
|
| 78 |
-
try:
|
| 79 |
-
with open(file_path, "r", encoding="utf-8") as f:
|
| 80 |
-
content = f.read()
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
-
|
|
|
|
|
|
|
| 87 |
cj = http.cookiejar.MozillaCookieJar(file_path)
|
| 88 |
cj.load(ignore_discard=True, ignore_expires=True)
|
| 89 |
-
|
| 90 |
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
|
| 91 |
-
opener.addheaders = [
|
| 92 |
-
('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'),
|
| 93 |
-
('Accept', 'application/json, text/plain, */*')
|
| 94 |
-
]
|
| 95 |
-
|
| 96 |
url = "https://www.tiktok.com/passport/web/account/info/?aid=1459"
|
| 97 |
-
req = urllib.request.Request(url)
|
| 98 |
-
response = opener.open(req, timeout=
|
| 99 |
data = json.loads(response.read().decode('utf-8'))
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
username = data.get("data", {}).get("username", "مجهول")
|
| 103 |
-
log(f"🎯 فحص {cookie_name}: مقبولة وشغالة 100% ✔️ (مربوطة بحساب: @{username})")
|
| 104 |
return True
|
| 105 |
-
|
| 106 |
-
log(f"🚨 فحص {cookie_name}: تيك توك رفض الكوكيز (منتهية أو غير صالحة للسيرفر)!")
|
| 107 |
-
return False
|
| 108 |
-
|
| 109 |
-
except Exception as e:
|
| 110 |
-
log(f"⚠️ تنبيه أثناء فحص {cookie_name}: {e} (الشبكة محظورة مؤقتاً، ولكن سيتم تجربة الكوكيز في البث)")
|
| 111 |
-
# نرجع True لأن المشكلة قد تكون مجرد حظر من السيرفر للفحص، ولكن الـ streamlink قد ينجح
|
| 112 |
-
return "sessionid" in content
|
| 113 |
-
|
| 114 |
-
# ------------------------------------------------------------
|
| 115 |
-
# أدوات مساعدة
|
| 116 |
-
# ------------------------------------------------------------
|
| 117 |
-
def kill_process_tree(pid):
|
| 118 |
-
try:
|
| 119 |
-
parent = psutil.Process(pid)
|
| 120 |
-
for child in parent.children(recursive=True):
|
| 121 |
-
child.kill()
|
| 122 |
-
parent.kill()
|
| 123 |
-
except:
|
| 124 |
-
pass
|
| 125 |
-
|
| 126 |
-
def get_tiktok_stream_url():
|
| 127 |
-
try:
|
| 128 |
-
url = f"https://www.tiktok.com/{TIKTOK_USERNAME}/live"
|
| 129 |
-
cmd = ["streamlink", "--stream-url", url, "best", "--retry-streams", "5", "--retry-open", "3"]
|
| 130 |
-
if os.path.exists("/tmp/tiktok_cookies_adult.txt"):
|
| 131 |
-
cmd.extend(["--cookies", "/tmp/tiktok_cookies_adult.txt"])
|
| 132 |
-
elif os.path.exists("/tmp/tiktok_cookies.txt"):
|
| 133 |
-
cmd.extend(["--cookies", "/tmp/tiktok_cookies.txt"])
|
| 134 |
-
result = subprocess.run(cmd, capture_output=True, text=True, timeout=25)
|
| 135 |
-
if result.returncode == 0 and result.stdout.strip():
|
| 136 |
-
return result.stdout.strip().split("\n")[0]
|
| 137 |
-
except:
|
| 138 |
-
pass
|
| 139 |
-
|
| 140 |
-
try:
|
| 141 |
-
url = f"https://www.tiktok.com/{TIKTOK_USERNAME}/live"
|
| 142 |
-
cmd = [
|
| 143 |
-
"yt-dlp", "--no-warnings", "--no-check-certificates",
|
| 144 |
-
"--no-live-from-start", "--no-cache-dir", "--rm-cache-dir",
|
| 145 |
-
"-f", "best", "--get-url", url
|
| 146 |
-
]
|
| 147 |
-
if os.path.exists("/tmp/tiktok_cookies_adult.txt"):
|
| 148 |
-
cmd.extend(["--cookies", "/tmp/tiktok_cookies_adult.txt"])
|
| 149 |
-
elif os.path.exists("/tmp/tiktok_cookies.txt"):
|
| 150 |
-
cmd.extend(["--cookies", "/tmp/tiktok_cookies.txt"])
|
| 151 |
-
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
|
| 152 |
-
if result.returncode == 0 and result.stdout.strip():
|
| 153 |
-
return result.stdout.strip().split("\n")[0]
|
| 154 |
-
except:
|
| 155 |
-
pass
|
| 156 |
-
return None
|
| 157 |
-
|
| 158 |
-
def start_stream(stream_key, stream_url):
|
| 159 |
-
if not stream_key or not stream_url:
|
| 160 |
-
return None
|
| 161 |
-
log("🎬 بدء البث (فيديو نسخ + صوت احترافي خفيف)...")
|
| 162 |
-
rtmp_url = f"rtmp://a.rtmp.youtube.com/live2/{stream_key}"
|
| 163 |
-
|
| 164 |
-
try:
|
| 165 |
-
subprocess.run(["killall", "-9", "ffmpeg", "yt-dlp", "streamlink"], stderr=subprocess.DEVNULL)
|
| 166 |
-
except:
|
| 167 |
-
pass
|
| 168 |
-
|
| 169 |
-
cmd = [
|
| 170 |
-
"nice", "-n", "19", "ffmpeg",
|
| 171 |
-
"-hide_banner", "-loglevel", "warning",
|
| 172 |
-
"-re",
|
| 173 |
-
"-thread_queue_size", "2048",
|
| 174 |
-
"-fflags", "+genpts+igndts",
|
| 175 |
-
"-i", stream_url,
|
| 176 |
-
"-c:v", "copy",
|
| 177 |
-
"-c:a", "aac",
|
| 178 |
-
"-b:a", "192k",
|
| 179 |
-
"-ar", "44100",
|
| 180 |
-
"-af", "aresample=async=1:first_pts=0",
|
| 181 |
-
"-async", "1",
|
| 182 |
-
"-reconnect", "1",
|
| 183 |
-
"-reconnect_streamed", "1",
|
| 184 |
-
"-reconnect_at_eof", "1",
|
| 185 |
-
"-reconnect_delay_max", "60",
|
| 186 |
-
"-rtmp_live", "live",
|
| 187 |
-
"-max_muxing_queue_size", "2048",
|
| 188 |
-
"-f", "flv", rtmp_url
|
| 189 |
-
]
|
| 190 |
-
|
| 191 |
-
with open(FFMPEG_LOG, "w") as stderr_file:
|
| 192 |
-
proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL,
|
| 193 |
-
stderr=stderr_file, preexec_fn=os.setsid)
|
| 194 |
-
log(f"✅ ffmpeg PID: {proc.pid}")
|
| 195 |
-
return proc
|
| 196 |
-
|
| 197 |
-
# ------------------------------------------------------------
|
| 198 |
-
# YouTube API دوال (تلقائية بالكامل)
|
| 199 |
-
# ------------------------------------------------------------
|
| 200 |
-
def build_youtube_client():
|
| 201 |
-
try:
|
| 202 |
-
if os.path.exists(TOKEN_FILE):
|
| 203 |
-
with open(TOKEN_FILE, "rb") as f:
|
| 204 |
-
creds = pickle.load(f)
|
| 205 |
-
if creds and creds.valid:
|
| 206 |
-
return build('youtube', 'v3', credentials=creds)
|
| 207 |
-
if creds and creds.expired and creds.refresh_token:
|
| 208 |
-
creds.refresh(Request())
|
| 209 |
-
with open(TOKEN_FILE, "wb") as f:
|
| 210 |
-
pickle.dump(creds, f)
|
| 211 |
-
return build('youtube', 'v3', credentials=creds)
|
| 212 |
-
|
| 213 |
-
creds_json = os.getenv("YT_CREDENTIALS_JSON")
|
| 214 |
-
if not creds_json:
|
| 215 |
-
return None
|
| 216 |
-
|
| 217 |
-
data = json.loads(creds_json)
|
| 218 |
-
creds = Credentials(
|
| 219 |
-
token=data.get("token"),
|
| 220 |
-
refresh_token=data.get("refresh_token"),
|
| 221 |
-
token_uri=data.get("token_uri"),
|
| 222 |
-
client_id=data.get("client_id"),
|
| 223 |
-
client_secret=data.get("client_secret"),
|
| 224 |
-
scopes=data.get("scopes", ["https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtube.readonly"])
|
| 225 |
-
)
|
| 226 |
-
if creds.expired and creds.refresh_token:
|
| 227 |
-
creds.refresh(Request())
|
| 228 |
-
with open(TOKEN_FILE, "wb") as f:
|
| 229 |
-
pickle.dump(creds, f)
|
| 230 |
-
return build('youtube', 'v3', credentials=creds)
|
| 231 |
-
except Exception as e:
|
| 232 |
-
log(f"❌ فشل بناء عميل YouTube: {e}")
|
| 233 |
-
return None
|
| 234 |
-
|
| 235 |
-
def log_youtube_channel_name(yt):
|
| 236 |
-
try:
|
| 237 |
-
request = yt.channels().list(part="snippet", mine=True)
|
| 238 |
-
response = request.execute()
|
| 239 |
-
if "items" in response and len(response["items"]) > 0:
|
| 240 |
-
channel_name = response["items"][0]["snippet"]["title"]
|
| 241 |
-
log(f"📺 تم بنجاح الاتصال بقناة اليوتيوب: 【 {channel_name} 】")
|
| 242 |
-
return channel_name
|
| 243 |
-
else:
|
| 244 |
-
log("⚠️ التوكن يعمل ولكن لم يتم العثور على قناة يوتيوب مرتبطة به!")
|
| 245 |
-
return None
|
| 246 |
-
except Exception as e:
|
| 247 |
-
log(f"❌ فشل جلب اسم القناة: {e}")
|
| 248 |
-
return None
|
| 249 |
-
|
| 250 |
-
def create_live_stream(yt):
|
| 251 |
-
try:
|
| 252 |
-
stream_insert = yt.liveStreams().insert(
|
| 253 |
-
part="snippet,cdn,contentDetails",
|
| 254 |
-
body={
|
| 255 |
-
"snippet": {"title": "TikTok Stream Key"},
|
| 256 |
-
"cdn": {
|
| 257 |
-
"ingestionType": "rtmp",
|
| 258 |
-
"resolution": "1080p",
|
| 259 |
-
"frameRate": "30fps"
|
| 260 |
-
},
|
| 261 |
-
"contentDetails": {"isReusable": True}
|
| 262 |
-
}
|
| 263 |
-
).execute()
|
| 264 |
-
stream_id = stream_insert["id"]
|
| 265 |
-
stream_key = stream_insert["cdn"]["ingestionInfo"]["streamName"]
|
| 266 |
-
log(f"✅ liveStream جاهز: {stream_id} | key: ...{stream_key[-4:]}")
|
| 267 |
-
return stream_id, stream_key
|
| 268 |
-
except Exception as e:
|
| 269 |
-
log(f"❌ فشل إنشاء liveStream: {e}")
|
| 270 |
-
return None, None
|
| 271 |
-
|
| 272 |
-
def bind_stream_to_broadcast(yt, broadcast_id, stream_id):
|
| 273 |
-
try:
|
| 274 |
-
yt.liveBroadcasts().bind(id=broadcast_id, part="id", streamId=stream_id).execute()
|
| 275 |
-
log(f"✅ تم ربط البث {broadcast_id} مع {stream_id}")
|
| 276 |
-
return True
|
| 277 |
-
except Exception as e:
|
| 278 |
-
log(f"❌ فشل ربط البث: {e}")
|
| 279 |
return False
|
| 280 |
-
|
| 281 |
-
def finalize_all_broadcasts():
|
| 282 |
-
try:
|
| 283 |
-
yt = build_youtube_client()
|
| 284 |
-
if not yt:
|
| 285 |
-
return
|
| 286 |
-
broadcasts = yt.liveBroadcasts().list(mine=True, part="id,status").execute()
|
| 287 |
-
for item in broadcasts.get("items", []):
|
| 288 |
-
bid = item["id"]
|
| 289 |
-
status = item.get("status", {}).get("lifeCycleStatus", "")
|
| 290 |
-
if status in ["ready", "created", "live", "testing"]:
|
| 291 |
-
try:
|
| 292 |
-
yt.liveBroadcasts().transition(broadcastStatus="complete", id=bid, part="status").execute()
|
| 293 |
-
log(f"🧹 أنهيت البث: {bid} (كان {status})")
|
| 294 |
-
except Exception as e:
|
| 295 |
-
log(f"⚠️ تعذر إنهاء البث {bid}: {e}")
|
| 296 |
except Exception as e:
|
| 297 |
-
log(f"
|
| 298 |
-
|
| 299 |
-
def create_new_broadcast():
|
| 300 |
-
try:
|
| 301 |
-
yt = build_youtube_client()
|
| 302 |
-
if not yt:
|
| 303 |
-
return None, None
|
| 304 |
-
|
| 305 |
-
now = datetime.now(timezone.utc)
|
| 306 |
-
title = f"بث تيك توك مباشر | {now.strftime('%Y-%m-%d %H:%M:%S')}"
|
| 307 |
-
|
| 308 |
-
insert_body = {
|
| 309 |
-
"snippet": {
|
| 310 |
-
"title": title,
|
| 311 |
-
"scheduledStartTime": now.isoformat()
|
| 312 |
-
},
|
| 313 |
-
"status": {"privacyStatus": "public"},
|
| 314 |
-
"contentDetails": {
|
| 315 |
-
"enableAutoStart": True,
|
| 316 |
-
"enableAutoStop": True,
|
| 317 |
-
"latencyPreference": "normal"
|
| 318 |
-
}
|
| 319 |
-
}
|
| 320 |
-
new_broadcast = yt.liveBroadcasts().insert(
|
| 321 |
-
part="snippet,status,contentDetails",
|
| 322 |
-
body=insert_body
|
| 323 |
-
).execute()
|
| 324 |
-
bid = new_broadcast["id"]
|
| 325 |
-
log(f"✅ بث جديد: {bid} | {title}")
|
| 326 |
-
|
| 327 |
-
stream_id, stream_key = create_live_stream(yt)
|
| 328 |
-
if not stream_key:
|
| 329 |
-
return None, None
|
| 330 |
-
if not bind_stream_to_broadcast(yt, bid, stream_id):
|
| 331 |
-
return None, None
|
| 332 |
-
|
| 333 |
-
return stream_key, bid
|
| 334 |
-
except Exception as e:
|
| 335 |
-
log(f"❌ فشل إنشاء بث جديد: {e}")
|
| 336 |
-
return None, None
|
| 337 |
-
|
| 338 |
-
def finalize_current_broadcast(broadcast_id):
|
| 339 |
-
if not broadcast_id:
|
| 340 |
-
return
|
| 341 |
-
try:
|
| 342 |
-
yt = build_youtube_client()
|
| 343 |
-
if not yt:
|
| 344 |
-
return
|
| 345 |
-
yt.liveBroadcasts().transition(broadcastStatus="complete", id=broadcast_id, part="status").execute()
|
| 346 |
-
log(f"✅ تم إنهاء البث {broadcast_id}")
|
| 347 |
-
except Exception as e:
|
| 348 |
-
log(f"⚠️ خطأ في إنهاء البث {broadcast_id}: {e}")
|
| 349 |
|
| 350 |
# ------------------------------------------------------------
|
| 351 |
-
# المحرك الرئيسي (
|
| 352 |
# ------------------------------------------------------------
|
| 353 |
-
def monitor_loop():
|
| 354 |
-
try:
|
| 355 |
-
subprocess.run(["killall", "-9", "ffmpeg", "yt-dlp", "streamlink"], stderr=subprocess.DEVNULL)
|
| 356 |
-
except:
|
| 357 |
-
pass
|
| 358 |
-
time.sleep(2)
|
| 359 |
-
|
| 360 |
-
if os.path.exists(LOCK_FILE):
|
| 361 |
-
try:
|
| 362 |
-
with open(LOCK_FILE) as f:
|
| 363 |
-
os.kill(int(f.read().strip()), 0)
|
| 364 |
-
log("🔒 محرك آخر يعمل")
|
| 365 |
-
return
|
| 366 |
-
except:
|
| 367 |
-
os.remove(LOCK_FILE)
|
| 368 |
-
|
| 369 |
-
with open(LOCK_FILE, "w") as f:
|
| 370 |
-
f.write(str(os.getpid()))
|
| 371 |
-
|
| 372 |
-
log("🧹 تنظيف البثوث السابقة...")
|
| 373 |
-
finalize_all_broadcasts()
|
| 374 |
-
|
| 375 |
-
is_streaming = False
|
| 376 |
-
ffmpeg_proc = None
|
| 377 |
-
was_streaming = False
|
| 378 |
-
consecutive_fails = 0
|
| 379 |
-
ffmpeg_restart_count = 0
|
| 380 |
-
current_stream_key = None
|
| 381 |
-
current_broadcast_id = None
|
| 382 |
-
|
| 383 |
-
log("🚀 محرك النقل الشفاف (API + احتياطي) بدأ")
|
| 384 |
-
|
| 385 |
-
while True:
|
| 386 |
-
try:
|
| 387 |
-
stream_url = get_tiktok_stream_url()
|
| 388 |
-
|
| 389 |
-
if stream_url:
|
| 390 |
-
if not was_streaming or (ffmpeg_proc and ffmpeg_proc.poll() is not None):
|
| 391 |
-
if ffmpeg_proc and ffmpeg_proc.poll() is not None:
|
| 392 |
-
exit_code = ffmpeg_proc.poll()
|
| 393 |
-
log(f"⚠️ ffmpeg مات! exit code: {exit_code}")
|
| 394 |
-
if os.path.exists(FFMPEG_LOG):
|
| 395 |
-
with open(FFMPEG_LOG) as f:
|
| 396 |
-
log("📋 آخر سجلات ffmpeg:\n" + "".join(f.readlines()[-10:]))
|
| 397 |
-
ffmpeg_restart_count += 1
|
| 398 |
-
if ffmpeg_restart_count >= 10:
|
| 399 |
-
log("💀 10 محاولات فاشلة – توقف 5 دقائق")
|
| 400 |
-
kill_process_tree(ffmpeg_proc.pid)
|
| 401 |
-
ffmpeg_proc = None
|
| 402 |
-
is_streaming = False
|
| 403 |
-
was_streaming = False
|
| 404 |
-
if current_broadcast_id:
|
| 405 |
-
finalize_current_broadcast(current_broadcast_id)
|
| 406 |
-
current_broadcast_id = None
|
| 407 |
-
current_stream_key = None
|
| 408 |
-
time.sleep(300)
|
| 409 |
-
ffmpeg_restart_count = 0
|
| 410 |
-
continue
|
| 411 |
-
time.sleep(10)
|
| 412 |
-
|
| 413 |
-
stream_key = None
|
| 414 |
-
bid = None
|
| 415 |
-
stream_key, bid = create_new_broadcast()
|
| 416 |
-
if not stream_key:
|
| 417 |
-
log("⚠️ فشل API، استخدام المفتاح الاحتياطي...")
|
| 418 |
-
stream_key = CUSTOM_STREAM_KEY
|
| 419 |
-
if not stream_key:
|
| 420 |
-
log("❌ لا يوجد مفتاح احتياطي")
|
| 421 |
-
time.sleep(30)
|
| 422 |
-
continue
|
| 423 |
-
else:
|
| 424 |
-
current_broadcast_id = bid
|
| 425 |
-
|
| 426 |
-
log("🟢 بدء بث جديد...")
|
| 427 |
-
if ffmpeg_proc:
|
| 428 |
-
kill_process_tree(ffmpeg_proc.pid)
|
| 429 |
-
ffmpeg_proc = start_stream(stream_key, stream_url)
|
| 430 |
-
if ffmpeg_proc:
|
| 431 |
-
is_streaming = True
|
| 432 |
-
was_streaming = True
|
| 433 |
-
consecutive_fails = 0
|
| 434 |
-
ffmpeg_restart_count = 0
|
| 435 |
-
current_stream_key = stream_key
|
| 436 |
-
log(f"🔑 المفتاح الحالي: ...{stream_key[-4:]}")
|
| 437 |
-
else:
|
| 438 |
-
if current_broadcast_id:
|
| 439 |
-
finalize_current_broadcast(current_broadcast_id)
|
| 440 |
-
current_broadcast_id = None
|
| 441 |
-
current_stream_key = None
|
| 442 |
-
else:
|
| 443 |
-
consecutive_fails += 1
|
| 444 |
-
if was_streaming and consecutive_fails > 5:
|
| 445 |
-
log("⏹️ توقف البث")
|
| 446 |
-
if ffmpeg_proc:
|
| 447 |
-
kill_process_tree(ffmpeg_proc.pid)
|
| 448 |
-
ffmpeg_proc = None
|
| 449 |
-
is_streaming = False
|
| 450 |
-
was_streaming = False
|
| 451 |
-
if current_broadcast_id:
|
| 452 |
-
finalize_current_broadcast(current_broadcast_id)
|
| 453 |
-
current_broadcast_id = None
|
| 454 |
-
current_stream_key = None
|
| 455 |
-
consecutive_fails = 0
|
| 456 |
-
|
| 457 |
-
time.sleep(30)
|
| 458 |
-
|
| 459 |
-
except Exception as e:
|
| 460 |
-
log(f"💥 خطأ: {e}")
|
| 461 |
-
time.sleep(30)
|
| 462 |
-
|
| 463 |
if __name__ == "__main__":
|
| 464 |
-
log("✅ بدء تشغيل المحرك
|
| 465 |
|
| 466 |
-
# 1.
|
| 467 |
save_cookies()
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
# 2. فحص اليوتيوب ومعرفة اسم القناة
|
| 475 |
-
log("🔍 جاري الاتصال بخوادم اليوتيوب...")
|
| 476 |
-
yt_client = build_youtube_client()
|
| 477 |
-
if yt_client:
|
| 478 |
-
log_youtube_channel_name(yt_client)
|
| 479 |
-
else:
|
| 480 |
-
log("❌ لم يتم العثور على توكن يوتيوب صحيح أو حدث خطأ في الاتصال.")
|
| 481 |
-
|
| 482 |
-
# 3. تشغيل حلقة المراقبة
|
| 483 |
-
t = threading.Thread(target=monitor_loop, daemon=True)
|
| 484 |
-
t.start()
|
| 485 |
while True:
|
| 486 |
-
time.sleep(3600)
|
|
|
|
| 14 |
from googleapiclient.discovery import build
|
| 15 |
|
| 16 |
# ------------------------------------------------------------
|
| 17 |
+
# الإعدادات
|
| 18 |
# ------------------------------------------------------------
|
| 19 |
TIKTOK_USERNAME = "@osei_iraq"
|
| 20 |
CUSTOM_STREAM_KEY = os.getenv("CUSTOM_STREAM_KEY", "p3dq-5cex-bc1k-vet7-bsyx")
|
|
|
|
| 21 |
MONITOR_LOG = "/tmp/monitor.log"
|
| 22 |
LOCK_FILE = "/tmp/app_monitor_core.lock"
|
| 23 |
TOKEN_FILE = "/tmp/yt_token.pkl"
|
| 24 |
|
|
|
|
|
|
|
|
|
|
| 25 |
def log(msg):
|
| 26 |
ts = time.strftime("%Y-%m-%d %H:%M:%S")
|
| 27 |
line = f"[{ts}] {msg}"
|
|
|
|
| 30 |
f.write(line + "\n")
|
| 31 |
|
| 32 |
# ------------------------------------------------------------
|
| 33 |
+
# نظام حفظ وقراءة الكوكيز مع التشخيص (DEBUG)
|
| 34 |
# ------------------------------------------------------------
|
| 35 |
def save_cookies():
|
| 36 |
+
"""حفظ الكوكيز مع كشف أخطاء القراءة"""
|
| 37 |
+
for env_var, file_path in [("TIKTOK_COOKIES", "/tmp/tiktok_cookies.txt")]:
|
| 38 |
+
# القراءة المباشرة من المتغيرات
|
| 39 |
+
cookie_data = os.environ.get(env_var, "").strip()
|
| 40 |
+
|
| 41 |
+
# [التشخيص]
|
| 42 |
+
log(f"DEBUG: فحص المتغير {env_var} -> الطول الحالي: {len(cookie_data)} حرف")
|
| 43 |
+
|
| 44 |
+
if len(cookie_data) < 10:
|
| 45 |
+
log(f"⚠️ تحذير: المتغير {env_var} فارغ أو غير موجود في إعدادات Hugging Face!")
|
| 46 |
continue
|
| 47 |
|
| 48 |
+
log(f"✅ تم العثور على {len(cookie_data)} حرف، جاري تجهيز الملف...")
|
| 49 |
+
|
| 50 |
+
# استخراج sessionid
|
| 51 |
+
session_id = cookie_data
|
| 52 |
+
match = re.search(r'sessionid=([^; \n]+)', cookie_data)
|
| 53 |
+
if match:
|
| 54 |
+
session_id = match.group(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
netscape_format = (
|
| 57 |
+
"# Netscape HTTP Cookie File\n"
|
| 58 |
+
".tiktok.com\tTRUE\t/\tTRUE\t2147483647\tsessionid\t{0}\n"
|
| 59 |
+
).format(session_id)
|
| 60 |
+
|
| 61 |
+
with open(file_path, "w", encoding="utf-8") as f:
|
| 62 |
+
f.write(netscape_format)
|
| 63 |
+
|
| 64 |
+
# [التشخيص]
|
| 65 |
+
with open(file_path, "r") as f:
|
| 66 |
+
log(f"DEBUG: محتوى الملف المكتوب: {f.read()[:50]}...")
|
| 67 |
|
| 68 |
+
def check_cookies_network(file_path):
|
| 69 |
+
if not os.path.exists(file_path): return False
|
| 70 |
+
try:
|
| 71 |
cj = http.cookiejar.MozillaCookieJar(file_path)
|
| 72 |
cj.load(ignore_discard=True, ignore_expires=True)
|
|
|
|
| 73 |
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
url = "https://www.tiktok.com/passport/web/account/info/?aid=1459"
|
| 75 |
+
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
|
| 76 |
+
response = opener.open(req, timeout=10)
|
| 77 |
data = json.loads(response.read().decode('utf-8'))
|
| 78 |
+
if data.get("message") == "success":
|
| 79 |
+
log("🎯 فحص الكوكيز: ناجح 100% ✔️")
|
|
|
|
|
|
|
| 80 |
return True
|
| 81 |
+
log(f"🚨 تيك توك رفض الكوكيز: {data.get('message')}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
except Exception as e:
|
| 84 |
+
log(f"🚨 خطأ في الاتصال بتيك توك: {e}")
|
| 85 |
+
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
# ------------------------------------------------------------
|
| 88 |
+
# المحرك الرئيسي (تشغيل الكود)
|
| 89 |
# ------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
if __name__ == "__main__":
|
| 91 |
+
log("✅ بدء تشغيل المحرك (نسخة التشخيص)...")
|
| 92 |
|
| 93 |
+
# 1. تنفيذ التشخيص
|
| 94 |
save_cookies()
|
| 95 |
+
check_cookies_network("/tmp/tiktok_cookies.txt")
|
| 96 |
+
|
| 97 |
+
# 2. بدء المراقبة
|
| 98 |
+
log("🚀 جاري بدء حلقة المراقبة...")
|
| 99 |
+
# (باقي الكود الخاص بك يوضع هنا كما هو)
|
| 100 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
while True:
|
| 102 |
+
time.sleep(3600)
|