forked from aymene69/stremio-jackett
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
297 lines (252 loc) · 9.95 KB
/
main.py
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import base64
import json
import logging
import re
import asyncio
import requests
import zipfile
import os
import shutil
from dotenv import load_dotenv
from aiocron import crontab
import starlette.status as status
from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates
from constants import NO_RESULTS
from debrid.alldebrid import get_stream_link_ad
from debrid.realdebrid import get_stream_link_rd
from debrid.premiumize import get_stream_link_pm
from utils.filter_results import filter_items
from utils.get_availability import availability
from utils.get_cached import search_cache
from utils.get_content import get_name
from utils.jackett import search
from utils.logger import setup_logger
from utils.process_results import process_results
load_dotenv()
root_path = os.environ.get("ROOT_PATH", None)
if root_path and not root_path.startswith("/"):
root_path = "/" + root_path
app = FastAPI(root_path=root_path)
VERSION = "3.0.13"
isDev = os.getenv("NODE_ENV") == "development"
class LogFilterMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
request = Request(scope, receive)
path = request.url.path
sensible_path = re.sub(r"/ey.*?/", "/<SENSITIVE_DATA>/", path)
logger.info(f"{request.method} - {sensible_path}")
return await self.app(scope, receive, send)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
if not isDev:
app.add_middleware(LogFilterMiddleware)
templates = Jinja2Templates(directory=".")
logger = setup_logger(__name__)
@app.get("/")
async def root():
return RedirectResponse(url="/configure")
@app.get("/configure")
async def configure(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.get("/{config}/configure")
async def configure(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.get("/{params}/manifest.json")
async def get_manifest():
return {
"id": "community.aymene69.jackett",
"icon": "https://i.imgur.com/yLNzl4q.png",
"version": VERSION,
"catalogs": [{"id": "jackitt_porn_stashdb", "type": "porn", "name": "Adult"}],
"resources": ["stream", "catalog"],
"types": ["movie", "series", "porn"],
"name": "Jackett" + (" (Dev)" if isDev else ""),
"description": "Stremio Jackett Addon",
"behaviorHints": {
"configurable": True,
},
}
formatter = logging.Formatter(
"[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s",
"%m-%d %H:%M:%S",
)
logger.info("Started Jackett Addon")
@app.get("/{config}/stream/{stream_type}/{stream_id}")
async def get_results(config: str, stream_type: str, stream_id: str):
stream_id = stream_id.replace(".json", "")
config = json.loads(base64.b64decode(config).decode("utf-8"))
logger.info(stream_type + " request")
logger.info("Getting name and properties")
name = get_name(stream_id, stream_type, config=config)
logger.info("Got name and properties: " + str(name["title"]))
logger.info("Getting config")
logger.info("Got config")
logger.info("Getting cached results")
if config["cache"]:
cached_results = search_cache(name)
else:
cached_results = []
logger.info("Got " + str(len(cached_results)) + " cached results")
logger.info("Filtering cached results")
filtered_cached_results = filter_items(
cached_results,
stream_type,
config=config,
cached=True,
season=name["season"] if stream_type == "series" else None,
episode=name["episode"] if stream_type == "series" else None,
)
logger.info("Filtered cached results")
if len(filtered_cached_results) >= int(config["maxResults"]):
logger.info("Cached results found")
logger.info("Processing cached results")
stream_list = process_results(
filtered_cached_results[: int(config["maxResults"])],
True,
stream_type,
name["season"] if stream_type == "series" else None,
name["episode"] if stream_type == "series" else None,
config=config,
)
logger.info("Processed cached results")
if len(stream_list) == 0:
logger.info("No results found")
return NO_RESULTS
return {"streams": stream_list}
else:
if len(filtered_cached_results) > 0:
logger.info(
"Not enough cached results found (results: "
+ str(len(filtered_cached_results))
+ ")"
)
else:
logger.info("No cached results found")
logger.info("Searching for results on Jackett")
search_results = []
if stream_type == "movie":
search_results = search(
{"type": name["type"], "title": name["title"], "year": name["year"]},
config=config,
)
elif stream_type == "series":
search_results = search(
{
"type": name["type"],
"title": name["title"],
"season": name["season"],
"episode": name["episode"],
},
config=config,
)
logger.info("Got " + str(len(search_results)) + " results from Jackett")
logger.info("Filtering results")
filtered_results = filter_items(search_results, stream_type, config=config)
logger.info("Filtered results")
logger.info("Checking availability")
results = (
availability(filtered_results, config=config) + filtered_cached_results
)
logger.info("Checked availability (results: " + str(len(results)) + ")")
logger.info("Processing results")
stream_list = process_results(
results[: int(config["maxResults"])],
False,
stream_type,
name["season"] if stream_type == "series" else None,
name["episode"] if stream_type == "series" else None,
config=config,
)
logger.info("Processed results (results: " + str(len(stream_list)) + ")")
if len(stream_list) == 0:
logger.info("No results found")
return NO_RESULTS
return {"streams": stream_list}
@app.get("/playback/{config}/{query}/{title}")
async def get_playback(config: str, query: str, title: str, request: Request):
try:
if not query or not title:
raise HTTPException(status_code=400, detail="Query and title are required.")
config = json.loads(base64.b64decode(config).decode("utf-8"))
logger.info("Decoding query")
query = base64.b64decode(query).decode("utf-8")
logger.info(query)
logger.info("Decoded query")
service = config["service"]
if service == "realdebrid":
logger.info("Getting Real-Debrid link")
source_ip = request.client.host
link = get_stream_link_rd(query, source_ip, config=config)
elif service == "alldebrid":
logger.info("Getting All-Debrid link")
link = get_stream_link_ad(query, config=config)
elif service == "premiumize":
logger.info("Getting Premiumize link")
link = get_stream_link_pm(query, config=config)
else:
raise HTTPException(
status_code=500, detail="Invalid service configuration."
)
logger.info("Got link: " + link)
return RedirectResponse(url=link, status_code=status.HTTP_301_MOVED_PERMANENTLY)
except Exception as e:
logger.error(f"An error occurred: {e}")
raise HTTPException(
status_code=500, detail="An error occurred while processing the request."
)
async def update_app():
try:
if not isDev:
current_version = "v" + VERSION
url = (
"https://api.github.com/repos/aymene69/stremio-jackett/releases/latest"
)
response = requests.get(url)
data = response.json()
latest_version = data["tag_name"]
if latest_version != current_version:
logger.info("New version available: " + latest_version)
logger.info("Updating...")
logger.info("Getting update zip...")
update_zip = requests.get(data["zipball_url"])
with open("update.zip", "wb") as file:
file.write(update_zip.content)
logger.info("Update zip downloaded")
logger.info("Extracting update...")
with zipfile.ZipFile("update.zip", "r") as zip_ref:
zip_ref.extractall("update")
logger.info("Update extracted")
extracted_folder = os.listdir("update")[0]
extracted_folder_path = os.path.join("update", extracted_folder)
for item in os.listdir(extracted_folder_path):
s = os.path.join(extracted_folder_path, item)
d = os.path.join(".", item)
if os.path.isdir(s):
shutil.copytree(s, d, dirs_exist_ok=True)
else:
shutil.copy2(s, d)
logger.info("Files copied")
logger.info("Cleaning up...")
shutil.rmtree("update")
os.remove("update.zip")
logger.info("Cleaned up")
logger.info("Updated !")
except Exception as e:
logger.error(f"Error during update: {e}")
@crontab("* * * * *", start=not isDev)
async def schedule_task():
await update_app()
async def main():
await asyncio.gather(schedule_task())
if __name__ == "__main__":
asyncio.run(main())