MyanmarSwe commited on
Commit
6c74d1d
·
verified ·
1 Parent(s): edb2588

Create sync.py

Browse files
Files changed (1) hide show
  1. sync.py +120 -0
sync.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, json, requests
2
+ from datetime import datetime
3
+ from pymongo import MongoClient
4
+
5
+ # Environment Variables
6
+ MONGO_URI = os.environ.get("MONGODB_URI")
7
+ TMDB_KEY = os.environ.get("TMDB_API_KEY")
8
+
9
+ # MongoDB Setup
10
+ client = MongoClient(MONGO_URI)
11
+ db = client['myanmarswe_cinema']
12
+ metas_col = db['metas']
13
+ streams_col = db['streams']
14
+ users_col = db['users']
15
+
16
+ def get_tmdb_data(tmdb_id, is_movie=True):
17
+ m_type = "movie" if is_movie else "tv"
18
+ # Append to response ဖြင့် Data အစုံကို တစ်ခါတည်းယူခြင်း
19
+ url = f"https://api.themoviedb.org/3/{m_type}/{tmdb_id}?api_key={TMDB_KEY}&append_to_response=credits,videos,images,recommendations,belongs_to_collection"
20
+
21
+ try:
22
+ res = requests.get(url).json()
23
+ if "id" not in res: return None
24
+
25
+ # Trailer & Media
26
+ trailers = [{"source": v["key"], "type": "Trailer"} for v in res.get("videos", {}).get("results", []) if v["type"] == "Trailer" and v["site"] == "YouTube"][:1]
27
+
28
+ # Runtime Error Handling
29
+ if is_movie:
30
+ run_time = f"{res.get('runtime')} min"
31
+ else:
32
+ ert = res.get('episode_run_time', [])
33
+ run_time = f"{ert[0]} min" if ert else "N/A"
34
+
35
+ # Ultra-Detail Meta Object
36
+ meta = {
37
+ "_id": f"tmdb:{tmdb_id}",
38
+ "id": f"tmdb:{tmdb_id}",
39
+ "type": m_type,
40
+ "name": res.get("title") or res.get("name"),
41
+ "poster": f"https://image.tmdb.org/t/p/w500{res.get('poster_path')}",
42
+ "background": f"https://image.tmdb.org/t/p/original{res.get('backdrop_path')}",
43
+ "logo": f"https://image.tmdb.org/t/p/original{res.get('poster_path')}", # Logo path can be refined
44
+ "description": res.get("overview"),
45
+ "releaseInfo": (res.get("release_date") or res.get("first_air_date", "0000"))[:4],
46
+ "imdbRating": str(res.get("vote_average", "N/A")),
47
+ "runtime": run_time,
48
+ "cast": [c["name"] for c in res.get("credits", {}).get("cast", [])[:10]],
49
+ "genres": [g["name"] for g in res.get("genres", [])],
50
+ "trailers": trailers,
51
+ "recommendations": [str(r["id"]) for r in res.get("recommendations", {}).get("results", [])[:10]],
52
+ "collection_info": res.get("belongs_to_collection"),
53
+ "updated_at": datetime.utcnow() # နောက်ဆုံးထည့်တာ ရှေ့ဆုံးပြဖို့
54
+ }
55
+
56
+ # TV Show Seasons Detail
57
+ if not is_movie:
58
+ videos = []
59
+ for s in res.get("seasons", []):
60
+ s_num = s.get("season_number")
61
+ if s_num == 0: continue
62
+ for e_num in range(1, s.get("episode_count", 0) + 1):
63
+ videos.append({
64
+ "id": f"tmdb:{tmdb_id}:{s_num}:{e_num}",
65
+ "title": f"S{s_num} E{e_num}",
66
+ "season": s_num, "episode": e_num
67
+ })
68
+ meta["videos"] = videos
69
+
70
+ return meta
71
+ except Exception as e:
72
+ print(f"TMDB Error: {e}")
73
+ return None
74
+
75
+ def process_sync(data):
76
+ # 1. Sync Users
77
+ users_list = data.get("users", [])
78
+ if users_list:
79
+ users_col.delete_many({}) # Refresh user list
80
+ users_col.insert_many(users_list)
81
+
82
+ # 2. Sync Movies/Series
83
+ items = data.get("movies_series", [])
84
+ for item in items:
85
+ tid = str(item['tmdb_id'])
86
+ is_movie = (item['type'] == 'movie')
87
+
88
+ # Get Metadata from TMDB
89
+ full_meta = get_tmdb_data(tid, is_movie)
90
+ if full_meta:
91
+ # Custom Overview Override
92
+ if item.get('custom_overview'):
93
+ full_meta['description'] = item['custom_overview']
94
+
95
+ # Save Meta to MongoDB (Update if exists)
96
+ metas_col.update_one({"_id": full_meta["_id"]}, {"$set": full_meta}, upsert=True)
97
+
98
+ # Save Stream URL to Streams Collection
99
+ stream_data = {
100
+ "tmdb_id": tid,
101
+ "type": item['type'],
102
+ "url": item['stream_url'],
103
+ "season": item.get('season'),
104
+ "episode": item.get('episode'),
105
+ "updated_at": datetime.utcnow()
106
+ }
107
+ # Stream တွေကို update လုပ်မယ် (သို့) အသစ်ထည့်မယ်
108
+ streams_col.update_one(
109
+ {"tmdb_id": tid, "season": item.get('season'), "episode": item.get('episode')},
110
+ {"$set": stream_data},
111
+ upsert=True
112
+ )
113
+
114
+ # Smart Collection Logic (If movie belongs to a set)
115
+ if is_movie and full_meta.get("collection_info"):
116
+ col_id = str(full_meta["collection_info"]["id"])
117
+ # Collection Meta ကိုလည်း တစ်ခါတည်း သိမ်းမယ်
118
+ # (ဒီနေရ���မှာ Collection details တွေကို ထပ်ယူတဲ့ logic ထည့်နိုင်ပါတယ်)
119
+
120
+ return {"status": "success"}