eaf-base-api 1.6.2__tar.gz → 2.0__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.0
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: requests
14
+ Requires-Dist: ffmpeg-progress-yield
15
+ Requires-Dist: m3u8
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,382 @@
1
+ import os
2
+ import m3u8
3
+ import time
4
+ import random
5
+ import string
6
+ import logging
7
+ import requests
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 = requests.Session()
71
+ self.session.headers.update(consts.HEADERS)
72
+
73
+ def update_user_agent(self):
74
+ """Updates the User-Agent"""
75
+ self.session.headers.update({"User-Agent": random.choice(consts.USER_AGENTS)})
76
+
77
+ def enforce_delay(self):
78
+ """Enforces the specified delay in consts.REQUEST_DELAY"""
79
+ delay = consts.REQUEST_DELAY
80
+ if delay > 0:
81
+ time_since_last_request = time.time() - self.last_request_time
82
+ logger.debug(f"Time since last request: {time_since_last_request:.2f} seconds.")
83
+ if time_since_last_request < delay:
84
+ sleep_time = delay - time_since_last_request
85
+ logger.debug(f"Enforcing delay of {sleep_time:.2f} seconds.")
86
+ time.sleep(sleep_time)
87
+
88
+ def fetch(self, url: str, get_bytes: bool = False, stream: bool = False, timeout: int = consts.TIMEOUT,
89
+ get_response: bool = False, save_cache: bool = True, cookies: dict = None,
90
+ allow_redirects: bool = True) -> Union[bytes, str, requests.Response]:
91
+ """
92
+ Fetches content in UTF-8 Text, Bytes or as a stream using multiple request attempts, support for proxies
93
+ and custom timeout.
94
+ """
95
+ content = cache.handle_cache(url)
96
+ if content is not None:
97
+ logger.info(f"Fetched content for: {url} from cache!")
98
+ return content
99
+
100
+ for attempt in range(1, consts.MAX_RETRIES):
101
+ if self.total_requests % 3 == 0: # Change user agent after 3 requests to prevent bot detection
102
+ self.update_user_agent()
103
+
104
+ try:
105
+ self.enforce_delay()
106
+ if consts.USE_PROXIES:
107
+ verify = False # Disable SSL verification
108
+ url = url.replace("https://", "http://") # Replace https to http to support HTTP proxies
109
+
110
+ else:
111
+ verify = True
112
+
113
+ response = self.session.get(url, stream=stream, proxies=consts.PROXIES, verify=verify,
114
+ timeout=timeout, allow_redirects=allow_redirects, cookies=cookies)
115
+
116
+ if response.status_code != 200:
117
+ logger.error(f"Unexpected status code {response.status_code} for URL: {url}")
118
+
119
+ if response.status_code == 404:
120
+ logger.error("Website returned 404. Not an issue for xivdeos, but for all other sites")
121
+ return response # Needed for xvideos. Means that video is unavailable lol
122
+
123
+ continue
124
+
125
+ if get_response:
126
+ return response
127
+
128
+ self.total_requests += 1
129
+
130
+ except Exception:
131
+ error = traceback.format_exc()
132
+ logger.error(f"Could not fetch: {url} ->: {error}")
133
+ continue # Next attempt
134
+
135
+ logger.debug(f"[{attempt}|{consts.MAX_RETRIES}] Fetch ->: {url}")
136
+
137
+ logger.debug(f"[{attempt}|{consts.MAX_RETRIES}] Fetch ->: 200 | Success")
138
+ if get_bytes is False:
139
+ content = response.content.decode("utf-8")
140
+ if save_cache:
141
+ logger.debug(f"Trying to save content of: {url} in local cache...")
142
+ cache.save_cache(url, content)
143
+
144
+ return content
145
+
146
+ return response.content
147
+
148
+ raise ConnectionError(f"Could not fetch content for: {url}")
149
+
150
+ @classmethod
151
+ def strip_title(cls, title: str) -> str:
152
+ """
153
+ :param title:
154
+ :return: str: strips out non UTF-8 chars of the title
155
+ """
156
+ illegal_chars = '<>:"/\\|?*'
157
+ cleaned_title = ''.join([char for char in title if char in string.printable and char not in illegal_chars])
158
+ return cleaned_title
159
+
160
+ @lru_cache(maxsize=250)
161
+ def get_m3u8_by_quality(self, m3u8_url: str, quality: str) -> str:
162
+ """Fetches the m3u8 URL for a given quality by extracting all possible sub-m3u8 URLs from the primary
163
+ m3u8 playlist"""
164
+ playlist_content = self.fetch(url=m3u8_url)
165
+ playlist = m3u8.loads(playlist_content)
166
+ logger.debug(f"Resolved m3u8 playlist: {m3u8_url}")
167
+
168
+ if not playlist.is_variant:
169
+ raise ValueError("Provided URL is not a master playlist.")
170
+
171
+ # Extract available qualities and URLs
172
+ qualities = {
173
+ (variant.stream_info.resolution or "unknown"): variant.uri
174
+ for variant in playlist.playlists
175
+ } # Fetches the available qualities
176
+
177
+ # Sort qualities by resolution (width x height)
178
+ sorted_qualities = sorted(
179
+ qualities.items(),
180
+ key=lambda x: (x[0][0] * x[0][1]) if x[0] != "unknown" else 0
181
+ ) # Sorts qualities to support different HLS naming schemes
182
+
183
+ # Select based on quality preference
184
+ if quality == "best":
185
+ url_tmp = sorted_qualities[-1][1] # Highest resolution URL
186
+
187
+ elif quality == "worst":
188
+ url_tmp = sorted_qualities[0][1] # Lowest resolution URL
189
+
190
+ elif quality == "half":
191
+ url_tmp = sorted_qualities[len(sorted_qualities) // 2][1] # Mid-quality URL
192
+
193
+ else:
194
+ raise ValueError("Invalid quality provided.")
195
+
196
+ full_url = urljoin(m3u8_url, url_tmp) # Merges the primary with the new URL to get the full URL path
197
+ return full_url
198
+
199
+ @lru_cache(maxsize=250)
200
+ def get_segments(self, m3u8_url_master: str, quality: str) -> list:
201
+ """Gets all video segments from a given quality and the primary m3u8 URL"""
202
+ m3u8_url = self.get_m3u8_by_quality(m3u8_url=m3u8_url_master, quality=quality)
203
+ logger.debug(f"Trying to fetch segment from m3u8 ->: {m3u8_url}")
204
+ content = self.fetch(url=m3u8_url)
205
+ segments_ = m3u8.loads(content).segments
206
+ segments = []
207
+
208
+ for segment in segments_:
209
+ segments.append(urljoin(m3u8_url, segment.uri)) # Get the full URL path to segment
210
+
211
+ logger.debug(f"Fetched {len(segments)} segments from m3u8 URL")
212
+ return segments
213
+
214
+ def download(self, video, quality: str, downloader: str, path: str, callback=None) -> None:
215
+ """
216
+ :param video:
217
+ :param callback:
218
+ :param downloader:
219
+ :param quality:
220
+ :param path:
221
+ :return:
222
+ """
223
+
224
+ if callback is None:
225
+ callback = Callback.text_progress_bar
226
+
227
+ if downloader == "default":
228
+ self.default(video=video, quality=quality, path=path, callback=callback)
229
+
230
+ elif downloader == "threaded":
231
+ threaded_download = self.threaded(max_workers=20, timeout=10)
232
+ threaded_download(self, video=video, quality=quality, path=path, callback=callback)
233
+
234
+ elif downloader == "FFMPEG":
235
+ self.FFMPEG(video=video, quality=quality, path=path, callback=callback)
236
+
237
+ @classmethod
238
+ def download_segment(cls, url: str, timeout: int) -> tuple[str, bytes, bool]:
239
+ """
240
+ Attempt to download a single segment, retrying on failure.
241
+ Returns a tuple of the URL, content (empty if failed after retries), and a success flag.
242
+ """
243
+
244
+ response = BaseCore().fetch(url, timeout=timeout, get_response=True)
245
+ response.raise_for_status()
246
+ return url, response.content, True # Success
247
+
248
+ def threaded(self, max_workers: int = 20, timeout: int = 10):
249
+ """
250
+ Creates a wrapper function for the actual download process, with retry logic.
251
+ """
252
+
253
+ def wrapper(self, video, quality: str, callback, path: str):
254
+ """
255
+ Download video segments in parallel, with retries for failures, and write to a file.
256
+ """
257
+ segments = self.get_segments(quality=quality, m3u8_url_master=video.m3u8_base_url)
258
+ length = len(segments)
259
+ completed, successful_downloads = 0, 0
260
+
261
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
262
+ # Map the last part of the URL (filename) to the future
263
+ future_to_hls_part = {executor.submit(self.download_segment, url, timeout): os.path.basename(url) for
264
+ url in
265
+ segments}
266
+
267
+ for future in as_completed(future_to_hls_part):
268
+ hls_part = future_to_hls_part[future]
269
+ try:
270
+ _, data, success = future.result()
271
+ completed += 1
272
+ if success:
273
+ successful_downloads += 1
274
+ callback(completed, length) # Update callback regardless of success to reflect progress
275
+ except Exception as e:
276
+ raise e
277
+
278
+ # Writing only successful downloads to the file
279
+ with open(path, 'wb') as file:
280
+ for segment_url in segments:
281
+ # Find the future object using the HLS part of the URL as the key
282
+ matched_futures = [future for future, hls_part in future_to_hls_part.items() if
283
+ hls_part == os.path.basename(segment_url)]
284
+ if matched_futures:
285
+ logging.info("Got a match")
286
+ future = matched_futures[0] # Assuming unique HLS parts, take the first match
287
+ try:
288
+ _, data, success = future.result()
289
+ if success:
290
+ file.write(data)
291
+ except Exception:
292
+ error = traceback.format_exc()
293
+ logger.error(f"Exception while downloading segment: {error}")
294
+
295
+ return wrapper
296
+
297
+ def default(self, video, quality, callback, path, start: int = 0) -> bool:
298
+ buffer = b''
299
+ segments = self.get_segments(quality=quality, m3u8_url_master=video.m3u8_base_url)[start:]
300
+ length = len(segments)
301
+
302
+ for i, url in enumerate(segments):
303
+ for _ in range(5):
304
+
305
+ segment = self.fetch(url, get_bytes=True)
306
+ buffer += segment
307
+ callback(i + 1, length)
308
+ break
309
+
310
+ with open(path, 'wb') as file:
311
+ file.write(buffer)
312
+
313
+ return True
314
+
315
+ def FFMPEG(self, video, quality: str, callback, path: str) -> bool:
316
+ base_url = video.m3u8_base_url
317
+ new_segment = self.get_m3u8_by_quality(quality=quality, m3u8_url=base_url)
318
+ url_components = base_url.split('/')
319
+ url_components[-1] = new_segment
320
+ new_url = '/'.join(url_components)
321
+
322
+ # Build the command for FFMPEG as a list directly
323
+ command = [
324
+ consts.FFMPEG_PATH,
325
+ "-i", new_url, # Input URL
326
+ "-bsf:a", "aac_adtstoasc",
327
+ "-y", # Overwrite output files without asking
328
+ "-c", "copy", # Copy streams without reencoding
329
+ path # Output file path
330
+ ]
331
+
332
+ # Initialize FfmpegProgress and execute the command
333
+ ff = FfmpegProgress(command)
334
+ for progress in ff.run_command_with_progress():
335
+ # Update the callback with the current progress
336
+ callback(int(round(progress)), 100)
337
+
338
+ if progress == 100:
339
+ return True
340
+
341
+ return False
342
+
343
+ def legacy_download(self, stream: bool, path: str, url: str, callback=None) -> bool:
344
+ response = self.fetch(url, stream=stream, get_bytes=True, get_response=True)
345
+ file_size = int(response.headers.get('content-length', 0))
346
+
347
+ if callback is None:
348
+ progress_bar = Callback()
349
+
350
+ downloaded_so_far = 0
351
+
352
+ if not os.path.exists(path):
353
+ with open(path, 'wb') as file:
354
+ for chunk in response.iter_content(chunk_size=1024):
355
+ file.write(chunk)
356
+ downloaded_so_far += len(chunk)
357
+
358
+ if callback:
359
+ callback(downloaded_so_far, file_size)
360
+
361
+ else:
362
+ progress_bar.text_progress_bar(downloaded=downloaded_so_far, total=file_size)
363
+
364
+ if not callback:
365
+ del progress_bar
366
+
367
+ return True
368
+
369
+ else:
370
+ raise FileExistsError("The file already exists.")
371
+
372
+ @classmethod
373
+ def return_path(cls, video, args) -> str:
374
+ path = args.output
375
+ if args.use_title:
376
+ if not str(path).endswith(os.sep):
377
+ path += os.sep
378
+ path += video.title + ".mp4"
379
+ else:
380
+ path = args.output
381
+
382
+ return path
@@ -0,0 +1,17 @@
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
+ USE_PROXIES = False
9
+ PROXIES = {}
10
+ USER_AGENTS = ["Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
11
+ "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",
12
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.3",
13
+ "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",
14
+ "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."]
15
+
16
+ HEADERS = {"User-Agent": random.choice(USER_AGENTS)}
17
+ COOKIES = None
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.1
2
+ Name: eaf_base_api
3
+ Version: 2.0
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: requests
14
+ Requires-Dist: ffmpeg-progress-yield
15
+ Requires-Dist: m3u8
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
1
  requests
2
2
  ffmpeg-progress-yield
3
+ m3u8
@@ -2,10 +2,10 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name="eaf_base_api",
5
- version="1.6.2",
5
+ version="2.0",
6
6
  packages=find_packages(),
7
7
  install_requires=[
8
- "requests", "ffmpeg-progress-yield"
8
+ "requests", "ffmpeg-progress-yield", "m3u8"
9
9
  ],
10
10
  entry_points={
11
11
  'console_scripts': [
@@ -1,44 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: eaf_base_api
3
- Version: 1.6.2
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,184 +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
- from pathlib import Path
12
-
13
-
14
- def setup_api(do_logging=False):
15
- if do_logging:
16
- logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
17
- logging.getLogger("urllib3").setLevel(logging.WARNING)
18
-
19
- else:
20
- logging.disable(logging.CRITICAL)
21
-
22
-
23
- class Core:
24
- def __init__(self, delay=REQUEST_DELAY):
25
- self.delay = delay
26
- self.start_delay = False
27
- self.last_request_time = None
28
-
29
- def get_content(self, url, headers=None, cookies=None, stream=False):
30
- for i in range(MAX_RETRIES):
31
- try:
32
-
33
- # Delay mechanism
34
- if self.last_request_time:
35
- elapsed_time = time.time() - self.last_request_time
36
- if elapsed_time < self.delay:
37
- time.sleep(self.delay - elapsed_time)
38
-
39
- self.last_request_time = time.time() # Update the time of the last request
40
-
41
- logging.debug(f"Trying to fetch {url} / Attempt: [{i+1}]")
42
- response = requests.get(url, headers=headers, cookies=cookies, stream=stream)
43
- if response.status_code == 200:
44
- logging.info(f"Successfully fetched {url} on attempt [{i+1}]")
45
- return response.content
46
- else:
47
- logging.warning(f"Failed to fetch {url} with status code {response.status_code} on attempt [{i+1}]")
48
- except requests.exceptions.RequestException as e:
49
- logging.error(f"Exception occurred when trying to fetch {url} on attempt [{i+1}]: {e}")
50
- if i < MAX_RETRIES - 1: # Implement exponential backoff
51
- time.sleep(2 ** i)
52
- logging.error(f"Failed to fetch {url} after {MAX_RETRIES} attempts.")
53
- logging.error("Returning None")
54
- return None
55
-
56
- @classmethod
57
- def fix_quality(cls, quality):
58
- """This method gives the user the opportunity to pass a string instead of the quality object"""
59
- if isinstance(quality, Quality):
60
- return quality
61
-
62
- elif str(quality) == "best":
63
- return Quality.BEST
64
-
65
- elif str(quality) == "half":
66
- return Quality.HALF
67
-
68
- elif str(quality) == "worst":
69
- return Quality.WORST
70
-
71
- def get_available_qualities(self, m3u8_base_url, base_qualities, seperator):
72
- """Returns the available qualities from the M3U8 base url"""
73
- content = self.get_content(m3u8_base_url).decode("utf-8")
74
- lines = content.splitlines()
75
-
76
- quality_url_map = {}
77
-
78
- for line in lines:
79
- for quality in base_qualities:
80
- if f"{seperator}{quality}" in line and not str(line).startswith("#"):
81
- quality_url_map[quality] = line
82
-
83
- self.quality_url_map = quality_url_map
84
- self.available_qualities = list(quality_url_map.keys())
85
- return self.available_qualities
86
-
87
- def get_m3u8_by_quality(self, quality, m3u8_base_url, base_qualities, seperator):
88
- """Returns the m3u8 url for the given quality"""
89
- quality = self.fix_quality(quality)
90
-
91
- self.get_available_qualities(m3u8_base_url, base_qualities, seperator=seperator)
92
- if quality == Quality.BEST:
93
- selected_quality = max(self.available_qualities, key=lambda q: base_qualities.index(q))
94
- elif quality == Quality.WORST:
95
- selected_quality = min(self.available_qualities, key=lambda q: base_qualities.index(q))
96
- elif quality == Quality.HALF:
97
- sorted_qualities = sorted(self.available_qualities, key=lambda q: base_qualities.index(q))
98
- middle_index = len(sorted_qualities) // 2
99
- selected_quality = sorted_qualities[middle_index]
100
-
101
- return self.quality_url_map.get(selected_quality)
102
-
103
- def download(self, video, quality, downloader, path, callback=None):
104
- """
105
- :param callback:
106
- :param downloader:
107
- :param quality:
108
- :param path:
109
- :return:
110
- """
111
- quality = self.fix_quality(quality)
112
-
113
- if callback is None:
114
- callback = Callback.text_progress_bar
115
-
116
- if downloader == default or str(downloader) == "default":
117
- default(video=video, quality=quality, path=path, callback=callback)
118
-
119
- elif downloader == threaded or str(downloader) == "threaded":
120
- threaded_download = threaded(max_workers=20, timeout=10)
121
- threaded_download(video=video, quality=quality, path=path, callback=callback)
122
-
123
- elif downloader == FFMPEG or str(downloader) == "FFMPEG":
124
- FFMPEG(video=video, quality=quality, path=path, callback=callback)
125
-
126
- @classmethod
127
- def correct_path(cls, path):
128
- return Path(path)
129
-
130
- @classmethod
131
- def get_segments(cls, quality, m3u8_base_url, base_qualities, seperator, source=1):
132
- quality = Core().fix_quality(quality)
133
- base_url = m3u8_base_url
134
- new_segment = Core().get_m3u8_by_quality(quality, m3u8_base_url=base_url, base_qualities=base_qualities,
135
- seperator=seperator)
136
- # Split the base URL into components
137
- url_components = base_url.split('/')
138
-
139
- # Replace the last component with the new segment
140
- url_components[-1] = new_segment
141
-
142
- # Rejoin the components into the new full URL
143
- new_url = '/'.join(url_components)
144
-
145
- if source == "spankbang":
146
- new_url = new_url.split(".mp4.urlset/")[1] # Please just don't ask, I'm a terrible programmer fr
147
-
148
- master_src = Core().get_content(url=new_url).decode("utf-8")
149
-
150
- urls = [l for l in master_src.splitlines()
151
- if l and not l.startswith('#')]
152
-
153
- segments = []
154
-
155
- for url in urls:
156
- url_components[-1] = url
157
- new_url = '/'.join(url_components)
158
- segments.append(new_url)
159
-
160
- return segments
161
-
162
- @classmethod
163
- def strip_title(cls, title: str) -> str:
164
- """
165
- :param title:
166
- :return: str: strips out non UTF-8 chars of the title
167
- """
168
- illegal_chars = '<>:"/\\|?*'
169
- cleaned_title = ''.join([char for char in title if char in string.printable and char not in illegal_chars])
170
- return cleaned_title
171
-
172
- @classmethod
173
- def return_path(cls, video, args):
174
- path = args.output
175
- if args.use_title:
176
- if not str(path).endswith(os.sep):
177
- path += os.sep
178
-
179
- path += video.title + ".mp4"
180
-
181
- else:
182
- path = args.output
183
-
184
- 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.2
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