MyanmarSwe commited on
Commit
289e111
·
verified ·
1 Parent(s): b7e1a6b

Update sync.py

Browse files
Files changed (1) hide show
  1. sync.py +27 -47
sync.py CHANGED
@@ -2,37 +2,38 @@ 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}",
@@ -40,21 +41,20 @@ def get_tmdb_data(tmdb_id, is_movie=True):
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")
@@ -63,58 +63,38 @@ def get_tmdb_data(tmdb_id, is_movie=True):
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"}
 
2
  from datetime import datetime
3
  from pymongo import MongoClient
4
 
 
5
  MONGO_URI = os.environ.get("MONGODB_URI")
6
  TMDB_KEY = os.environ.get("TMDB_API_KEY")
7
 
 
8
  client = MongoClient(MONGO_URI)
9
  db = client['myanmarswe_cinema']
10
  metas_col = db['metas']
11
  streams_col = db['streams']
12
  users_col = db['users']
13
 
14
+ def get_tmdb_data(tmdb_id, m_type):
 
 
15
  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"
16
 
17
  try:
18
  res = requests.get(url).json()
19
  if "id" not in res: return None
20
 
 
21
  trailers = [{"source": v["key"], "type": "Trailer"} for v in res.get("videos", {}).get("results", []) if v["type"] == "Trailer" and v["site"] == "YouTube"][:1]
22
 
23
+ # Runtime Formatting
24
+ if m_type == "movie":
25
  run_time = f"{res.get('runtime')} min"
26
  else:
27
  ert = res.get('episode_run_time', [])
28
  run_time = f"{ert[0]} min" if ert else "N/A"
29
 
30
+ # Cast formatting for Stremio (Array of strings)
31
+ cast_list = [c["name"] for c in res.get("credits", {}).get("cast", [])[:15]]
32
+
33
+ # Logo handling (Logo မရှိရင် Poster ကို သုံးမယ်)
34
+ logo_path = res.get("poster_path")
35
+ # TMDB images endpoint ကနေ logo ရှာရင် ပိုကောင်းပေမယ့် လောလောဆယ် poster ကို logo fallback လုပ်ထားပါတယ်
36
+
37
  meta = {
38
  "_id": f"tmdb:{tmdb_id}",
39
  "id": f"tmdb:{tmdb_id}",
 
41
  "name": res.get("title") or res.get("name"),
42
  "poster": f"https://image.tmdb.org/t/p/w500{res.get('poster_path')}",
43
  "background": f"https://image.tmdb.org/t/p/original{res.get('backdrop_path')}",
44
+ "logo": f"https://image.tmdb.org/t/p/w500{logo_path}",
45
  "description": res.get("overview"),
46
  "releaseInfo": (res.get("release_date") or res.get("first_air_date", "0000"))[:4],
47
+ "imdbRating": "{:.1f}".format(res.get("vote_average", 0)) if res.get("vote_average") else "N/A",
48
  "runtime": run_time,
49
+ "cast": cast_list,
50
  "genres": [g["name"] for g in res.get("genres", [])],
51
  "trailers": trailers,
52
  "recommendations": [str(r["id"]) for r in res.get("recommendations", {}).get("results", [])[:10]],
53
  "collection_info": res.get("belongs_to_collection"),
54
+ "updated_at": datetime.utcnow()
55
  }
56
 
57
+ if m_type == "tv":
 
58
  videos = []
59
  for s in res.get("seasons", []):
60
  s_num = s.get("season_number")
 
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
+ "released": res.get("first_air_date") # Released date field is important for series UI
68
  })
69
  meta["videos"] = videos
70
 
71
  return meta
72
+ except: return None
 
 
73
 
74
  def process_sync(data):
75
+ if data.get("users"):
76
+ users_col.delete_many({})
77
+ users_col.insert_many(data["users"])
 
 
78
 
 
79
  items = data.get("movies_series", [])
80
  for item in items:
81
  tid = str(item['tmdb_id'])
82
+ m_type = item['type'] # 'movie' or 'series'
83
 
84
+ full_meta = get_tmdb_data(tid, m_type)
 
85
  if full_meta:
 
86
  if item.get('custom_overview'):
87
  full_meta['description'] = item['custom_overview']
88
 
89
+ metas_col.update_one({"id": full_meta["id"]}, {"$set": full_meta}, upsert=True)
 
90
 
 
91
  stream_data = {
92
+ "tmdb_id": tid, "type": m_type, "url": item['stream_url'],
93
+ "season": item.get('season'), "episode": item.get('episode'),
 
 
 
94
  "updated_at": datetime.utcnow()
95
  }
 
96
  streams_col.update_one(
97
  {"tmdb_id": tid, "season": item.get('season'), "episode": item.get('episode')},
98
+ {"$set": stream_data}, upsert=True
 
99
  )
 
 
 
 
 
 
 
100
  return {"status": "success"}