eaf-base-api 1.6.3__tar.gz → 2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,56 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+
6
+ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
7
+
8
+ This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
9
+
10
+ 0. Additional Definitions.
11
+ As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License.
12
+
13
+ “The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
14
+
15
+ An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
16
+
17
+ A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”.
18
+
19
+ The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
20
+
21
+ The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
22
+
23
+ 1. Exception to Section 3 of the GNU GPL.
24
+ You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
25
+
26
+ 2. Conveying Modified Versions.
27
+ If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
28
+
29
+ a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
30
+ b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
31
+ 3. Object Code Incorporating Material from Library Header Files.
32
+ The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
33
+
34
+ a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
35
+ b) Accompany the object code with a copy of the GNU GPL and this license document.
36
+ 4. Combined Works.
37
+ You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
38
+
39
+ a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
40
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
41
+ c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
42
+ d) Do one of the following:
43
+ 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
44
+ 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
45
+ e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
46
+ 5. Combined Libraries.
47
+ You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
48
+
49
+ a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
50
+ b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
51
+ 6. Revised Versions of the GNU Lesser General Public License.
52
+ The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
53
+
54
+ Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
55
+
56
+ If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.1
2
+ Name: eaf_base_api
3
+ Version: 2.1
4
+ Summary: A base API for EchterAlsFake's Porn APIs
5
+ Home-page: https://github.com/EchterAlsFake/eaf_base_api
6
+ Author: Johannes Habel
7
+ Author-email: EchterAlsFake@proton.me
8
+ License: LGPLv3
9
+ Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
10
+ Classifier: Programming Language :: Python
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: ffmpeg-progress-yield
14
+ Requires-Dist: m3u8
15
+ Requires-Dist: httpx
16
+
17
+ # EAF Base API
18
+
19
+ # What is this?
20
+ When using one of my Porn site APIs, you probably came across this package and wondered what it actually does, so here's
21
+ a detailed answer.
22
+
23
+ A lot of Porn sites use very similar methods for m3u8 (HLS) parsing and other things. I also wanted to implement proxy
24
+ support, and there was a lot of code that I would have rewritten in every API again and again. That's why I made this API
25
+ package. The `BaseCore` class does all the necessary stuff like m3u8 parsing, a great caching system, network request
26
+ fetching with retry attempts and proxy support.
27
+
28
+ # Using Proxies / Caching
29
+ There's a small documentation for this project.
30
+ <br>Please have a look at it: https://github.com/EchterAlsFake/API_Docs/blob/master/Porn_APIs/eaf_base_api.md
31
+
32
+
33
+ # Can I use this for myself?
34
+ Yes, you can, but I may change stuff here and there from time to time, and it would maybe break your project.
35
+ I would not recommend you to install and use it as a package, but just copy the code you need.
36
+
37
+ I can recommend everyone the download functions for HLS streaming since, for example, the threaded preset is very well
38
+ optimized. If you just use mine, you need to consume less caffeine and brain cells to make such a function :)
39
+
40
+
41
+ # License
42
+ Licensed under The [LGPLv3](https://www.gnu.org/licenses/lgpl-3.0.en.html) license.
43
+ <br>Copyright (C) 2024-2025 Johannes Habel
@@ -0,0 +1,27 @@
1
+ # EAF Base API
2
+
3
+ # What is this?
4
+ When using one of my Porn site APIs, you probably came across this package and wondered what it actually does, so here's
5
+ a detailed answer.
6
+
7
+ A lot of Porn sites use very similar methods for m3u8 (HLS) parsing and other things. I also wanted to implement proxy
8
+ support, and there was a lot of code that I would have rewritten in every API again and again. That's why I made this API
9
+ package. The `BaseCore` class does all the necessary stuff like m3u8 parsing, a great caching system, network request
10
+ fetching with retry attempts and proxy support.
11
+
12
+ # Using Proxies / Caching
13
+ There's a small documentation for this project.
14
+ <br>Please have a look at it: https://github.com/EchterAlsFake/API_Docs/blob/master/Porn_APIs/eaf_base_api.md
15
+
16
+
17
+ # Can I use this for myself?
18
+ Yes, you can, but I may change stuff here and there from time to time, and it would maybe break your project.
19
+ I would not recommend you to install and use it as a package, but just copy the code you need.
20
+
21
+ I can recommend everyone the download functions for HLS streaming since, for example, the threaded preset is very well
22
+ optimized. If you just use mine, you need to consume less caffeine and brain cells to make such a function :)
23
+
24
+
25
+ # License
26
+ Licensed under The [LGPLv3](https://www.gnu.org/licenses/lgpl-3.0.en.html) license.
27
+ <br>Copyright (C) 2024-2025 Johannes Habel
@@ -0,0 +1,4 @@
1
+ __all__ = ["BaseCore", "Callback"]
2
+
3
+ from base_api.base import BaseCore
4
+ from base_api.modules.progress_bars import Callback
@@ -0,0 +1,418 @@
1
+ import os
2
+ import time
3
+ import m3u8
4
+ import httpx
5
+ import random
6
+ import string
7
+ import logging
8
+ import traceback
9
+ import threading
10
+
11
+ from typing import Union
12
+ from functools import lru_cache
13
+ from urllib.parse import urljoin
14
+ from ffmpeg_progress_yield import FfmpegProgress
15
+ from concurrent.futures import ThreadPoolExecutor, as_completed
16
+
17
+ try:
18
+ from modules import consts
19
+ from modules.progress_bars import Callback
20
+
21
+ except (ModuleNotFoundError, ImportError):
22
+ from .modules import consts
23
+ from .modules.progress_bars import Callback
24
+
25
+ logging.basicConfig(format='%(name)s %(levelname)s %(asctime)s %(message)s', datefmt='%I:%M:%S %p')
26
+ logger = logging.getLogger("BASE API")
27
+ logger.setLevel(logging.DEBUG)
28
+
29
+ def disable_logging():
30
+ logger.setLevel(logging.CRITICAL)
31
+
32
+
33
+ class Cache:
34
+ """
35
+ Caches content from network requests
36
+ """
37
+
38
+ def __init__(self):
39
+ self.cache_dictionary = {}
40
+ self.lock = threading.Lock()
41
+
42
+ def handle_cache(self, url):
43
+ if url is None:
44
+ return
45
+
46
+ with self.lock:
47
+ content = self.cache_dictionary.get(url, None)
48
+ return content
49
+
50
+ def save_cache(self, url, content):
51
+ with self.lock:
52
+ if len(self.cache_dictionary.keys()) >= consts.MAX_CACHE_ITEMS:
53
+ first_key = next(iter(self.cache_dictionary))
54
+ # Delete the first item
55
+ del self.cache_dictionary[first_key]
56
+ logger.info(f"Deleting: {first_key} from cache, due to caching limits...")
57
+
58
+ self.cache_dictionary[url] = content
59
+
60
+ cache = Cache()
61
+
62
+
63
+ class BaseCore:
64
+ """
65
+ The base class which has all necessary functions for other API packages
66
+ """
67
+ def __init__(self):
68
+ self.last_request_time = time.time()
69
+ self.total_requests = 0 # Tracks how many requests have been made
70
+ self.session = None
71
+ self.initialize_session()
72
+
73
+
74
+ def update_user_agent(self):
75
+ """Updates the User-Agent"""
76
+ self.session.headers.update({"User-Agent": random.choice(consts.USER_AGENTS)})
77
+
78
+ def initialize_session(self):
79
+ verify = True
80
+
81
+ if consts.PROXY is not None:
82
+ verify = False
83
+
84
+ self.session = httpx.Client(proxy=consts.PROXY,
85
+ headers=consts.HEADERS,
86
+ verify=verify,
87
+ timeout=consts.TIMEOUT
88
+ )
89
+
90
+ def enforce_delay(self):
91
+ """Enforces the specified delay in consts.REQUEST_DELAY"""
92
+ delay = consts.REQUEST_DELAY
93
+ if delay > 0:
94
+ time_since_last_request = time.time() - self.last_request_time
95
+ logger.debug(f"Time since last request: {time_since_last_request:.2f} seconds.")
96
+ if time_since_last_request < delay:
97
+ sleep_time = delay - time_since_last_request
98
+ logger.debug(f"Enforcing delay of {sleep_time:.2f} seconds.")
99
+ time.sleep(sleep_time)
100
+
101
+ def fetch(
102
+ self,
103
+ url: str,
104
+ get_bytes: bool = False,
105
+ timeout: int = consts.TIMEOUT,
106
+ get_response: bool = False,
107
+ save_cache: bool = True,
108
+ cookies: dict = None,
109
+ allow_redirects: bool = True,
110
+ ) -> Union[bytes, str, httpx.Response, None]:
111
+ """
112
+ Fetches content in UTF-8 Text, Bytes, or as a stream using multiple request attempts,
113
+ support for proxies and custom timeout.
114
+ """
115
+ # Check cache first
116
+ content = cache.handle_cache(url)
117
+ if content is not None:
118
+ logger.info(f"Fetched content for: {url} from cache!")
119
+ return content
120
+
121
+ for attempt in range(1, consts.MAX_RETRIES + 1):
122
+ try:
123
+ # Update user agent periodically
124
+ if self.total_requests % 3 == 0:
125
+ self.update_user_agent()
126
+
127
+ self.enforce_delay()
128
+
129
+ # Perform the request with stream handling
130
+ with self.session.stream("GET", url, timeout=timeout, cookies=cookies,
131
+ follow_redirects=allow_redirects) as response:
132
+ self.total_requests += 1
133
+
134
+ # Log and handle non-200 status codes
135
+ if response.status_code != 200:
136
+ logger.warning(
137
+ f"Attempt {attempt}: Unexpected status code {response.status_code} for URL: {url}")
138
+
139
+ if response.status_code == 404:
140
+ logger.error("Resource not found (404). This may indicate the content is unavailable.")
141
+ return None # Return None for unavailable resources
142
+
143
+ continue # Retry for other non-200 status codes
144
+
145
+ logger.debug(f"Attempt {attempt}: Successfully fetched URL: {url}")
146
+
147
+ # Return response if requested
148
+ if get_response:
149
+ return response
150
+
151
+ # Process and return content
152
+ if get_bytes:
153
+ content = b"".join([chunk for chunk in response.iter_bytes()])
154
+ else:
155
+ content = "".join([chunk.decode("utf-8") for chunk in response.iter_bytes()])
156
+ if save_cache:
157
+ logger.debug(f"Saving content of {url} to local cache.")
158
+ cache.save_cache(url, content)
159
+
160
+ return content
161
+
162
+ except httpx.RequestError as e:
163
+ logger.error(f"Attempt {attempt}: Request error for URL {url}: {e}")
164
+
165
+ except Exception:
166
+ logger.error(f"Attempt {attempt}: Unexpected error for URL {url}: {traceback.format_exc()}")
167
+
168
+ logger.info(f"Retrying ({attempt}/{consts.MAX_RETRIES}) for URL: {url}")
169
+
170
+ logger.error(f"Failed to fetch URL {url} after {consts.MAX_RETRIES} attempts.")
171
+ return None # Return None if all attempts fail
172
+
173
+ @classmethod
174
+ def strip_title(cls, title: str) -> str:
175
+ """
176
+ :param title:
177
+ :return: str: strips out non UTF-8 chars of the title
178
+ """
179
+ illegal_chars = '<>:"/\\|?*'
180
+ cleaned_title = ''.join([char for char in title if char in string.printable and char not in illegal_chars])
181
+ return cleaned_title
182
+
183
+ @lru_cache(maxsize=250)
184
+ def get_m3u8_by_quality(self, m3u8_url: str, quality: str) -> str:
185
+ """Fetches the m3u8 URL for a given quality by extracting all possible sub-m3u8 URLs from the primary
186
+ m3u8 playlist"""
187
+ playlist_content = self.fetch(url=m3u8_url)
188
+ playlist = m3u8.loads(playlist_content)
189
+ logger.debug(f"Resolved m3u8 playlist: {m3u8_url}")
190
+
191
+ if not playlist.is_variant:
192
+ raise ValueError("Provided URL is not a master playlist.")
193
+
194
+ # Extract available qualities and URLs
195
+ qualities = {
196
+ (variant.stream_info.resolution or "unknown"): variant.uri
197
+ for variant in playlist.playlists
198
+ } # Fetches the available qualities
199
+
200
+ # Sort qualities by resolution (width x height)
201
+ sorted_qualities = sorted(
202
+ qualities.items(),
203
+ key=lambda x: (x[0][0] * x[0][1]) if x[0] != "unknown" else 0
204
+ ) # Sorts qualities to support different HLS naming schemes
205
+
206
+ # Select based on quality preference
207
+ if quality == "best":
208
+ url_tmp = sorted_qualities[-1][1] # Highest resolution URL
209
+
210
+ elif quality == "worst":
211
+ url_tmp = sorted_qualities[0][1] # Lowest resolution URL
212
+
213
+ elif quality == "half":
214
+ url_tmp = sorted_qualities[len(sorted_qualities) // 2][1] # Mid-quality URL
215
+
216
+ else:
217
+ raise ValueError("Invalid quality provided.")
218
+
219
+ full_url = urljoin(m3u8_url, url_tmp) # Merges the primary with the new URL to get the full URL path
220
+ return full_url
221
+
222
+ @lru_cache(maxsize=250)
223
+ def get_segments(self, m3u8_url_master: str, quality: str) -> list:
224
+ """Gets all video segments from a given quality and the primary m3u8 URL"""
225
+ m3u8_url = self.get_m3u8_by_quality(m3u8_url=m3u8_url_master, quality=quality)
226
+ logger.debug(f"Trying to fetch segment from m3u8 ->: {m3u8_url}")
227
+ content = self.fetch(url=m3u8_url)
228
+ segments_ = m3u8.loads(content).segments
229
+ segments = []
230
+
231
+ for segment in segments_:
232
+ segments.append(urljoin(m3u8_url, segment.uri)) # Get the full URL path to segment
233
+
234
+ logger.debug(f"Fetched {len(segments)} segments from m3u8 URL")
235
+ return segments
236
+
237
+ def download(self, video, quality: str, downloader: str, path: str, callback=None) -> None:
238
+ """
239
+ :param video:
240
+ :param callback:
241
+ :param downloader:
242
+ :param quality:
243
+ :param path:
244
+ :return:
245
+ """
246
+
247
+ if callback is None:
248
+ callback = Callback.text_progress_bar
249
+
250
+ if downloader == "default":
251
+ self.default(video=video, quality=quality, path=path, callback=callback)
252
+
253
+ elif downloader == "threaded":
254
+ threaded_download = self.threaded(max_workers=20, timeout=10)
255
+ threaded_download(self, video=video, quality=quality, path=path, callback=callback)
256
+
257
+ elif downloader == "FFMPEG":
258
+ self.FFMPEG(video=video, quality=quality, path=path, callback=callback)
259
+
260
+ @classmethod
261
+ def download_segment(cls, url: str, timeout: int) -> tuple[str, bytes, bool]:
262
+ """
263
+ Attempt to download a single segment, retrying on failure.
264
+ Returns a tuple of the URL, content (empty if failed after retries), and a success flag.
265
+ """
266
+
267
+ response = BaseCore().fetch(url, timeout=timeout, get_response=True)
268
+ response.raise_for_status()
269
+ content = b"".join(response.iter_bytes())
270
+ return url, content, True # Success
271
+
272
+ def threaded(self, max_workers: int = 20, timeout: int = 10):
273
+ """
274
+ Creates a wrapper function for the actual download process, with retry logic.
275
+ """
276
+
277
+ def wrapper(self, video, quality: str, callback, path: str):
278
+ """
279
+ Download video segments in parallel, with retries for failures, and write to a file.
280
+ """
281
+ segments = self.get_segments(quality=quality, m3u8_url_master=video.m3u8_base_url)
282
+ length = len(segments)
283
+ completed, successful_downloads = 0, 0
284
+
285
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
286
+ future_to_hls_part = {
287
+ executor.submit(self.download_segment, url, timeout): os.path.basename(url)
288
+ for url in segments
289
+ }
290
+
291
+ for future in as_completed(future_to_hls_part):
292
+ hls_part = future_to_hls_part[future]
293
+ try:
294
+ _, data, success = future.result()
295
+ completed += 1
296
+ if success:
297
+ successful_downloads += 1
298
+ callback(completed, length) # Update progress callback
299
+ except Exception as e:
300
+ logger.error(f"Error processing segment {hls_part}: {e}")
301
+
302
+ # Write only successful segments to the output file
303
+ with open(path, 'wb') as file:
304
+ for segment_url in segments:
305
+ matched_futures = [
306
+ future for future, hls_part in future_to_hls_part.items()
307
+ if hls_part == os.path.basename(segment_url)
308
+ ]
309
+ if matched_futures:
310
+ future = matched_futures[0]
311
+ try:
312
+ _, data, success = future.result()
313
+ if success:
314
+ file.write(data)
315
+ except Exception as e:
316
+ logger.error(f"Exception writing segment {segment_url}: {e}")
317
+
318
+ return wrapper
319
+
320
+ def default(self, video, quality, callback, path, start: int = 0) -> bool:
321
+ buffer = b''
322
+ segments = self.get_segments(quality=quality, m3u8_url_master=video.m3u8_base_url)[start:]
323
+ length = len(segments)
324
+
325
+ for i, url in enumerate(segments):
326
+ for _ in range(5):
327
+
328
+ segment = self.fetch(url, get_bytes=True)
329
+ buffer += segment
330
+ callback(i + 1, length)
331
+ break
332
+
333
+ with open(path, 'wb') as file:
334
+ file.write(buffer)
335
+
336
+ return True
337
+
338
+ def FFMPEG(self, video, quality: str, callback, path: str) -> bool:
339
+ base_url = video.m3u8_base_url
340
+ new_segment = self.get_m3u8_by_quality(quality=quality, m3u8_url=base_url)
341
+ url_components = base_url.split('/')
342
+ url_components[-1] = new_segment
343
+ new_url = '/'.join(url_components)
344
+
345
+ # Build the command for FFMPEG as a list directly
346
+ command = [
347
+ consts.FFMPEG_PATH,
348
+ "-i", new_url, # Input URL
349
+ "-bsf:a", "aac_adtstoasc",
350
+ "-y", # Overwrite output files without asking
351
+ "-c", "copy", # Copy streams without re-encoding
352
+ path # Output file path
353
+ ]
354
+
355
+ # Initialize FfmpegProgress and execute the command
356
+ ff = FfmpegProgress(command)
357
+ for progress in ff.run_command_with_progress():
358
+ # Update the callback with the current progress
359
+ callback(int(round(progress)), 100)
360
+
361
+ if progress == 100:
362
+ return True
363
+
364
+ return False
365
+
366
+ def legacy_download(self, path: str, url: str, callback=None) -> bool:
367
+ """
368
+ Download a file using streaming, with support for progress updates.
369
+ """
370
+ try:
371
+ with self.session.stream("GET", url, timeout=30) as response: # Use a reasonable timeout
372
+ response.raise_for_status()
373
+
374
+ file_size = int(response.headers.get('content-length', 0))
375
+
376
+ if callback is None:
377
+ progress_bar = Callback()
378
+
379
+ downloaded_so_far = 0
380
+
381
+ # Open file for writing
382
+ with open(path, 'wb') as file:
383
+ for chunk in response.iter_bytes(chunk_size=1024):
384
+ if not chunk:
385
+ break # End of stream
386
+
387
+ file.write(chunk)
388
+ downloaded_so_far += len(chunk)
389
+
390
+ # Update progress
391
+ if callback:
392
+ callback(downloaded_so_far, file_size)
393
+ else:
394
+ progress_bar.text_progress_bar(downloaded=downloaded_so_far, total=file_size)
395
+
396
+ if not callback:
397
+ del progress_bar
398
+
399
+ return True
400
+
401
+ except httpx.RequestError as e:
402
+ logger.error(f"Request failed for URL {url}: {e}")
403
+ return False
404
+ except Exception as e:
405
+ logger.error(f"Unexpected error during download: {e}")
406
+ return False
407
+
408
+ @classmethod
409
+ def return_path(cls, video, args) -> str:
410
+ path = args.output
411
+ if args.use_title:
412
+ if not str(path).endswith(os.sep):
413
+ path += os.sep
414
+ path += video.title + ".mp4"
415
+ else:
416
+ path = args.output
417
+
418
+ return path
@@ -0,0 +1,16 @@
1
+ import random
2
+
3
+ MAX_CACHE_ITEMS = 200 # Lower this value if you are on a low-ram system (<=4 GB)
4
+ MAX_RETRIES = 4
5
+ REQUEST_DELAY = 0
6
+ TIMEOUT = 20 # Maximal request timeout
7
+ FFMPEG_PATH = "ffmpeg"
8
+ PROXY = None
9
+ USER_AGENTS = ["Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
10
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.1",
11
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.3",
12
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.3",
13
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0."]
14
+
15
+ HEADERS = {"User-Agent": random.choice(USER_AGENTS)}
16
+ COOKIES = None
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.1
2
+ Name: eaf_base_api
3
+ Version: 2.1
4
+ Summary: A base API for EchterAlsFake's Porn APIs
5
+ Home-page: https://github.com/EchterAlsFake/eaf_base_api
6
+ Author: Johannes Habel
7
+ Author-email: EchterAlsFake@proton.me
8
+ License: LGPLv3
9
+ Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
10
+ Classifier: Programming Language :: Python
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: ffmpeg-progress-yield
14
+ Requires-Dist: m3u8
15
+ Requires-Dist: httpx
16
+
17
+ # EAF Base API
18
+
19
+ # What is this?
20
+ When using one of my Porn site APIs, you probably came across this package and wondered what it actually does, so here's
21
+ a detailed answer.
22
+
23
+ A lot of Porn sites use very similar methods for m3u8 (HLS) parsing and other things. I also wanted to implement proxy
24
+ support, and there was a lot of code that I would have rewritten in every API again and again. That's why I made this API
25
+ package. The `BaseCore` class does all the necessary stuff like m3u8 parsing, a great caching system, network request
26
+ fetching with retry attempts and proxy support.
27
+
28
+ # Using Proxies / Caching
29
+ There's a small documentation for this project.
30
+ <br>Please have a look at it: https://github.com/EchterAlsFake/API_Docs/blob/master/Porn_APIs/eaf_base_api.md
31
+
32
+
33
+ # Can I use this for myself?
34
+ Yes, you can, but I may change stuff here and there from time to time, and it would maybe break your project.
35
+ I would not recommend you to install and use it as a package, but just copy the code you need.
36
+
37
+ I can recommend everyone the download functions for HLS streaming since, for example, the threaded preset is very well
38
+ optimized. If you just use mine, you need to consume less caffeine and brain cells to make such a function :)
39
+
40
+
41
+ # License
42
+ Licensed under The [LGPLv3](https://www.gnu.org/licenses/lgpl-3.0.en.html) license.
43
+ <br>Copyright (C) 2024-2025 Johannes Habel
@@ -1,12 +1,11 @@
1
+ LICENSE
1
2
  README.md
2
3
  setup.py
3
4
  base_api/__init__.py
4
5
  base_api/base.py
5
6
  base_api/modules/__init__.py
6
7
  base_api/modules/consts.py
7
- base_api/modules/download.py
8
8
  base_api/modules/progress_bars.py
9
- base_api/modules/quality.py
10
9
  eaf_base_api.egg-info/PKG-INFO
11
10
  eaf_base_api.egg-info/SOURCES.txt
12
11
  eaf_base_api.egg-info/dependency_links.txt
@@ -1,2 +1,3 @@
1
- requests
2
1
  ffmpeg-progress-yield
2
+ m3u8
3
+ httpx
@@ -2,10 +2,9 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name="eaf_base_api",
5
- version="1.6.3",
5
+ version="2.1",
6
6
  packages=find_packages(),
7
- install_requires=[
8
- "requests", "ffmpeg-progress-yield"
7
+ install_requires=["ffmpeg-progress-yield", "m3u8", "httpx"
9
8
  ],
10
9
  entry_points={
11
10
  'console_scripts': [
@@ -1,44 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: eaf_base_api
3
- Version: 1.6.3
4
- Summary: A base API for EchterAlsFake's Porn APIs
5
- Home-page: https://github.com/EchterAlsFake/eaf_base_api
6
- Author: Johannes Habel
7
- Author-email: EchterAlsFake@proton.me
8
- License: LGPLv3
9
- Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
10
- Classifier: Programming Language :: Python
11
- Description-Content-Type: text/markdown
12
- Requires-Dist: requests
13
- Requires-Dist: ffmpeg-progress-yield
14
-
15
- # EAF Base API
16
-
17
- ! Still in Development
18
-
19
- This Python package is a base api for all my Porn Site APIs. A lot of sites use the same methods, and
20
- there's a lot of code that I've rewritten again and again. This is why I created this base api, so that
21
- I need to write less code and everything is easier to be maintainable.
22
-
23
- # PRs
24
- Pull Requests are welcome, but if you make changes run `pytest` on all APIs that are using this to make sure your
25
- PR didn't break anything.
26
-
27
- # Documentation
28
-
29
- As this is some kind of 'raw' base API, this won't be documented, as it's only functional when used together
30
- with the main APIs.
31
-
32
- Maybe you can look at the code comments. They could be helpful
33
-
34
- # Implementation
35
- You are welcome to implement this API in your own projects. If it's useful... But I don't recommend this, as things
36
- might change without a warning. But things like the threaded downloads can be useful for other projects :)
37
-
38
- I'd say the threaded modes from the download module are already very well optimized, so feel free to just copy them
39
- for your own projects. You don't need to do any attribution, I don't care :)
40
-
41
-
42
- # License
43
-
44
- LGPLv3
@@ -1,30 +0,0 @@
1
- # EAF Base API
2
-
3
- ! Still in Development
4
-
5
- This Python package is a base api for all my Porn Site APIs. A lot of sites use the same methods, and
6
- there's a lot of code that I've rewritten again and again. This is why I created this base api, so that
7
- I need to write less code and everything is easier to be maintainable.
8
-
9
- # PRs
10
- Pull Requests are welcome, but if you make changes run `pytest` on all APIs that are using this to make sure your
11
- PR didn't break anything.
12
-
13
- # Documentation
14
-
15
- As this is some kind of 'raw' base API, this won't be documented, as it's only functional when used together
16
- with the main APIs.
17
-
18
- Maybe you can look at the code comments. They could be helpful
19
-
20
- # Implementation
21
- You are welcome to implement this API in your own projects. If it's useful... But I don't recommend this, as things
22
- might change without a warning. But things like the threaded downloads can be useful for other projects :)
23
-
24
- I'd say the threaded modes from the download module are already very well optimized, so feel free to just copy them
25
- for your own projects. You don't need to do any attribution, I don't care :)
26
-
27
-
28
- # License
29
-
30
- LGPLv3
@@ -1,5 +0,0 @@
1
- __all__ = ["Core", "Quality", "setup_api", "default", "threaded", "FFMPEG", "Callback"]
2
-
3
- from base_api.base import Core, Quality, setup_api
4
- from base_api.modules.download import default, threaded, FFMPEG
5
- from base_api.modules.progress_bars import Callback
@@ -1,181 +0,0 @@
1
- import requests
2
- import logging
3
- import time
4
- import string
5
- import os
6
-
7
- from base_api.modules.quality import Quality
8
- from base_api.modules.progress_bars import Callback
9
- from base_api.modules.download import default, threaded, FFMPEG
10
- from base_api.modules.consts import MAX_RETRIES, REQUEST_DELAY
11
-
12
- def setup_api(do_logging=False):
13
- if do_logging:
14
- logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
15
- logging.getLogger("urllib3").setLevel(logging.WARNING)
16
-
17
- else:
18
- logging.disable(logging.CRITICAL)
19
-
20
-
21
- class Core:
22
- def __init__(self, delay=REQUEST_DELAY):
23
- self.delay = delay
24
- self.start_delay = False
25
- self.last_request_time = None
26
-
27
- def get_content(self, url, headers=None, cookies=None, stream=False):
28
- for i in range(MAX_RETRIES):
29
- try:
30
- # Delay mechanism
31
- if self.last_request_time:
32
- elapsed_time = time.time() - self.last_request_time
33
- if elapsed_time < self.delay:
34
- time.sleep(self.delay - elapsed_time)
35
-
36
- self.last_request_time = time.time() # Update the time of the last request
37
-
38
- logging.debug(f"Trying to fetch {url} / Attempt: [{i+1}]")
39
- response = requests.get(url, headers=headers, cookies=cookies, stream=stream)
40
- if response.status_code == 200:
41
- logging.info(f"Successfully fetched {url} on attempt [{i+1}]")
42
- return response.content
43
-
44
- else:
45
- logging.warning(f"Failed to fetch {url} with status code {response.status_code} on attempt [{i+1}]")
46
-
47
- except requests.exceptions.RequestException as e:
48
- logging.error(f"Exception occurred when trying to fetch {url} on attempt [{i+1}]: {e}")
49
-
50
- if i < MAX_RETRIES - 1: # Implement exponential backoff
51
- time.sleep(2 ** i)
52
-
53
- logging.error(f"Failed to fetch {url} after {MAX_RETRIES} attempts.")
54
- logging.error("Returning None")
55
- return None
56
-
57
- @classmethod
58
- def fix_quality(cls, quality):
59
- """This method gives the user the opportunity to pass a string instead of the quality object"""
60
- if isinstance(quality, Quality):
61
- return quality
62
-
63
- elif str(quality) == "best":
64
- return Quality.BEST
65
-
66
- elif str(quality) == "half":
67
- return Quality.HALF
68
-
69
- elif str(quality) == "worst":
70
- return Quality.WORST
71
-
72
- def get_available_qualities(self, m3u8_base_url, base_qualities, seperator):
73
- """Returns the available qualities from the M3U8 base url"""
74
- content = self.get_content(m3u8_base_url).decode("utf-8")
75
- lines = content.splitlines()
76
-
77
- quality_url_map = {}
78
-
79
- for line in lines:
80
- for quality in base_qualities:
81
- if f"{seperator}{quality}" in line and not str(line).startswith("#"):
82
- quality_url_map[quality] = line
83
-
84
- self.quality_url_map = quality_url_map
85
- self.available_qualities = list(quality_url_map.keys())
86
- return self.available_qualities
87
-
88
- def get_m3u8_by_quality(self, quality, m3u8_base_url, base_qualities, seperator):
89
- """Returns the m3u8 url for the given quality"""
90
- quality = self.fix_quality(quality)
91
-
92
- self.get_available_qualities(m3u8_base_url, base_qualities, seperator=seperator)
93
- if quality == Quality.BEST:
94
- selected_quality = max(self.available_qualities, key=lambda q: base_qualities.index(q))
95
- elif quality == Quality.WORST:
96
- selected_quality = min(self.available_qualities, key=lambda q: base_qualities.index(q))
97
- elif quality == Quality.HALF:
98
- sorted_qualities = sorted(self.available_qualities, key=lambda q: base_qualities.index(q))
99
- middle_index = len(sorted_qualities) // 2
100
- selected_quality = sorted_qualities[middle_index]
101
-
102
- return self.quality_url_map.get(selected_quality)
103
-
104
- def download(self, video, quality, downloader, path, callback=None):
105
- """
106
- :param callback:
107
- :param downloader:
108
- :param quality:
109
- :param path:
110
- :return:
111
- """
112
- quality = self.fix_quality(quality)
113
-
114
- if callback is None:
115
- callback = Callback.text_progress_bar
116
-
117
- if downloader == default or str(downloader) == "default":
118
- default(video=video, quality=quality, path=path, callback=callback)
119
-
120
- elif downloader == threaded or str(downloader) == "threaded":
121
- threaded_download = threaded(max_workers=20, timeout=10)
122
- threaded_download(video=video, quality=quality, path=path, callback=callback)
123
-
124
- elif downloader == FFMPEG or str(downloader) == "FFMPEG":
125
- FFMPEG(video=video, quality=quality, path=path, callback=callback)
126
-
127
- @classmethod
128
- def get_segments(cls, quality, m3u8_base_url, base_qualities, seperator, source=1):
129
- quality = Core().fix_quality(quality)
130
- base_url = m3u8_base_url
131
- new_segment = Core().get_m3u8_by_quality(quality, m3u8_base_url=base_url, base_qualities=base_qualities,
132
- seperator=seperator)
133
- # Split the base URL into components
134
- url_components = base_url.split('/')
135
-
136
- # Replace the last component with the new segment
137
- url_components[-1] = new_segment
138
-
139
- # Rejoin the components into the new full URL
140
- new_url = '/'.join(url_components)
141
-
142
- if source == "spankbang":
143
- new_url = new_url.split(".mp4.urlset/")[1] # Please just don't ask, I'm a terrible programmer fr
144
-
145
- master_src = Core().get_content(url=new_url).decode("utf-8")
146
-
147
- urls = [l for l in master_src.splitlines()
148
- if l and not l.startswith('#')]
149
-
150
- segments = []
151
-
152
- for url in urls:
153
- url_components[-1] = url
154
- new_url = '/'.join(url_components)
155
- segments.append(new_url)
156
-
157
- return segments
158
-
159
- @classmethod
160
- def strip_title(cls, title: str) -> str:
161
- """
162
- :param title:
163
- :return: str: strips out non UTF-8 chars of the title
164
- """
165
- illegal_chars = '<>:"/\\|?*'
166
- cleaned_title = ''.join([char for char in title if char in string.printable and char not in illegal_chars])
167
- return cleaned_title
168
-
169
- @classmethod
170
- def return_path(cls, video, args):
171
- path = args.output
172
- if args.use_title:
173
- if not str(path).endswith(os.sep):
174
- path += os.sep
175
-
176
- path += video.title + ".mp4"
177
-
178
- else:
179
- path = args.output
180
-
181
- return path
@@ -1,3 +0,0 @@
1
- MAX_RETRIES = 4
2
- REQUEST_DELAY = 0
3
- FFMPEG_PATH = "ffmpeg"
@@ -1,166 +0,0 @@
1
- # Thanks to: https://github.com/EchterAlsFake/PHUB/blob/master/src/phub/modules/download.py
2
- # oh and of course ChatGPT lol
3
- import logging
4
- import time
5
- import requests
6
- import os
7
- from ffmpeg_progress_yield import FfmpegProgress
8
- from concurrent.futures import ThreadPoolExecutor, as_completed
9
- from typing import Callable, List
10
- from base_api.modules.progress_bars import Callback
11
-
12
- try:
13
- from base_api.modules.consts import FFMPEG_PATH
14
-
15
- except (ModuleNotFoundError, ImportError):
16
- from .consts import FFMPEG_PATH
17
-
18
- CallbackType = Callable[[int, int], None]
19
-
20
- """
21
- Important: The title of the video isn't applied to the output path. You need to manually append it to
22
- the output path. This has good reasons, to make this library more adaptable into other applications.
23
- """
24
-
25
-
26
- def download_segment(url: str, timeout: int, retries: int = 3, backoff_factor: float = 0.3) -> tuple[str, bytes, bool]:
27
- """
28
- Attempt to download a single segment, retrying on failure.
29
- Returns a tuple of the URL, content (empty if failed after retries), and a success flag.
30
- """
31
- for attempt in range(retries):
32
- try:
33
- response = requests.get(url, timeout=timeout)
34
- response.raise_for_status() # Raises stored HTTPError, if one occurred.
35
- return (url, response.content, True) # Success
36
- except requests.RequestException as e:
37
- print(f"Retry {attempt + 1} for {url}: {e}")
38
- time.sleep(backoff_factor * (2 ** attempt)) # Exponential backoff
39
-
40
- # After all retries have failed
41
- return (url, b'', False) # Failed download
42
-
43
-
44
- def threaded(max_workers: int = 20, timeout: int = 10, retries: int = 3):
45
- """
46
- Creates a wrapper function for the actual download process, with retry logic.
47
- """
48
- def wrapper(video, quality, callback, path):
49
- """
50
- Download video segments in parallel, with retries for failures, and write to a file.
51
- """
52
- segments = video.get_segments(quality=quality)
53
- length = len(segments)
54
- completed, successful_downloads = 0, 0
55
-
56
- with ThreadPoolExecutor(max_workers=max_workers) as executor:
57
- # Map the last part of the URL (filename) to the future
58
- future_to_hls_part = {executor.submit(download_segment, url, timeout, retries): os.path.basename(url) for url in segments}
59
-
60
- for future in as_completed(future_to_hls_part):
61
- hls_part = future_to_hls_part[future]
62
- try:
63
- _, data, success = future.result()
64
- completed += 1
65
- if success:
66
- successful_downloads += 1
67
- callback(completed, length) # Update callback regardless of success to reflect progress
68
- except Exception as e:
69
- raise e
70
-
71
- # Writing only successful downloads to the file
72
- with open(path, 'wb') as file:
73
- for segment_url in segments:
74
- # Find the future object using the HLS part of the URL as the key
75
- matched_futures = [future for future, hls_part in future_to_hls_part.items() if hls_part == os.path.basename(segment_url)]
76
- if matched_futures:
77
- logging.info("Got a match")
78
- future = matched_futures[0] # Assuming unique HLS parts, take the first match
79
- try:
80
- _, data, success = future.result()
81
- if success:
82
- file.write(data)
83
- except Exception as e:
84
- pass # Optionally handle or log the exception here
85
-
86
- return wrapper
87
-
88
-
89
- def default(video, quality, callback, path, start: int = 0) -> bool:
90
- buffer = b''
91
- segments = video.get_segments(quality)[start:]
92
- length = len(segments)
93
-
94
- for i, url in enumerate(segments):
95
- for _ in range(5):
96
-
97
- segment = requests.get(url)
98
-
99
- if segment.ok:
100
- buffer += segment.content
101
- callback(i + 1, length)
102
- break
103
-
104
- with open(path, 'wb') as file:
105
- file.write(buffer)
106
-
107
- return True
108
-
109
-
110
- def FFMPEG(video, quality, callback, path, start=0) -> bool:
111
- base_url = video.m3u8_base_url
112
- new_segment = video.get_m3u8_by_quality(quality)
113
- url_components = base_url.split('/')
114
- url_components[-1] = new_segment
115
- new_url = '/'.join(url_components)
116
-
117
- # Build the command for FFMPEG as a list directly
118
- command = [
119
- FFMPEG_PATH,
120
- "-i", new_url, # Input URL
121
- "-bsf:a", "aac_adtstoasc",
122
- "-y", # Overwrite output files without asking
123
- "-c", "copy", # Copy streams without reencoding
124
- path # Output file path
125
- ]
126
-
127
- # Initialize FfmpegProgress and execute the command
128
- ff = FfmpegProgress(command)
129
- for progress in ff.run_command_with_progress():
130
- # Update the callback with the current progress
131
- callback(int(round(progress)), 100)
132
-
133
- if progress == 100:
134
- return True
135
-
136
- return False
137
-
138
-
139
- def legacy_download(stream, path, url, callback=None):
140
- response = requests.get(url, stream=stream)
141
- file_size = int(response.headers.get('content-length', 0))
142
-
143
- if callback is None:
144
- progress_bar = Callback()
145
-
146
- downloaded_so_far = 0
147
-
148
- if not os.path.exists(path):
149
- with open(path, 'wb') as file:
150
- for chunk in response.iter_content(chunk_size=1024):
151
- file.write(chunk)
152
- downloaded_so_far += len(chunk)
153
-
154
- if callback:
155
- callback(downloaded_so_far, file_size)
156
-
157
- else:
158
- progress_bar.text_progress_bar(downloaded=downloaded_so_far, total=file_size)
159
-
160
- if not callback:
161
- del progress_bar
162
-
163
- return True
164
-
165
- else:
166
- raise FileExistsError("The file already exists.")
@@ -1,7 +0,0 @@
1
- from enum import Enum
2
-
3
-
4
- class Quality(Enum):
5
- BEST = 'BEST'
6
- HALF = 'HALF'
7
- WORST = 'WORST'
@@ -1,44 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: eaf_base_api
3
- Version: 1.6.3
4
- Summary: A base API for EchterAlsFake's Porn APIs
5
- Home-page: https://github.com/EchterAlsFake/eaf_base_api
6
- Author: Johannes Habel
7
- Author-email: EchterAlsFake@proton.me
8
- License: LGPLv3
9
- Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
10
- Classifier: Programming Language :: Python
11
- Description-Content-Type: text/markdown
12
- Requires-Dist: requests
13
- Requires-Dist: ffmpeg-progress-yield
14
-
15
- # EAF Base API
16
-
17
- ! Still in Development
18
-
19
- This Python package is a base api for all my Porn Site APIs. A lot of sites use the same methods, and
20
- there's a lot of code that I've rewritten again and again. This is why I created this base api, so that
21
- I need to write less code and everything is easier to be maintainable.
22
-
23
- # PRs
24
- Pull Requests are welcome, but if you make changes run `pytest` on all APIs that are using this to make sure your
25
- PR didn't break anything.
26
-
27
- # Documentation
28
-
29
- As this is some kind of 'raw' base API, this won't be documented, as it's only functional when used together
30
- with the main APIs.
31
-
32
- Maybe you can look at the code comments. They could be helpful
33
-
34
- # Implementation
35
- You are welcome to implement this API in your own projects. If it's useful... But I don't recommend this, as things
36
- might change without a warning. But things like the threaded downloads can be useful for other projects :)
37
-
38
- I'd say the threaded modes from the download module are already very well optimized, so feel free to just copy them
39
- for your own projects. You don't need to do any attribution, I don't care :)
40
-
41
-
42
- # License
43
-
44
- LGPLv3
File without changes