MyanmarSwe commited on
Commit
9f12ce1
·
verified ·
1 Parent(s): d52d0f9

Update sync.py

Browse files
Files changed (1) hide show
  1. sync.py +59 -96
sync.py CHANGED
@@ -1,4 +1,4 @@
1
- import os, json, requests
2
  from datetime import datetime
3
  from pymongo import MongoClient
4
 
@@ -7,131 +7,94 @@ TMDB_KEY = os.environ.get("TMDB_API_KEY")
7
 
8
  client = MongoClient(MONGO_URI)
9
  db = client['myanmarswe_cinema']
10
- metas_col, streams_col, users_col = db['metas'], db['streams'], db['users']
11
 
12
  def get_tmdb_data(tmdb_id, m_type):
13
  tmdb_type = "movie" if m_type == "movie" else "tv"
 
14
  url = f"https://api.themoviedb.org/3/{tmdb_type}/{tmdb_id}?api_key={TMDB_KEY}&append_to_response=credits,videos,images,recommendations,belongs_to_collection"
15
 
16
  try:
17
  res = requests.get(url).json()
18
  if "id" not in res: return None
19
 
20
- logo_url = None
21
- images = res.get("images", {})
22
- logos = images.get("logos", [])
23
- if logos:
24
- en_logos = [l for l in logos if l.get("iso_639_1") == "en"]
25
- logo_path = en_logos[0]["file_path"] if en_logos else logos[0]["file_path"]
26
- logo_url = f"https://image.tmdb.org/t/p/w500{logo_path}"
27
-
28
- # --- Cast & Crew Explicit Data Casting Fix ---
29
  credits = res.get("credits", {})
30
- cast_list = credits.get("cast", [])
31
- cast = [str(c.get("name")) for c in cast_list[:15] if c.get("name")]
32
-
33
- crew_list = credits.get("crew", [])
34
- directors = [str(c.get("name")) for c in crew_list if c.get("job") == "Director" and c.get("name")]
35
-
36
- if m_type == "series" and not directors:
37
- creator_list = res.get("created_by", [])
38
- directors = [str(c.get("name")) for c in creator_list if c.get("name")]
39
-
40
- run_t = res.get("runtime") if m_type == "movie" else (res.get("episode_run_time", [None])[0] if res.get("episode_run_time") else None)
41
- runtime_str = f"{run_t} min" if run_t else "N/A"
42
 
43
  meta = {
44
  "_id": f"tmdb:{tmdb_id}",
45
  "id": f"tmdb:{tmdb_id}",
46
  "type": m_type,
47
- "name": res.get("title") or res.get("name") or "Unknown",
48
- "poster": f"https://image.tmdb.org/t/p/w500{res.get('poster_path')}" if res.get('poster_path') else None,
49
- "background": f"https://image.tmdb.org/t/p/original{res.get('backdrop_path')}" if res.get('backdrop_path') else None,
50
- "logo": logo_url,
51
  "description": res.get("overview") or "",
52
  "releaseInfo": str((res.get("release_date") or res.get("first_air_date", "0000"))[:4]),
53
- "imdbRating": "{:.1f}".format(res.get("vote_average", 0)) if res.get("vote_average") else "N/A",
54
- "runtime": runtime_str,
55
- "cast": cast if cast else ["Unknown Actor"], # Error ကာကွယ်ရန် Fallback ထည့်ထားခြင်း
56
- "director": directors if directors else ["Unknown Director"],
57
  "genres": [g["name"] for g in res.get("genres", [])],
58
- "trailers": [{"source": v["key"], "type": "Trailer"} for v in res.get("videos", {}).get("results", []) if v["type"] == "Trailer" and v["site"] == "YouTube"][:1],
59
- "recommendations": [str(r["id"]) for r in res.get("recommendations", {}).get("results", [])[:10]],
60
- "collection_info": res.get("belongs_to_collection"),
61
  "updated_at": datetime.utcnow()
62
  }
63
 
 
64
  if m_type == "series":
65
  videos = []
66
- first_air = res.get("first_air_date")
67
- rel_date = f"{first_air}T00:00:00.000Z" if first_air else "2000-01-01T00:00:00.000Z"
68
-
69
  for s in res.get("seasons", []):
70
  s_num = s.get("season_number")
71
  if s_num == 0: continue
72
- for e_num in range(1, s.get("episode_count", 0) + 1):
 
 
 
73
  videos.append({
74
- "id": f"tmdb:{tmdb_id}:{s_num}:{e_num}",
75
- "title": f"S{s_num} E{e_num}",
76
- "season": s_num, "episode": e_num,
77
- "released": rel_date
 
 
78
  })
79
  meta["videos"] = videos
80
 
81
- # --- Smart Collection Processing with Strict Series ID Format ---
82
- if meta.get("collection_info"):
83
- col_id = meta["collection_info"]["id"]
84
- col_url = f"https://api.themoviedb.org/3/collection/{col_id}?api_key={TMDB_KEY}"
85
- col_res = requests.get(col_url).json()
86
- if "id" in col_res:
87
- col_videos = []
88
- for i, p in enumerate(col_res.get("parts", [])):
89
- p_date = p.get("release_date")
90
- c_rel_date = f"{p_date}T00:00:00.000Z" if p_date else "2000-01-01T00:00:00.000Z"
91
- col_videos.append({
92
- "id": f"tmdb_col:{col_id}:1:{i+1}", # Stremio Series Standard အတိုင်း ID Format ပြောင်းလဲခြင်း
93
- "movie_id": str(p['id']), # Stream ရှာရန် မူရင်း Movie ID ကို ခေတ္တသိမ်းထားခြင်း
94
- "title": p.get('title') or f"Part {i+1}",
95
- "season": 1,
96
- "episode": i+1,
97
- "released": c_rel_date
98
- })
 
 
99
 
100
- col_meta = {
101
- "_id": f"tmdb_col:{col_id}",
102
- "id": f"tmdb_col:{col_id}",
103
- "type": "series",
104
- "name": col_res.get("name") or "Collection",
105
- "poster": f"https://image.tmdb.org/t/p/w500{col_res.get('poster_path')}" if col_res.get('poster_path') else "https://via.placeholder.com/500x750?text=No+Poster",
106
- "background": f"https://image.tmdb.org/t/p/original{col_res.get('backdrop_path')}" if col_res.get('backdrop_path') else "https://via.placeholder.com/1280x720?text=No+Background",
107
- "description": col_res.get("overview") or "No description available.",
108
- "cast": [],
109
- "director": [],
110
- "genres": ["Collection"],
111
- "videos": col_videos,
112
- "updated_at": datetime.utcnow()
113
- }
114
- metas_col.update_one({"id": col_meta["id"]}, {"$set": col_meta}, upsert=True)
115
 
116
  return meta
117
- except Exception as e:
118
- print(f"Error fetching TMDB: {e}")
119
- return None
120
-
121
- def process_sync(data):
122
- if data.get("users"):
123
- users_col.delete_many({})
124
- users_col.insert_many(data["users"])
125
-
126
- items = data.get("movies_series", [])
127
- for item in items:
128
- tid, m_type = str(item['tmdb_id']), item['type']
129
- full_meta = get_tmdb_data(tid, m_type)
130
- if full_meta:
131
- if item.get('custom_overview'): full_meta['description'] = item['custom_overview']
132
- metas_col.update_one({"id": full_meta["id"]}, {"$set": full_meta}, upsert=True)
133
-
134
- s_query = {"tmdb_id": tid, "season": item.get('season'), "episode": item.get('episode')}
135
- s_data = {**s_query, "type": m_type, "url": item['stream_url'], "updated_at": datetime.utcnow()}
136
- streams_col.update_one(s_query, {"$set": s_data}, upsert=True)
137
- return {"status": "success"}
 
1
+ import os, requests
2
  from datetime import datetime
3
  from pymongo import MongoClient
4
 
 
7
 
8
  client = MongoClient(MONGO_URI)
9
  db = client['myanmarswe_cinema']
10
+ metas_col = db['metas']
11
 
12
  def get_tmdb_data(tmdb_id, m_type):
13
  tmdb_type = "movie" if m_type == "movie" else "tv"
14
+ # Episode Poster အတွက် images ပါ ထပ်တောင်းထားပါတယ်
15
  url = f"https://api.themoviedb.org/3/{tmdb_type}/{tmdb_id}?api_key={TMDB_KEY}&append_to_response=credits,videos,images,recommendations,belongs_to_collection"
16
 
17
  try:
18
  res = requests.get(url).json()
19
  if "id" not in res: return None
20
 
21
+ # Cast List - String သီးသန့်ဖြစ်ရပါမယ်
 
 
 
 
 
 
 
 
22
  credits = res.get("credits", {})
23
+ cast = [str(c.get("name")) for c in credits.get("cast", [])[:15]]
24
+ directors = [str(c.get("name")) for c in credits.get("crew", []) if c.get("job") == "Director"]
 
 
 
 
 
 
 
 
 
 
25
 
26
  meta = {
27
  "_id": f"tmdb:{tmdb_id}",
28
  "id": f"tmdb:{tmdb_id}",
29
  "type": m_type,
30
+ "name": res.get("title") or res.get("name"),
31
+ "poster": f"https://image.tmdb.org/t/p/w500{res.get('poster_path')}",
32
+ "background": f"https://image.tmdb.org/t/p/original{res.get('backdrop_path')}",
 
33
  "description": res.get("overview") or "",
34
  "releaseInfo": str((res.get("release_date") or res.get("first_air_date", "0000"))[:4]),
35
+ "imdbRating": str(res.get("vote_average", "N/A")),
36
+ "cast": cast if cast else ["N/A"],
37
+ "director": directors if directors else ["N/A"],
 
38
  "genres": [g["name"] for g in res.get("genres", [])],
 
 
 
39
  "updated_at": datetime.utcnow()
40
  }
41
 
42
+ # Series Episode logic with Posters
43
  if m_type == "series":
44
  videos = []
 
 
 
45
  for s in res.get("seasons", []):
46
  s_num = s.get("season_number")
47
  if s_num == 0: continue
48
+ # Episode list fetching for thumbnails
49
+ ep_url = f"https://api.themoviedb.org/3/tv/{tmdb_id}/season/{s_num}?api_key={TMDB_KEY}"
50
+ ep_res = requests.get(ep_url).json()
51
+ for ep in ep_res.get("episodes", []):
52
  videos.append({
53
+ "id": f"tmdb:{tmdb_id}:{s_num}:{ep['episode_number']}",
54
+ "title": ep.get("name") or f"Episode {ep['episode_number']}",
55
+ "season": s_num,
56
+ "episode": ep['episode_number'],
57
+ "released": f"{ep.get('air_date')}T00:00:00.000Z",
58
+ "thumbnail": f"https://image.tmdb.org/t/p/w500{ep.get('still_path')}" if ep.get("still_path") else meta["background"]
59
  })
60
  meta["videos"] = videos
61
 
62
+ # Collection Logic - နှစ်အလိုက် Sort စီခြင်း
63
+ if res.get("belongs_to_collection"):
64
+ col_id = res["belongs_to_collection"]["id"]
65
+ c_url = f"https://api.themoviedb.org/3/collection/{col_id}?api_key={TMDB_KEY}"
66
+ c_res = requests.get(c_url).json()
67
+
68
+ # Release Date အလိုက် Sort စီပါမယ်
69
+ sorted_parts = sorted(c_res.get("parts", []), key=lambda x: x.get("release_date", "9999-99-99"))
70
+
71
+ col_videos = []
72
+ for i, p in enumerate(sorted_parts):
73
+ col_videos.append({
74
+ "id": f"tmdb_col:{col_id}:1:{i+1}",
75
+ "movie_id": str(p['id']), # Link ချိတ်ရန် ID သိမ်းထားခြင်း
76
+ "title": f"({p.get('release_date', '')[:4]}) {p.get('title')}",
77
+ "season": 1,
78
+ "episode": i+1,
79
+ "released": f"{p.get('release_date')}T00:00:00.000Z",
80
+ "thumbnail": f"https://image.tmdb.org/t/p/w500{p.get('backdrop_path')}" if p.get('backdrop_path') else None
81
+ })
82
 
83
+ col_meta = {
84
+ "_id": f"tmdb_col:{col_id}",
85
+ "id": f"tmdb_col:{col_id}",
86
+ "type": "series",
87
+ "name": c_res.get("name"),
88
+ "poster": f"https://image.tmdb.org/t/p/w500{c_res.get('poster_path')}",
89
+ "background": f"https://image.tmdb.org/t/p/original{c_res.get('backdrop_path')}",
90
+ "description": c_res.get("overview") or f"All movies in {c_res.get('name')}",
91
+ "genres": ["Collection"],
92
+ "videos": col_videos,
93
+ "updated_at": datetime.utcnow()
94
+ }
95
+ metas_col.update_one({"id": col_meta["id"]}, {"$set": col_meta}, upsert=True)
 
 
96
 
97
  return meta
98
+ except Exception as e:
99
+ print(f"Sync Error: {e}")
100
+ return None