-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
243 lines (192 loc) · 8.52 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
import asyncio
import aiohttp
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse, JSONResponse
from fastapi.encoders import jsonable_encoder
import logging
import json
from datetime import datetime, timedelta
import os
from fastapi.middleware.cors import CORSMiddleware
import time
from dotenv import load_dotenv
import requests
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI()
origins = ["*"] # Allow all origins (for testing)
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
load_dotenv() # Load environment variables from .env file
JACKETT_API_URL = os.getenv("JACKETT_API_URL")
API_KEY = os.getenv("API_KEY")
PORT = int(os.getenv("PORT", 8000)) # Default to 8000 if PORT is not set
CACHE_FILE = "configured_indexers.json"
CACHE_DURATION = timedelta(minutes=30)
# Initialize last cache update time
last_cache_update = datetime.now()
def get_jackett_cookie():
"""
Simulates a login to Pikpak Plus and retrieves the 'Jackett' cookie.
Returns:
The value of the 'Jackett' cookie, or None if the login fails or the cookie is not found.
"""
load_dotenv() # Load environment variables from .env file
JACKETT_API_URL = os.getenv("JACKETT_API_URL")
url = f"{JACKETT_API_URL}/UI/Login"
# Start a session to maintain cookies and reuse connections
session = requests.Session()
# Send a GET request to initiate the login process (replace with actual login logic)
response = session.get(url)
# Check for successful response (replace with actual success check)
if response.status_code != 200:
print(f"Failed to reach Pikpak Plus dashboard (status code: {response.status_code})")
return None
# Extract the 'Jackett' cookie from the session
try:
return session.cookies['Jackett']
except KeyError:
print("Jackett cookie not found in session.")
return None
def get_search_results_url(indexer_id: str):
return f"{JACKETT_API_URL}/api/v2.0/indexers/{indexer_id}/results"
async def fetch_jackett_results_for_indexer(session: aiohttp.ClientSession, indexer_id: str, query: str):
url = get_search_results_url(indexer_id)
params = {"apikey": API_KEY, "Query": query}
try:
async with session.get(url, params=params) as response:
if response.status == 200:
data = await response.json()
results = data.get("Results", [])
logger.info(f"Indexer {indexer_id} returned {len(results)} results.")
return [jsonable_encoder(trimmed_result(result)) for result in results]
else:
logger.error(f"Error fetching from indexer {indexer_id}: {response.status}")
return [{"error": f"Error fetching from indexer {indexer_id}: {response.status}"}]
except Exception as e:
logger.error(f"Exception fetching from indexer {indexer_id}: {str(e)}")
return [{"error": f"Exception fetching from indexer {indexer_id}: {str(e)}"}]
def create_magnet_link(result):
torrenturl = result.get("Link")
infohash = result.get("InfoHash")
magneturi = result.get("MagnetUri")
if magneturi is not None:
return magneturi
elif torrenturl is not None and infohash is not None:
return f"magnet:?xt=urn:btih:{infohash.lower()}"
else:
return torrenturl
def trimmed_result(result):
return {
"Title": result.get("Title"),
"Link": create_magnet_link(result),
"Size": result.get("Size"),
"Seeders": result.get("Seeders"),
"Leechers": result.get("Leechers"),
"InfoHash": result.get("InfoHash"),
"IndexerId": result.get("Tracker"),
'year': result.get('Year'),
"Details": result.get("Details"),
}
async def process_indexer(session: aiohttp.ClientSession, indexer_id: str, query: str):
start_time = time.time()
logger.info(f"Starting query for indexer {indexer_id}")
results = await fetch_jackett_results_for_indexer(session, indexer_id, query)
end_time = time.time()
logger.info(f"Finished query for indexer {indexer_id}. Time taken: {end_time - start_time:.2f} seconds")
return results
async def get_configured_indexers_from_file():
global last_cache_update
if os.path.exists(CACHE_FILE) and datetime.now() - last_cache_update < CACHE_DURATION:
try:
with open(CACHE_FILE, "r") as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError) as e:
logger.error(f"Error reading cache file: {e}")
logger.info(
"Cache is stale or doesn't exist. Fetching configured indexers from Jackett...")
jackett_cookie = get_jackett_cookie()
if not jackett_cookie:
raise HTTPException(
status_code=500, detail="Failed to retrieve Jackett cookie.")
configured_indexers = await get_configured_indexers(jackett_cookie)
try:
with open(CACHE_FILE, "w") as f:
json.dump(configured_indexers, f)
except (FileNotFoundError, json.JSONDecodeError) as e:
logger.error(f"Error saving cache file: {e}")
last_cache_update = datetime.now()
return configured_indexers
async def get_configured_indexers(jackett_cookie):
"""
Fetches a list of configured indexers from the Jackett API.
Args:
jackett_cookie: The 'Jackett' cookie value required for authentication.
Returns:
A list of configured indexer IDs.
Raises:
HTTPException: If there's an issue with the Jackett API request.
"""
load_dotenv() # Load environment variables from .env file
async with aiohttp.ClientSession() as session:
params = {"apikey": API_KEY, "configured": 'true'}
# Set the cookie in the headers
headers = {'Cookie': f'Jackett={jackett_cookie}'}
url = f"{JACKETT_API_URL}/api/v2.0/indexers"
try:
async with session.get(url, params=params, headers=headers) as response:
if response.status == 200:
indexers_data = await response.json()
configured_indexers = [
indexer["id"] for indexer in indexers_data if indexer.get("configured", False)]
return configured_indexers
else:
error_message = f"Jackett API Error: {response.status} - {response.reason}"
logger.error(error_message)
raise HTTPException(
status_code=response.status, detail=error_message)
except aiohttp.ClientError as e:
error_message = f"Error connecting to Jackett API: {str(e)}"
logger.error(error_message)
raise HTTPException(status_code=500, detail=error_message)
async def event_generator(query: str):
configured_indexers = await get_configured_indexers_from_file()
async with aiohttp.ClientSession() as session:
tasks = [asyncio.create_task(process_indexer(
session, indexer_id, query)) for indexer_id in configured_indexers]
for completed_task in asyncio.as_completed(tasks):
results = await completed_task
for item in results:
yield f"data: {json.dumps(item)}\n\n"
@app.get("/search")
async def search(query: str):
return StreamingResponse(event_generator(query), media_type="text/event-stream")
@app.get("/indexers")
async def get_indexers():
# Use the list of configured indexersconfigured_indexers = await get_configured_indexers(jackett_cookie)
try:
jackett_cookie = get_jackett_cookie()
if not jackett_cookie:
raise HTTPException(
status_code=500, detail="Failed to retrieve Jackett cookie.")
configured_indexers = await get_configured_indexers(jackett_cookie)
# Cache the results for subsequent requests
with open(CACHE_FILE, "w") as f:
json.dump(configured_indexers, f)
except (FileNotFoundError, json.JSONDecodeError) as e:
logger.error(f"Error reading/writing cache file: {e}")
except Exception as e:
logger.exception("Error fetching indexers:", exc_info=e)
raise HTTPException(status_code=500, detail="Error fetching indexers.")
return JSONResponse(content={"indexers": configured_indexers})
@app.get("/")
async def root():
return {"message": "Hello freeloader!!, feel free to use /search and /indexers"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=PORT)