-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtmdb_api.py
More file actions
203 lines (169 loc) · 5.87 KB
/
Copy pathtmdb_api.py
File metadata and controls
203 lines (169 loc) · 5.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import requests, os, log
import db
TMDB_API = "https://api.themoviedb.org/3"
TMDB_IMAGE_DOMAIN = os.getenv("TMDB_IMAGE_DOMAIN", "https://image.tmdb.org")
TMDB_LANG = "zh-CN"
def get_tmdb_token():
"""从数据库获取 TMDB API Token"""
return db.get_system_config("TMDB_API_TOKEN")
def get_headers():
"""获取 TMDB API 请求头"""
token = get_tmdb_token()
if not token:
return None
return {
"accept": "application/json",
"Authorization": "Bearer {}".format(token),
}
TMDB_MEDIA_TYPES = {
"Movie": "movie",
"Episode": "tv",
}
def login():
"""
Logs in to the TMDB API.
"""
headers = get_headers()
if not headers:
log.logger.critical("TMDB_API_TOKEN not configured! Please set it in WebUI.")
return False
login_url = f"{TMDB_API}/authentication"
try:
response = requests.get(login_url, headers=headers, timeout=5)
response.raise_for_status()
log.logger.debug("TMDB login successful.")
return True
except requests.exceptions.ConnectionError as e:
log.logger.error(f"TMDB login failed. Check network connection: {e}")
return False
except requests.exceptions.RequestException as e:
log.logger.error(
f"TMDB login failed. {response.json()['status_message']}"
)
return False
def search_media(media_type, name, year):
"""
Search for movies or TV shows on TMDB API.
"""
headers = get_headers()
if not headers:
return [], "TMDB_API_TOKEN not configured"
media_type = (
TMDB_MEDIA_TYPES[media_type] if media_type in TMDB_MEDIA_TYPES else media_type
)
search_url = f"{TMDB_API}/search/{media_type}?query={name}&language={TMDB_LANG}&page=1"
if year != -1:
search_url += f"&year={year}"
try:
response = requests.get(search_url, headers=headers)
response.raise_for_status()
return response.json().get("results", []), None
except requests.exceptions.RequestException as e:
return (
[],
f"TMDB search for {name} failed. Check network connection or API token: {e}",
)
def get_external_ids(media_type, tmdb_id):
"""
Fetches the external IDs for a given media type and TMDB ID.
"""
headers = get_headers()
if not headers:
return {}, "TMDB_API_TOKEN not configured"
media_type = (
TMDB_MEDIA_TYPES[media_type] if media_type in TMDB_MEDIA_TYPES else media_type
)
external_ids_url = (
f"{TMDB_API}/{media_type}/{tmdb_id}/external_ids?language={TMDB_LANG}"
)
try:
response = requests.get(external_ids_url, headers=headers)
response.raise_for_status()
return response.json(), None
except requests.exceptions.RequestException as e:
return (
{},
f"TMDB get external IDs for {media_type}/{tmdb_id} failed: {e}",
)
def find_by_tvdb_id(tvdb_id):
"""通过 TVDB ID 在 TMDB 查找对应条目,返回 (type, tmdb_id) 或 (None, None)"""
headers = get_headers()
if not headers:
return None, "TMDB_API_TOKEN not configured"
try:
url = f"{TMDB_API}/find/{tvdb_id}?external_source=tvdb_id"
response = requests.get(url, headers=headers)
response.raise_for_status()
data = response.json()
# Try TV results first (for Episode), then Movie
for item in data.get("tv_results", []) + data.get("movie_results", []):
return item.get("id"), None
return None, f"No TMDB match for TVDB ID {tvdb_id}"
except requests.exceptions.RequestException as e:
return None, f"TMDB find by TVDB {tvdb_id} failed: {e}"
def get_movie_details(movie_id):
"""
Fetches the details for a given movie ID.
"""
headers = get_headers()
if not headers:
return {}, "TMDB_API_TOKEN not configured"
details_url = f"{TMDB_API}/movie/{movie_id}?language={TMDB_LANG}"
try:
response = requests.get(details_url, headers=headers)
response.raise_for_status()
return response.json(), None
except requests.exceptions.RequestException as e:
return (
{},
f"TMDB get movie details for {movie_id} failed: {e}",
)
def get_tv_details(tv_id):
"""
Fetches the details for a given TV ID.
"""
headers = get_headers()
if not headers:
return {}, "TMDB_API_TOKEN not configured"
details_url = f"{TMDB_API}/tv/{tv_id}?language={TMDB_LANG}"
try:
response = requests.get(details_url, headers=headers)
response.raise_for_status()
return response.json(), None
except requests.exceptions.RequestException as e:
return (
{},
f"TMDB get TV details for {tv_id} failed: {e}",
)
def get_tv_episode_details(tv_id, season_number, episode_number):
"""
Fetches the details for a given TV episode.
"""
headers = get_headers()
if not headers:
return {}, "TMDB_API_TOKEN not configured"
episode_url = (
f"{TMDB_API}/tv/{tv_id}/season/{season_number}/episode/{episode_number}"
f"?language={TMDB_LANG}"
)
try:
response = requests.get(episode_url, headers=headers)
response.raise_for_status()
return response.json(), None
except requests.exceptions.RequestException as e:
return (
{},
f"TMDB get TV episode details for {tv_id}/S{season_number}E{episode_number} failed: {e}",
)
def get_poster_url(poster_path, size="w500"):
"""
Returns the full poster URL for a given poster path.
"""
return f"{TMDB_IMAGE_DOMAIN}/t/p/{size}{poster_path}"
def get_still_url(still_path, size="w500"):
"""
Returns the full still URL for a given still path.
"""
return f"{TMDB_IMAGE_DOMAIN}/t/p/{size}{still_path}"