StreamingCommunity 1.7.6__py3-none-any.whl

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.

Potentially problematic release.


This version of StreamingCommunity might be problematic. Click here for more details.

Files changed (97) hide show
  1. StreamingCommunity/Src/Api/Player/Helper/Vixcloud/js_parser.py +140 -0
  2. StreamingCommunity/Src/Api/Player/Helper/Vixcloud/util.py +166 -0
  3. StreamingCommunity/Src/Api/Player/ddl.py +89 -0
  4. StreamingCommunity/Src/Api/Player/maxstream.py +151 -0
  5. StreamingCommunity/Src/Api/Player/supervideo.py +194 -0
  6. StreamingCommunity/Src/Api/Player/vixcloud.py +212 -0
  7. StreamingCommunity/Src/Api/Site/1337xx/__init__.py +50 -0
  8. StreamingCommunity/Src/Api/Site/1337xx/costant.py +15 -0
  9. StreamingCommunity/Src/Api/Site/1337xx/site.py +84 -0
  10. StreamingCommunity/Src/Api/Site/1337xx/title.py +66 -0
  11. StreamingCommunity/Src/Api/Site/altadefinizione/__init__.py +50 -0
  12. StreamingCommunity/Src/Api/Site/altadefinizione/costant.py +15 -0
  13. StreamingCommunity/Src/Api/Site/altadefinizione/film.py +69 -0
  14. StreamingCommunity/Src/Api/Site/altadefinizione/site.py +86 -0
  15. StreamingCommunity/Src/Api/Site/animeunity/__init__.py +50 -0
  16. StreamingCommunity/Src/Api/Site/animeunity/anime.py +126 -0
  17. StreamingCommunity/Src/Api/Site/animeunity/costant.py +15 -0
  18. StreamingCommunity/Src/Api/Site/animeunity/film_serie.py +131 -0
  19. StreamingCommunity/Src/Api/Site/animeunity/site.py +165 -0
  20. StreamingCommunity/Src/Api/Site/animeunity/util/ScrapeSerie.py +97 -0
  21. StreamingCommunity/Src/Api/Site/bitsearch/__init__.py +51 -0
  22. StreamingCommunity/Src/Api/Site/bitsearch/costant.py +15 -0
  23. StreamingCommunity/Src/Api/Site/bitsearch/site.py +84 -0
  24. StreamingCommunity/Src/Api/Site/bitsearch/title.py +47 -0
  25. StreamingCommunity/Src/Api/Site/cb01new/__init__.py +51 -0
  26. StreamingCommunity/Src/Api/Site/cb01new/costant.py +15 -0
  27. StreamingCommunity/Src/Api/Site/cb01new/film.py +69 -0
  28. StreamingCommunity/Src/Api/Site/cb01new/site.py +74 -0
  29. StreamingCommunity/Src/Api/Site/ddlstreamitaly/Player/ScrapeSerie.py +83 -0
  30. StreamingCommunity/Src/Api/Site/ddlstreamitaly/__init__.py +57 -0
  31. StreamingCommunity/Src/Api/Site/ddlstreamitaly/costant.py +16 -0
  32. StreamingCommunity/Src/Api/Site/ddlstreamitaly/series.py +142 -0
  33. StreamingCommunity/Src/Api/Site/ddlstreamitaly/site.py +93 -0
  34. StreamingCommunity/Src/Api/Site/ddlstreamitaly/util/ScrapeSerie.py +83 -0
  35. StreamingCommunity/Src/Api/Site/guardaserie/Player/ScrapeSerie.py +110 -0
  36. StreamingCommunity/Src/Api/Site/guardaserie/__init__.py +52 -0
  37. StreamingCommunity/Src/Api/Site/guardaserie/costant.py +15 -0
  38. StreamingCommunity/Src/Api/Site/guardaserie/series.py +195 -0
  39. StreamingCommunity/Src/Api/Site/guardaserie/site.py +84 -0
  40. StreamingCommunity/Src/Api/Site/guardaserie/util/ScrapeSerie.py +110 -0
  41. StreamingCommunity/Src/Api/Site/mostraguarda/__init__.py +48 -0
  42. StreamingCommunity/Src/Api/Site/mostraguarda/costant.py +15 -0
  43. StreamingCommunity/Src/Api/Site/mostraguarda/film.py +94 -0
  44. StreamingCommunity/Src/Api/Site/piratebays/__init__.py +50 -0
  45. StreamingCommunity/Src/Api/Site/piratebays/costant.py +15 -0
  46. StreamingCommunity/Src/Api/Site/piratebays/site.py +89 -0
  47. StreamingCommunity/Src/Api/Site/piratebays/title.py +45 -0
  48. StreamingCommunity/Src/Api/Site/streamingcommunity/__init__.py +55 -0
  49. StreamingCommunity/Src/Api/Site/streamingcommunity/costant.py +15 -0
  50. StreamingCommunity/Src/Api/Site/streamingcommunity/film.py +70 -0
  51. StreamingCommunity/Src/Api/Site/streamingcommunity/series.py +203 -0
  52. StreamingCommunity/Src/Api/Site/streamingcommunity/site.py +126 -0
  53. StreamingCommunity/Src/Api/Site/streamingcommunity/util/ScrapeSerie.py +113 -0
  54. StreamingCommunity/Src/Api/Template/Class/SearchType.py +101 -0
  55. StreamingCommunity/Src/Api/Template/Util/__init__.py +5 -0
  56. StreamingCommunity/Src/Api/Template/Util/get_domain.py +137 -0
  57. StreamingCommunity/Src/Api/Template/Util/manage_ep.py +153 -0
  58. StreamingCommunity/Src/Api/Template/Util/recall_search.py +37 -0
  59. StreamingCommunity/Src/Api/Template/__init__.py +3 -0
  60. StreamingCommunity/Src/Api/Template/site.py +87 -0
  61. StreamingCommunity/Src/Lib/Downloader/HLS/downloader.py +968 -0
  62. StreamingCommunity/Src/Lib/Downloader/HLS/proxyes.py +110 -0
  63. StreamingCommunity/Src/Lib/Downloader/HLS/segments.py +540 -0
  64. StreamingCommunity/Src/Lib/Downloader/MP4/downloader.py +156 -0
  65. StreamingCommunity/Src/Lib/Downloader/TOR/downloader.py +222 -0
  66. StreamingCommunity/Src/Lib/Downloader/__init__.py +5 -0
  67. StreamingCommunity/Src/Lib/Driver/driver_1.py +76 -0
  68. StreamingCommunity/Src/Lib/FFmpeg/__init__.py +4 -0
  69. StreamingCommunity/Src/Lib/FFmpeg/capture.py +170 -0
  70. StreamingCommunity/Src/Lib/FFmpeg/command.py +292 -0
  71. StreamingCommunity/Src/Lib/FFmpeg/util.py +242 -0
  72. StreamingCommunity/Src/Lib/M3U8/__init__.py +6 -0
  73. StreamingCommunity/Src/Lib/M3U8/decryptor.py +129 -0
  74. StreamingCommunity/Src/Lib/M3U8/estimator.py +173 -0
  75. StreamingCommunity/Src/Lib/M3U8/parser.py +666 -0
  76. StreamingCommunity/Src/Lib/M3U8/url_fixer.py +52 -0
  77. StreamingCommunity/Src/Lib/TMBD/__init__.py +2 -0
  78. StreamingCommunity/Src/Lib/TMBD/obj_tmbd.py +39 -0
  79. StreamingCommunity/Src/Lib/TMBD/tmdb.py +346 -0
  80. StreamingCommunity/Src/Upload/update.py +64 -0
  81. StreamingCommunity/Src/Upload/version.py +5 -0
  82. StreamingCommunity/Src/Util/_jsonConfig.py +204 -0
  83. StreamingCommunity/Src/Util/call_stack.py +42 -0
  84. StreamingCommunity/Src/Util/color.py +20 -0
  85. StreamingCommunity/Src/Util/console.py +12 -0
  86. StreamingCommunity/Src/Util/headers.py +147 -0
  87. StreamingCommunity/Src/Util/logger.py +53 -0
  88. StreamingCommunity/Src/Util/message.py +46 -0
  89. StreamingCommunity/Src/Util/os.py +417 -0
  90. StreamingCommunity/Src/Util/table.py +163 -0
  91. StreamingCommunity/run.py +196 -0
  92. StreamingCommunity-1.7.6.dist-info/LICENSE +674 -0
  93. StreamingCommunity-1.7.6.dist-info/METADATA +348 -0
  94. StreamingCommunity-1.7.6.dist-info/RECORD +97 -0
  95. StreamingCommunity-1.7.6.dist-info/WHEEL +5 -0
  96. StreamingCommunity-1.7.6.dist-info/entry_points.txt +2 -0
  97. StreamingCommunity-1.7.6.dist-info/top_level.txt +1 -0
@@ -0,0 +1,156 @@
1
+ # 09.06.24
2
+
3
+ import os
4
+ import sys
5
+ import ssl
6
+ import certifi
7
+ import logging
8
+
9
+
10
+ # External libraries
11
+ import httpx
12
+ from tqdm import tqdm
13
+
14
+
15
+ # Internal utilities
16
+ from StreamingCommunity.Src.Util.headers import get_headers
17
+ from StreamingCommunity.Src.Util.color import Colors
18
+ from StreamingCommunity.Src.Util.console import console, Panel
19
+ from StreamingCommunity.Src.Util._jsonConfig import config_manager
20
+ from StreamingCommunity.Src.Util.os import internet_manager
21
+
22
+
23
+ # Logic class
24
+ from ...FFmpeg import print_duration_table
25
+
26
+
27
+ # Suppress SSL warnings
28
+ import urllib3
29
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
30
+
31
+
32
+ # Config
33
+ GET_ONLY_LINK = config_manager.get_bool('M3U8_PARSER', 'get_only_link')
34
+ TQDM_USE_LARGE_BAR = config_manager.get_int('M3U8_DOWNLOAD', 'tqdm_use_large_bar')
35
+ REQUEST_VERIFY = config_manager.get_float('REQUESTS', 'verify_ssl')
36
+ REQUEST_TIMEOUT = config_manager.get_float('REQUESTS', 'timeout')
37
+
38
+
39
+
40
+ def MP4_downloader(url: str, path: str, referer: str = None, headers_: dict = None):
41
+ """
42
+ Downloads an MP4 video from a given URL with robust error handling and SSL bypass.
43
+
44
+ Parameters:
45
+ - url (str): The URL of the MP4 video to download.
46
+ - path (str): The local path where the downloaded MP4 file will be saved.
47
+ - referer (str, optional): The referer header value.
48
+ - headers_ (dict, optional): Custom headers for the request.
49
+ """
50
+ # Early return for link-only mode
51
+ if GET_ONLY_LINK:
52
+ return {'path': path, 'url': url}
53
+
54
+ # Validate URL
55
+ if not (url.lower().startswith('http://') or url.lower().startswith('https://')):
56
+ logging.error(f"Invalid URL: {url}")
57
+ console.print(f"[bold red]Invalid URL: {url}[/bold red]")
58
+ return None
59
+
60
+ # Prepare headers
61
+ try:
62
+ headers = {}
63
+ if referer:
64
+ headers['Referer'] = referer
65
+
66
+ # Use custom headers if provided, otherwise use default user agent
67
+ if headers_:
68
+ headers.update(headers_)
69
+ else:
70
+ headers['User-Agent'] = get_headers()
71
+
72
+ except Exception as header_err:
73
+ logging.error(f"Error preparing headers: {header_err}")
74
+ console.print(f"[bold red]Error preparing headers: {header_err}[/bold red]")
75
+ return None
76
+
77
+ try:
78
+ # Create a custom transport that bypasses SSL verification
79
+ transport = httpx.HTTPTransport(
80
+ verify=False, # Disable SSL certificate verification
81
+ http2=True # Optional: enable HTTP/2 support
82
+ )
83
+
84
+ # Download with streaming and progress tracking
85
+ with httpx.Client(transport=transport, timeout=httpx.Timeout(60.0)) as client:
86
+ with client.stream("GET", url, headers=headers, timeout=REQUEST_TIMEOUT) as response:
87
+ response.raise_for_status()
88
+
89
+ # Get total file size
90
+ total = int(response.headers.get('content-length', 0))
91
+
92
+ # Handle empty streams
93
+ if total == 0:
94
+ console.print("[bold red]No video stream found.[/bold red]")
95
+ return None
96
+
97
+ # Create progress bar
98
+ progress_bar = tqdm(
99
+ total=total,
100
+ ascii='░▒█',
101
+ bar_format=f"{Colors.YELLOW}[MP4] {Colors.WHITE}({Colors.CYAN}video{Colors.WHITE}): "
102
+ f"{Colors.RED}{{percentage:.2f}}% {Colors.MAGENTA}{{bar}} {Colors.WHITE}[ "
103
+ f"{Colors.YELLOW}{{n_fmt}}{Colors.WHITE} / {Colors.RED}{{total_fmt}} {Colors.WHITE}] "
104
+ f"{Colors.YELLOW}{{elapsed}} {Colors.WHITE}< {Colors.CYAN}{{remaining}} {Colors.WHITE}| "
105
+ f"{Colors.YELLOW}{{rate_fmt}}{{postfix}} {Colors.WHITE}]",
106
+ unit='iB',
107
+ unit_scale=True,
108
+ desc='Downloading',
109
+ mininterval=0.05
110
+ )
111
+
112
+ # Ensure directory exists
113
+ os.makedirs(os.path.dirname(path), exist_ok=True)
114
+
115
+ # Download file
116
+ with open(path, 'wb') as file, progress_bar as bar:
117
+ downloaded = 0
118
+ for chunk in response.iter_bytes(chunk_size=1024):
119
+ if chunk:
120
+ size = file.write(chunk)
121
+ downloaded += size
122
+ bar.update(size)
123
+
124
+ # Optional: Add a check to stop download if needed
125
+ # if downloaded > MAX_DOWNLOAD_SIZE:
126
+ # break
127
+
128
+ # Post-download processing
129
+ if os.path.exists(path) and os.path.getsize(path) > 0:
130
+ console.print(Panel(
131
+ f"[bold green]Download completed![/bold green]\n"
132
+ f"[cyan]File size: [bold red]{internet_manager.format_file_size(os.path.getsize(path))}[/bold red]\n"
133
+ f"[cyan]Duration: [bold]{print_duration_table(path, description=False, return_string=True)}[/bold]",
134
+ title=f"{os.path.basename(path.replace('.mp4', ''))}",
135
+ border_style="green"
136
+ ))
137
+ return path
138
+
139
+ else:
140
+ console.print("[bold red]Download failed or file is empty.[/bold red]")
141
+ return None
142
+
143
+ except httpx.HTTPStatusError as http_err:
144
+ logging.error(f"HTTP error occurred: {http_err}")
145
+ console.print(f"[bold red]HTTP Error: {http_err}[/bold red]")
146
+ return None
147
+
148
+ except httpx.RequestError as req_err:
149
+ logging.error(f"Request error: {req_err}")
150
+ console.print(f"[bold red]Request Error: {req_err}[/bold red]")
151
+ return None
152
+
153
+ except Exception as e:
154
+ logging.error(f"Unexpected error during download: {e}")
155
+ console.print(f"[bold red]Unexpected Error: {e}[/bold red]")
156
+ return None
@@ -0,0 +1,222 @@
1
+ # 23.06.24
2
+
3
+ import os
4
+ import sys
5
+ import time
6
+ import shutil
7
+ import logging
8
+
9
+
10
+ # Internal utilities
11
+ from StreamingCommunity.Src.Util.color import Colors
12
+ from StreamingCommunity.Src.Util.os import internet_manager
13
+ from StreamingCommunity.Src.Util._jsonConfig import config_manager
14
+
15
+
16
+ # External libraries
17
+ from tqdm import tqdm
18
+ from qbittorrent import Client
19
+
20
+
21
+ # Tor config
22
+ HOST = str(config_manager.get_dict('DEFAULT', 'config_qbit_tor')['host'])
23
+ PORT = str(config_manager.get_dict('DEFAULT', 'config_qbit_tor')['port'])
24
+ USERNAME = str(config_manager.get_dict('DEFAULT', 'config_qbit_tor')['user'])
25
+ PASSWORD = str(config_manager.get_dict('DEFAULT', 'config_qbit_tor')['pass'])
26
+
27
+ # Config
28
+ TQDM_USE_LARGE_BAR = config_manager.get_int('M3U8_DOWNLOAD', 'tqdm_use_large_bar')
29
+ REQUEST_VERIFY = config_manager.get_float('REQUESTS', 'verify_ssl')
30
+ REQUEST_TIMEOUT = config_manager.get_float('REQUESTS', 'timeout')
31
+
32
+
33
+
34
+ class TOR_downloader:
35
+ def __init__(self):
36
+ """
37
+ Initializes the TorrentManager instance.
38
+
39
+ Parameters:
40
+ - host (str): IP address or hostname of the qBittorrent Web UI.
41
+ - port (int): Port number of the qBittorrent Web UI.
42
+ - username (str): Username for logging into qBittorrent.
43
+ - password (str): Password for logging into qBittorrent.
44
+ """
45
+ try:
46
+ self.qb = Client(f'http://{HOST}:{PORT}/')
47
+ except:
48
+ logging.error("Start qbitorrent first.")
49
+
50
+ self.username = USERNAME
51
+ self.password = PASSWORD
52
+ self.logged_in = False
53
+ self.save_path = None
54
+ self.torrent_name = None
55
+
56
+ self.login()
57
+
58
+ def login(self):
59
+ """
60
+ Logs into the qBittorrent Web UI.
61
+ """
62
+ try:
63
+ self.qb.login(self.username, self.password)
64
+ self.logged_in = True
65
+ logging.info("Successfully logged in to qBittorrent.")
66
+
67
+ except Exception as e:
68
+ logging.error(f"Failed to log in: {str(e)}")
69
+ self.logged_in = False
70
+
71
+ def add_magnet_link(self, magnet_link):
72
+ """
73
+ Adds a torrent via magnet link to qBittorrent.
74
+
75
+ Parameters:
76
+ - magnet_link (str): Magnet link of the torrent to be added.
77
+ """
78
+ try:
79
+ self.qb.download_from_link(magnet_link)
80
+ logging.info("Added magnet link to qBittorrent.")
81
+
82
+ # Get the hash of the latest added torrent
83
+ torrents = self.qb.torrents()
84
+ if torrents:
85
+ self.latest_torrent_hash = torrents[-1]['hash']
86
+ logging.info(f"Latest torrent hash: {self.latest_torrent_hash}")
87
+
88
+ except Exception as e:
89
+ logging.error(f"Failed to add magnet link: {str(e)}")
90
+
91
+ def start_download(self):
92
+ """
93
+ Starts downloading the latest added torrent and monitors progress.
94
+ """
95
+ try:
96
+
97
+ torrents = self.qb.torrents()
98
+ if not torrents:
99
+ logging.error("No torrents found.")
100
+ return
101
+
102
+ # Sleep to load magnet to qbit app
103
+ time.sleep(10)
104
+ latest_torrent = torrents[-1]
105
+ torrent_hash = latest_torrent['hash']
106
+
107
+ # Custom bar for mobile and pc
108
+ if TQDM_USE_LARGE_BAR:
109
+ bar_format = (
110
+ f"{Colors.YELLOW}[TOR] {Colors.WHITE}({Colors.CYAN}video{Colors.WHITE}): "
111
+ f"{Colors.RED}{{percentage:.2f}}% {Colors.MAGENTA}{{bar}} {Colors.WHITE}[ "
112
+ f"{Colors.YELLOW}{{elapsed}} {Colors.WHITE}< {Colors.CYAN}{{remaining}}{{postfix}} {Colors.WHITE}]"
113
+ )
114
+ else:
115
+ bar_format = (
116
+ f"{Colors.YELLOW}Proc{Colors.WHITE}: "
117
+ f"{Colors.RED}{{percentage:.2f}}% {Colors.WHITE}| "
118
+ f"{Colors.CYAN}{{remaining}}{{postfix}} {Colors.WHITE}]"
119
+ )
120
+
121
+ progress_bar = tqdm(
122
+ total=100,
123
+ ascii='░▒█',
124
+ bar_format=bar_format,
125
+ unit_scale=True,
126
+ unit_divisor=1024,
127
+ mininterval=0.05
128
+ )
129
+
130
+ with progress_bar as pbar:
131
+ while True:
132
+
133
+ # Get variable from qtorrent
134
+ torrent_info = self.qb.get_torrent(torrent_hash)
135
+ self.save_path = torrent_info['save_path']
136
+ self.torrent_name = torrent_info['name']
137
+
138
+ # Fetch important variable
139
+ pieces_have = torrent_info['pieces_have']
140
+ pieces_num = torrent_info['pieces_num']
141
+ progress = (pieces_have / pieces_num) * 100 if pieces_num else 0
142
+ pbar.n = progress
143
+
144
+ download_speed = torrent_info['dl_speed']
145
+ total_size = torrent_info['total_size']
146
+ downloaded_size = torrent_info['total_downloaded']
147
+
148
+ # Format variable
149
+ downloaded_size_str = internet_manager.format_file_size(downloaded_size)
150
+ downloaded_size = downloaded_size_str.split(' ')[0]
151
+
152
+ total_size_str = internet_manager.format_file_size(total_size)
153
+ total_size = total_size_str.split(' ')[0]
154
+ total_size_unit = total_size_str.split(' ')[1]
155
+
156
+ average_internet_str = internet_manager.format_transfer_speed(download_speed)
157
+ average_internet = average_internet_str.split(' ')[0]
158
+ average_internet_unit = average_internet_str.split(' ')[1]
159
+
160
+ # Update the progress bar's postfix
161
+ if TQDM_USE_LARGE_BAR:
162
+ pbar.set_postfix_str(
163
+ f"{Colors.WHITE}[ {Colors.GREEN}{downloaded_size} {Colors.WHITE}< {Colors.GREEN}{total_size} {Colors.RED}{total_size_unit} "
164
+ f"{Colors.WHITE}| {Colors.CYAN}{average_internet} {Colors.RED}{average_internet_unit}"
165
+ )
166
+ else:
167
+ pbar.set_postfix_str(
168
+ f"{Colors.WHITE}[ {Colors.GREEN}{downloaded_size}{Colors.RED} {total_size} "
169
+ f"{Colors.WHITE}| {Colors.CYAN}{average_internet} {Colors.RED}{average_internet_unit}"
170
+ )
171
+
172
+ pbar.refresh()
173
+ time.sleep(0.2)
174
+
175
+ # Break at the end
176
+ if int(progress) == 100:
177
+ break
178
+
179
+ except KeyboardInterrupt:
180
+ logging.info("Download process interrupted.")
181
+
182
+ except Exception as e:
183
+ logging.error(f"Download error: {str(e)}")
184
+ sys.exit(0)
185
+
186
+ def move_downloaded_files(self, destination=None):
187
+ """
188
+ Moves downloaded files of the latest torrent to another location.
189
+
190
+ Parameters:
191
+ - save_path (str): Current save path (output directory) of the torrent.
192
+ - destination (str, optional): Destination directory to move files. If None, moves to current directory.
193
+
194
+ Returns:
195
+ - bool: True if files are moved successfully, False otherwise.
196
+ """
197
+
198
+ video_extensions = {'.mp4', '.mkv', 'avi'}
199
+ time.sleep(2)
200
+
201
+ # List directories in the save path
202
+ dirs = [d for d in os.listdir(self.save_path) if os.path.isdir(os.path.join(self.save_path, d))]
203
+
204
+ for dir_name in dirs:
205
+ if self.torrent_name.split(" ")[0] in dir_name:
206
+ dir_path = os.path.join(self.save_path, dir_name)
207
+
208
+ # Ensure destination is set; if not, use current directory
209
+ destination = destination or os.getcwd()
210
+
211
+ # Move only video files
212
+ for file_name in os.listdir(dir_path):
213
+ file_path = os.path.join(dir_path, file_name)
214
+
215
+ # Check if it's a file and if it has a video extension
216
+ if os.path.isfile(file_path) and os.path.splitext(file_name)[1] in video_extensions:
217
+ shutil.move(file_path, os.path.join(destination, file_name))
218
+ logging.info(f"Moved file {file_name} to {destination}")
219
+
220
+ time.sleep(2)
221
+ self.qb.delete_permanently(self.qb.torrents()[-1]['hash'])
222
+ return True
@@ -0,0 +1,5 @@
1
+ # 23.06.24
2
+
3
+ from .HLS.downloader import HLS_Downloader
4
+ from .MP4.downloader import MP4_downloader
5
+ from .TOR.downloader import TOR_downloader
@@ -0,0 +1,76 @@
1
+ # 29.06.24
2
+
3
+ import tempfile
4
+ import logging
5
+
6
+
7
+ # External library
8
+ from bs4 import BeautifulSoup
9
+ from seleniumbase import Driver
10
+
11
+
12
+ # Internal utilities
13
+ from StreamingCommunity.Src.Util._jsonConfig import config_manager
14
+
15
+
16
+ # Config
17
+ USE_HEADLESS = config_manager.get_bool("BROWSER", "headless")
18
+
19
+
20
+ class WebAutomation:
21
+ """
22
+ A class for automating web interactions using SeleniumBase and BeautifulSoup.
23
+ """
24
+
25
+ def __init__(self):
26
+ """
27
+ Initializes the WebAutomation instance with SeleniumBase Driver.
28
+
29
+ Parameters:
30
+ headless (bool, optional): Whether to run the browser in headless mode. Default is True.
31
+ """
32
+ logging.getLogger('seleniumbase').setLevel(logging.ERROR)
33
+
34
+ self.driver = Driver(
35
+ uc=True,
36
+ uc_cdp_events=True,
37
+ headless=USE_HEADLESS,
38
+ user_data_dir = tempfile.mkdtemp(),
39
+ chromium_arg="--disable-search-engine-choice-screen"
40
+ )
41
+
42
+ def quit(self):
43
+ """
44
+ Quits the WebDriver instance.
45
+ """
46
+ self.driver.quit()
47
+
48
+ def get_page(self, url):
49
+ """
50
+ Navigates the browser to the specified URL.
51
+
52
+ Parameters:
53
+ url (str): The URL to navigate to.
54
+ """
55
+ self.driver.get(url)
56
+
57
+ def retrieve_soup(self):
58
+ """
59
+ Retrieves the BeautifulSoup object for the current page's HTML content.
60
+
61
+ Returns:
62
+ BeautifulSoup object: Parsed HTML content of the current page.
63
+ """
64
+ html_content = self.driver.page_source
65
+ soup = BeautifulSoup(html_content, 'html.parser')
66
+ return soup
67
+
68
+ def get_content(self):
69
+ """
70
+ Returns the HTML content of the current page.
71
+
72
+ Returns:
73
+ str: The HTML content of the current page.
74
+ """
75
+ return self.driver.page_source
76
+
@@ -0,0 +1,4 @@
1
+ # 18.04.24
2
+
3
+ from .command import join_video, join_audios, join_subtitle
4
+ from .util import print_duration_table, get_video_duration_s
@@ -0,0 +1,170 @@
1
+ # 16.04.24
2
+
3
+ import re
4
+ import logging
5
+ import threading
6
+ import subprocess
7
+
8
+
9
+ # Internal utilities
10
+ from StreamingCommunity.Src.Util.console import console
11
+ from StreamingCommunity.Src.Util.os import internet_manager
12
+
13
+
14
+ # Variable
15
+ terminate_flag = threading.Event()
16
+
17
+
18
+ def capture_output(process: subprocess.Popen, description: str) -> None:
19
+ """
20
+ Function to capture and print output from a subprocess.
21
+
22
+ Parameters:
23
+ - process (subprocess.Popen): The subprocess whose output is captured.
24
+ - description (str): Description of the command being executed.
25
+ """
26
+ try:
27
+
28
+ # Variable to store the length of the longest progress string
29
+ max_length = 0
30
+
31
+ for line in iter(process.stdout.readline, ''):
32
+ try:
33
+ line = line.strip()
34
+ if not line:
35
+ continue
36
+
37
+ logging.info(f"FFMPEG line: {line}")
38
+
39
+ # Capture only error
40
+ if "rror" in str(line):
41
+ console.log(f"[red]FFMPEG: {str(line).strip()}")
42
+
43
+ # Check if termination is requested
44
+ if terminate_flag.is_set():
45
+ break
46
+
47
+ if "size=" in line:
48
+ try:
49
+
50
+ # Parse the output line to extract relevant information
51
+ data = parse_output_line(line)
52
+
53
+ if 'q' in data:
54
+ is_end = (float(data.get('q', -1.0)) == -1.0)
55
+ size_key = 'Lsize' if is_end else 'size'
56
+ byte_size = int(re.findall(r'\d+', data.get(size_key, '0'))[0]) * 1000
57
+ else:
58
+ byte_size = int(re.findall(r'\d+', data.get('size', '0'))[0]) * 1000
59
+
60
+
61
+ # Construct the progress string with formatted output information
62
+ progress_string = (f"[yellow][FFmpeg] [white][{description}[white]]: "
63
+ f"([green]'speed': [yellow]{data.get('speed', 'N/A')}[white], "
64
+ f"[green]'size': [yellow]{internet_manager.format_file_size(byte_size)}[white])")
65
+ max_length = max(max_length, len(progress_string))
66
+
67
+ # Print the progress string to the console, overwriting the previous line
68
+ console.print(progress_string.ljust(max_length), end="\r")
69
+
70
+ except Exception as e:
71
+ logging.error(f"Error parsing output line: {line} - {e}")
72
+
73
+ except Exception as e:
74
+ logging.error(f"Error processing line from subprocess: {e}")
75
+
76
+ except Exception as e:
77
+ logging.error(f"Error in capture_output: {e}")
78
+
79
+ finally:
80
+ try:
81
+ terminate_process(process)
82
+ except Exception as e:
83
+ logging.error(f"Error terminating process: {e}")
84
+
85
+
86
+ def parse_output_line(line: str) -> dict:
87
+ """
88
+ Function to parse the output line and extract relevant information.
89
+
90
+ Parameters:
91
+ - line (str): The output line to parse.
92
+
93
+ Returns:
94
+ dict: A dictionary containing parsed information.
95
+ """
96
+ try:
97
+
98
+ data = {}
99
+
100
+ # Split the line by whitespace and extract key-value pairs
101
+ parts = line.replace(" ", "").replace("= ", "=").split()
102
+
103
+ for part in parts:
104
+ key_value = part.split('=')
105
+
106
+ if len(key_value) == 2:
107
+ key = key_value[0]
108
+ value = key_value[1]
109
+ data[key] = value
110
+
111
+ return data
112
+
113
+ except Exception as e:
114
+ logging.error(f"Error parsing line: {line} - {e}")
115
+ return {}
116
+
117
+
118
+ def terminate_process(process):
119
+ """
120
+ Function to terminate a subprocess if it's still running.
121
+
122
+ Parameters:
123
+ - process (subprocess.Popen): The subprocess to terminate.
124
+ """
125
+ try:
126
+ if process.poll() is None: # Check if the process is still running
127
+ process.kill()
128
+ except Exception as e:
129
+ logging.error(f"Failed to terminate process: {e}")
130
+
131
+
132
+ def capture_ffmpeg_real_time(ffmpeg_command: list, description: str) -> None:
133
+ """
134
+ Function to capture real-time output from ffmpeg process.
135
+
136
+ Parameters:
137
+ - ffmpeg_command (list): The command to execute ffmpeg.
138
+ - description (str): Description of the command being executed.
139
+ """
140
+
141
+ global terminate_flag
142
+
143
+ # Clear the terminate_flag before starting a new capture
144
+ terminate_flag.clear()
145
+
146
+ try:
147
+
148
+ # Start the ffmpeg process with subprocess.Popen
149
+ process = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
150
+
151
+ # Start a thread to capture and print output
152
+ output_thread = threading.Thread(target=capture_output, args=(process, description))
153
+ output_thread.start()
154
+
155
+ try:
156
+ # Wait for ffmpeg process to complete
157
+ process.wait()
158
+
159
+ except KeyboardInterrupt:
160
+ logging.error("Terminating ffmpeg process...")
161
+
162
+ except Exception as e:
163
+ logging.error(f"Error in ffmpeg process: {e}")
164
+
165
+ finally:
166
+ terminate_flag.set() # Signal the output capture thread to terminate
167
+ output_thread.join() # Wait for the output capture thread to complete
168
+
169
+ except Exception as e:
170
+ logging.error(f"Failed to start ffmpeg process: {e}")