MyanmarSwe commited on
Commit
31f4662
·
verified ·
1 Parent(s): c0a3e03

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +35 -34
main.py CHANGED
@@ -12,7 +12,6 @@ TMDB_KEY = os.getenv("TMDB_KEY")
12
  SHEET_ID = os.getenv("SHEET_ID")
13
  SERVICE_ACCOUNT_STR = os.getenv("SERVICE_ACCOUNT_JSON")
14
 
15
- # Cache
16
  db_cache = {"movies": [], "tv_shows": [], "users": {}}
17
  tmdb_cache = {}
18
  filter_options = {"years": set(), "genres": set(), "casts": set()}
@@ -27,7 +26,8 @@ def get_sheet():
27
  async def fetch_tmdb_meta(tmdb_id, media_type="movie"):
28
  ck = f"{media_type}_{tmdb_id}"
29
  if ck in tmdb_cache: return tmdb_cache[ck]
30
- url = f"https://api.themoviedb.org/3/{media_type}/{tmdb_id}?api_key={TMDB_KEY}&append_to_response=credits"
 
31
  async with httpx.AsyncClient() as client:
32
  res = await client.get(url)
33
  if res.status_code == 200:
@@ -44,14 +44,13 @@ async def refresh_db():
44
  db_cache["tv_shows"] = ss.worksheet("tv_shows").get_all_records()
45
  db_cache["users"] = {r["user_token"]: r for r in ss.worksheet("users").get_all_records() if r["status"] == "active"}
46
 
47
- # Filter Options များကို ပြန်ဆန်းသစ်ခြင်း
48
  filter_options["years"].clear()
49
  filter_options["genres"].clear()
50
  filter_options["casts"].clear()
51
 
52
- all_items = db_cache["movies"] + db_cache["tv_shows"]
53
- for item in all_items:
54
- m_type = "movie" if item in db_cache["movies"] else "tv"
55
  data = await fetch_tmdb_meta(item["tmdb_id"], m_type)
56
  if data:
57
  rd = data.get("release_date") or data.get("first_air_date", "0000")
@@ -60,7 +59,7 @@ async def refresh_db():
60
  for person in data.get("credits", {}).get("cast", [])[:5]:
61
  filter_options["casts"].add(person["name"])
62
 
63
- return {"status": "success", "message": "Database & Filters Synced"}
64
  except Exception as e:
65
  return {"status": "error", "message": str(e)}
66
 
@@ -68,52 +67,45 @@ async def refresh_db():
68
  async def get_manifest(token: str):
69
  if token not in db_cache["users"]: raise HTTPException(status_code=403)
70
 
71
- # Sidebar Filters စီစဉ်ခြင်း
72
  years = [f"Year: {y}" for y in sorted(list(filter_options["years"]), reverse=True)]
73
  genres = [f"Genre: {g}" for g in sorted(list(filter_options["genres"]))]
74
- casts = [f"Actor: {c}" for c in sorted(list(filter_options["casts"]))]
75
  combined = ["All"] + years + genres + casts
76
 
77
  return {
78
- "id": f"ms.private.{token}",
79
- "version": "2.1.0",
80
  "name": "MyanmarSwe Private Cinema",
 
81
  "resources": ["catalog", "meta", "stream"],
82
  "types": ["movie", "series"],
83
  "catalogs": [
84
- {
85
- "type": "movie", "id": "ms_latest", "name": "✨ New Arrivals",
86
- "extra": [{"name": "genre", "options": combined}]
87
- },
88
- {
89
- "type": "movie", "id": "ms_collections", "name": "📚 Movie Collections",
90
- "extra": [{"name": "genre", "options": combined}]
91
- },
92
- {
93
- "type": "series", "id": "ms_series", "name": "📺 TV Series",
94
- "extra": [{"name": "genre", "options": combined}]
95
- }
96
  ]
97
  }
98
 
99
  @app.get("/{token}/catalog/{type}/{id}.json")
100
  async def get_catalog(token: str, type: str, id: str, genre: str = None):
 
101
  items = db_cache["movies"] if type == "movie" else db_cache["tv_shows"]
102
  metas = []
103
  processed_ids = set()
104
  processed_collections = set()
105
 
106
- # Sort: New Arrivals အတွက် နောက်ဆုံးထည့်ထားတာကို အရင်ပြရန်
107
  if id == "ms_latest": items = items[::-1]
108
 
109
  for item in items:
110
  tid = str(item["tmdb_id"])
111
  if tid in processed_ids: continue
112
 
113
- tmdb_data = await fetch_tmdb_meta(tid, "movie" if type == "movie" else "tv")
 
114
  if not tmdb_data: continue
115
 
116
- # --- Filter Logic ---
117
  show_item = False
118
  if not genre or genre == "All":
119
  show_item = True
@@ -125,12 +117,11 @@ async def get_catalog(token: str, type: str, id: str, genre: str = None):
125
  if rd.startswith(value): show_item = True
126
  elif prefix == "Genre":
127
  if any(g["name"] == value for g in tmdb_data.get("genres", [])): show_item = True
128
- elif prefix == "Actor":
129
  cast = [p["name"] for p in tmdb_data.get("credits", {}).get("cast", [])[:5]]
130
  if value in cast: show_item = True
131
  except: show_item = True
132
 
133
- # --- Catalog Specific Logic ---
134
  if id == "ms_collections":
135
  col = tmdb_data.get("belongs_to_collection")
136
  if not col or col["id"] in processed_collections: continue
@@ -141,7 +132,7 @@ async def get_catalog(token: str, type: str, id: str, genre: str = None):
141
 
142
  if show_item:
143
  metas.append({
144
- "id": f"tmdb:{tid}",
145
  "type": type,
146
  "name": name,
147
  "poster": f"https://image.tmdb.org/t/p/w500{poster}"
@@ -152,38 +143,48 @@ async def get_catalog(token: str, type: str, id: str, genre: str = None):
152
 
153
  @app.get("/{token}/meta/{type}/tmdb:{tmdb_id}.json")
154
  async def get_meta(token: str, type: str, tmdb_id: str):
 
155
  tmdb_data = await fetch_tmdb_meta(tmdb_id, "movie" if type == "movie" else "tv")
156
  if not tmdb_data: return {"meta": {}}
 
157
  meta = {
158
  "id": f"tmdb:{tmdb_id}",
159
  "type": type,
160
  "name": tmdb_data.get("title") or tmdb_data.get("name"),
161
- "poster": f"https://image.tmdb.org/t/p/w500{tmdb_data['poster_path']}",
162
- "background": f"https://image.tmdb.org/t/p/original{tmdb_data['backdrop_path']}",
163
- "description": tmdb_data.get("overview")
 
 
 
164
  }
 
165
  if type == "series":
166
  videos = []
167
  episodes = [row for row in db_cache["tv_shows"] if str(row["tmdb_id"]) == str(tmdb_id)]
168
  for ep in episodes:
169
  videos.append({
170
  "id": f"tmdb:{tmdb_id}:{ep['season']}:{ep['episode']}",
171
- "title": ep.get("name", f"Episode {ep['episode']}"),
172
  "season": int(ep["season"]), "episode": int(ep["episode"]),
173
  "released": "2020-01-01T00:00:00.000Z"
174
  })
175
  meta["videos"] = sorted(videos, key=lambda x: (x['season'], x['episode']))
 
176
  return {"meta": meta}
177
 
178
  @app.get("/{token}/stream/{type}/{id}.json")
179
  async def get_stream(token: str, type: str, id: str):
180
  if token not in db_cache["users"]: return {"streams": []}
 
181
  parts = id.split(":")
182
  tmdb_id = parts[1]
 
183
  if type == "series" and len(parts) >= 4:
184
  s, e = str(parts[2]), str(parts[3])
185
  matched = next((i for i in db_cache["tv_shows"] if str(i["tmdb_id"]) == tmdb_id and str(i["season"]) == s and str(i["episode"]) == e), None)
186
  else:
187
  matched = next((i for i in db_cache["movies"] if str(i["tmdb_id"]) == tmdb_id), None)
 
188
  if not matched: return {"streams": []}
189
- return {"streams": [{"title": "🚀 MyanmarSwe Direct", "url": matched["link"]}]}
 
12
  SHEET_ID = os.getenv("SHEET_ID")
13
  SERVICE_ACCOUNT_STR = os.getenv("SERVICE_ACCOUNT_JSON")
14
 
 
15
  db_cache = {"movies": [], "tv_shows": [], "users": {}}
16
  tmdb_cache = {}
17
  filter_options = {"years": set(), "genres": set(), "casts": set()}
 
26
  async def fetch_tmdb_meta(tmdb_id, media_type="movie"):
27
  ck = f"{media_type}_{tmdb_id}"
28
  if ck in tmdb_cache: return tmdb_cache[ck]
29
+ # append_to_response မှာ images ပါ ထည့်ထားသည်
30
+ url = f"https://api.themoviedb.org/3/{media_type}/{tmdb_id}?api_key={TMDB_KEY}&append_to_response=credits,videos"
31
  async with httpx.AsyncClient() as client:
32
  res = await client.get(url)
33
  if res.status_code == 200:
 
44
  db_cache["tv_shows"] = ss.worksheet("tv_shows").get_all_records()
45
  db_cache["users"] = {r["user_token"]: r for r in ss.worksheet("users").get_all_records() if r["status"] == "active"}
46
 
 
47
  filter_options["years"].clear()
48
  filter_options["genres"].clear()
49
  filter_options["casts"].clear()
50
 
51
+ # TV Show အတွက် 'tmdb:' prefix တပ်ပေးရန် လိုအပ်သည်
52
+ all_items = [(i, "movie") for i in db_cache["movies"]] + [(i, "tv") for i in db_cache["tv_shows"]]
53
+ for item, m_type in all_items:
54
  data = await fetch_tmdb_meta(item["tmdb_id"], m_type)
55
  if data:
56
  rd = data.get("release_date") or data.get("first_air_date", "0000")
 
59
  for person in data.get("credits", {}).get("cast", [])[:5]:
60
  filter_options["casts"].add(person["name"])
61
 
62
+ return {"status": "success", "message": "Metadata Sync Complete"}
63
  except Exception as e:
64
  return {"status": "error", "message": str(e)}
65
 
 
67
  async def get_manifest(token: str):
68
  if token not in db_cache["users"]: raise HTTPException(status_code=403)
69
 
70
+ # Filter များကို နာမည်အလိုက် စီစဉ်ခြင်း
71
  years = [f"Year: {y}" for y in sorted(list(filter_options["years"]), reverse=True)]
72
  genres = [f"Genre: {g}" for g in sorted(list(filter_options["genres"]))]
73
+ casts = [f"Cast: {c}" for c in sorted(list(filter_options["casts"]))]
74
  combined = ["All"] + years + genres + casts
75
 
76
  return {
77
+ "id": f"ms.cinema.fixed.{token}",
78
+ "version": "2.5.0",
79
  "name": "MyanmarSwe Private Cinema",
80
+ "idPrefixes": ["tmdb:"], # Metadata ချိတ်ဆက်ဖို့ ဒါက အရေးကြီးဆုံးပါ
81
  "resources": ["catalog", "meta", "stream"],
82
  "types": ["movie", "series"],
83
  "catalogs": [
84
+ {"type": "movie", "id": "ms_latest", "name": "✨ New Movies", "extra": [{"name": "genre", "options": combined}]},
85
+ {"type": "movie", "id": "ms_collections", "name": "📚 Collections", "extra": [{"name": "genre", "options": combined}]},
86
+ {"type": "series", "id": "ms_series", "name": "📺 TV Library", "extra": [{"name": "genre", "options": combined}]}
 
 
 
 
 
 
 
 
 
87
  ]
88
  }
89
 
90
  @app.get("/{token}/catalog/{type}/{id}.json")
91
  async def get_catalog(token: str, type: str, id: str, genre: str = None):
92
+ # (Catalog Logic က အရင်အတိုင်းဖြစ်သော်လည်း Filter prefixes များကို Cast: ဟု ပြောင်းထားသည်)
93
  items = db_cache["movies"] if type == "movie" else db_cache["tv_shows"]
94
  metas = []
95
  processed_ids = set()
96
  processed_collections = set()
97
 
 
98
  if id == "ms_latest": items = items[::-1]
99
 
100
  for item in items:
101
  tid = str(item["tmdb_id"])
102
  if tid in processed_ids: continue
103
 
104
+ m_type = "movie" if type == "movie" else "tv"
105
+ tmdb_data = await fetch_tmdb_meta(tid, m_type)
106
  if not tmdb_data: continue
107
 
108
+ # Filter Logic
109
  show_item = False
110
  if not genre or genre == "All":
111
  show_item = True
 
117
  if rd.startswith(value): show_item = True
118
  elif prefix == "Genre":
119
  if any(g["name"] == value for g in tmdb_data.get("genres", [])): show_item = True
120
+ elif prefix == "Cast":
121
  cast = [p["name"] for p in tmdb_data.get("credits", {}).get("cast", [])[:5]]
122
  if value in cast: show_item = True
123
  except: show_item = True
124
 
 
125
  if id == "ms_collections":
126
  col = tmdb_data.get("belongs_to_collection")
127
  if not col or col["id"] in processed_collections: continue
 
132
 
133
  if show_item:
134
  metas.append({
135
+ "id": f"tmdb:{tid}", # Prefix ထည့်ထားသည်
136
  "type": type,
137
  "name": name,
138
  "poster": f"https://image.tmdb.org/t/p/w500{poster}"
 
143
 
144
  @app.get("/{token}/meta/{type}/tmdb:{tmdb_id}.json")
145
  async def get_meta(token: str, type: str, tmdb_id: str):
146
+ # Meta Logic မှာ TMDB API ကနေ Cast တွေပါ တစ်ခါတည်း ဆွဲယူပြသရန်
147
  tmdb_data = await fetch_tmdb_meta(tmdb_id, "movie" if type == "movie" else "tv")
148
  if not tmdb_data: return {"meta": {}}
149
+
150
  meta = {
151
  "id": f"tmdb:{tmdb_id}",
152
  "type": type,
153
  "name": tmdb_data.get("title") or tmdb_data.get("name"),
154
+ "poster": f"https://image.tmdb.org/t/p/w500{tmdb_data.get('poster_path')}",
155
+ "background": f"https://image.tmdb.org/t/p/original{tmdb_data.get('backdrop_path')}",
156
+ "description": tmdb_data.get("overview"),
157
+ "genres": [g["name"] for g in tmdb_data.get("genres", [])],
158
+ "releaseInfo": tmdb_data.get("release_date", "")[:4] if type == "movie" else tmdb_data.get("first_air_date", "")[:4],
159
+ "cast": [p["name"] for p in tmdb_data.get("credits", {}).get("cast", [])[:10]]
160
  }
161
+
162
  if type == "series":
163
  videos = []
164
  episodes = [row for row in db_cache["tv_shows"] if str(row["tmdb_id"]) == str(tmdb_id)]
165
  for ep in episodes:
166
  videos.append({
167
  "id": f"tmdb:{tmdb_id}:{ep['season']}:{ep['episode']}",
168
+ "title": ep.get("name", f"Season {ep['season']} Episode {ep['episode']}"),
169
  "season": int(ep["season"]), "episode": int(ep["episode"]),
170
  "released": "2020-01-01T00:00:00.000Z"
171
  })
172
  meta["videos"] = sorted(videos, key=lambda x: (x['season'], x['episode']))
173
+
174
  return {"meta": meta}
175
 
176
  @app.get("/{token}/stream/{type}/{id}.json")
177
  async def get_stream(token: str, type: str, id: str):
178
  if token not in db_cache["users"]: return {"streams": []}
179
+ # Prefix tmdb: ကို ဖယ်ထုတ်ပြီး ID ရှာခြင်း
180
  parts = id.split(":")
181
  tmdb_id = parts[1]
182
+
183
  if type == "series" and len(parts) >= 4:
184
  s, e = str(parts[2]), str(parts[3])
185
  matched = next((i for i in db_cache["tv_shows"] if str(i["tmdb_id"]) == tmdb_id and str(i["season"]) == s and str(i["episode"]) == e), None)
186
  else:
187
  matched = next((i for i in db_cache["movies"] if str(i["tmdb_id"]) == tmdb_id), None)
188
+
189
  if not matched: return {"streams": []}
190
+ return {"streams": [{"title": "🚀 MyanmarSwe Direct Link", "url": matched["link"]}]}