StreamingCommunity 3.3.0__py3-none-any.whl → 3.3.2__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 (40) hide show
  1. StreamingCommunity/Api/Site/altadefinizione/__init__.py +37 -17
  2. StreamingCommunity/Api/Site/animeunity/__init__.py +36 -16
  3. StreamingCommunity/Api/Site/animeworld/__init__.py +50 -6
  4. StreamingCommunity/Api/Site/crunchyroll/__init__.py +42 -16
  5. StreamingCommunity/Api/Site/crunchyroll/site.py +1 -1
  6. StreamingCommunity/Api/Site/guardaserie/__init__.py +50 -6
  7. StreamingCommunity/Api/Site/mediasetinfinity/__init__.py +43 -5
  8. StreamingCommunity/Api/Site/mediasetinfinity/film.py +1 -1
  9. StreamingCommunity/Api/Site/mediasetinfinity/site.py +6 -3
  10. StreamingCommunity/Api/Site/mediasetinfinity/util/ScrapeSerie.py +6 -7
  11. StreamingCommunity/Api/Site/mediasetinfinity/util/get_license.py +189 -0
  12. StreamingCommunity/Api/Site/raiplay/__init__.py +45 -14
  13. StreamingCommunity/Api/Site/raiplay/series.py +9 -5
  14. StreamingCommunity/Api/Site/raiplay/site.py +6 -4
  15. StreamingCommunity/Api/Site/raiplay/util/ScrapeSerie.py +6 -2
  16. StreamingCommunity/Api/Site/streamingcommunity/__init__.py +7 -2
  17. StreamingCommunity/Api/Site/streamingcommunity/site.py +0 -3
  18. StreamingCommunity/Api/Site/streamingwatch/__init__.py +44 -14
  19. StreamingCommunity/Api/Site/streamingwatch/site.py +0 -3
  20. StreamingCommunity/Lib/Downloader/DASH/cdm_helpher.py +1 -18
  21. StreamingCommunity/Lib/Downloader/DASH/downloader.py +88 -52
  22. StreamingCommunity/Lib/Downloader/HLS/downloader.py +38 -14
  23. StreamingCommunity/Lib/Downloader/HLS/segments.py +1 -1
  24. StreamingCommunity/Lib/FFmpeg/command.py +66 -7
  25. StreamingCommunity/Lib/FFmpeg/util.py +16 -13
  26. StreamingCommunity/Lib/M3U8/decryptor.py +0 -14
  27. StreamingCommunity/Lib/TMBD/tmdb.py +0 -12
  28. StreamingCommunity/Upload/version.py +1 -1
  29. StreamingCommunity/Util/{bento4_installer.py → installer/bento4_install.py} +15 -33
  30. StreamingCommunity/Util/installer/binary_paths.py +83 -0
  31. StreamingCommunity/Util/{ffmpeg_installer.py → installer/ffmpeg_install.py} +11 -54
  32. StreamingCommunity/Util/logger.py +3 -8
  33. StreamingCommunity/Util/os.py +67 -68
  34. StreamingCommunity/run.py +1 -1
  35. {streamingcommunity-3.3.0.dist-info → streamingcommunity-3.3.2.dist-info}/METADATA +313 -498
  36. {streamingcommunity-3.3.0.dist-info → streamingcommunity-3.3.2.dist-info}/RECORD +40 -39
  37. {streamingcommunity-3.3.0.dist-info → streamingcommunity-3.3.2.dist-info}/WHEEL +0 -0
  38. {streamingcommunity-3.3.0.dist-info → streamingcommunity-3.3.2.dist-info}/entry_points.txt +0 -0
  39. {streamingcommunity-3.3.0.dist-info → streamingcommunity-3.3.2.dist-info}/licenses/LICENSE +0 -0
  40. {streamingcommunity-3.3.0.dist-info → streamingcommunity-3.3.2.dist-info}/top_level.txt +0 -0
@@ -86,9 +86,6 @@ def title_search(query: str) -> int:
86
86
  soup = BeautifulSoup(response.text, 'html.parser')
87
87
 
88
88
  except Exception as e:
89
- if "WinError" in str(e) or "Errno" in str(e):
90
- console.print("\n[bold yellow]Please make sure you have enabled and configured a valid proxy.[/bold yellow]")
91
-
92
89
  console.print(f"[red]Site: {site_constant.SITE_NAME}, request search error: {e}")
93
90
  return 0
94
91
 
@@ -29,29 +29,11 @@ def get_widevine_keys(pssh, license_url, cdm_device_path, headers=None, payload=
29
29
  Returns:
30
30
  list: List of dicts {'kid': ..., 'key': ...} (only CONTENT keys) or None if error.
31
31
  """
32
-
33
- # Check if PSSH is a valid base64 string
34
- try:
35
- base64.b64decode(pssh)
36
- except Exception:
37
- console.print("[bold red] Invalid PSSH base64 string.[/bold red]")
38
- return None
39
-
40
32
  try:
41
33
  device = Device.load(cdm_device_path)
42
34
  cdm = Cdm.from_device(device)
43
35
  session_id = cdm.open()
44
36
 
45
- # Display security level in a more readable format
46
- security_levels = {1: "L1 (Hardware)", 2: "L2 (Software)", 3: "L3 (Software)"}
47
- security_level_str = security_levels.get(device.security_level, 'Unknown')
48
- logging.info(f"Security Level: {security_level_str}")
49
-
50
- # Only allow L3, otherwise warn and exit
51
- if device.security_level != 3:
52
- console.print(f"[bold yellow]⚠️ Only L3 (Software) security level is supported. Current: {security_level_str}[/bold yellow]")
53
- return None
54
-
55
37
  try:
56
38
  challenge = cdm.get_license_challenge(session_id, PSSH(pssh))
57
39
  req_headers = headers or {}
@@ -108,6 +90,7 @@ def get_widevine_keys(pssh, license_url, cdm_device_path, headers=None, payload=
108
90
  content_keys = []
109
91
  for key in cdm.get_keys(session_id):
110
92
  if key.type == "CONTENT":
93
+
111
94
  kid = key.kid.hex() if isinstance(key.kid, bytes) else str(key.kid)
112
95
  key_val = key.key.hex() if isinstance(key.key, bytes) else str(key.key)
113
96
 
@@ -6,11 +6,13 @@ import shutil
6
6
 
7
7
  # External libraries
8
8
  from rich.console import Console
9
+ from rich.panel import Panel
9
10
 
10
11
 
11
12
  # Internal utilities
12
13
  from StreamingCommunity.Util.config_json import config_manager
13
- from StreamingCommunity.Lib.FFmpeg.command import join_audios, join_video
14
+ from StreamingCommunity.Util.os import internet_manager
15
+ from ...FFmpeg import print_duration_table, join_audios, join_video
14
16
 
15
17
 
16
18
  # Logic class
@@ -20,6 +22,7 @@ from .decrypt import decrypt_with_mp4decrypt
20
22
  from .cdm_helpher import get_widevine_keys
21
23
 
22
24
 
25
+
23
26
  # Config
24
27
  DOWNLOAD_SPECIFIC_AUDIO = config_manager.get_list('M3U8_DOWNLOAD', 'specific_list_audio')
25
28
  FILTER_CUSTOM_REOLUTION = str(config_manager.get('M3U8_CONVERSION', 'force_resolution')).strip().lower()
@@ -35,8 +38,8 @@ class DASH_Downloader:
35
38
  self.cdm_device = cdm_device
36
39
  self.license_url = license_url
37
40
  self.mpd_url = mpd_url
38
- self.original_output_path = os.path.abspath(str(output_path))
39
- self.out_path = os.path.splitext(self.original_output_path)[0]
41
+ self.out_path = os.path.splitext(os.path.abspath(str(output_path)))[0]
42
+ self.original_output_path = output_path
40
43
  self.parser = None
41
44
  self._setup_temp_dirs()
42
45
 
@@ -94,12 +97,35 @@ class DASH_Downloader:
94
97
  self.error = None
95
98
  self.stopped = False
96
99
 
100
+ # Fetch keys immediately after obtaining PSSH
101
+ if not self.parser.pssh:
102
+ console.print("[red]No PSSH found: segments are not encrypted, skipping decryption.")
103
+ self.download_segments(clear=True)
104
+ return True
105
+
106
+ keys = get_widevine_keys(
107
+ pssh=self.parser.pssh,
108
+ license_url=self.license_url,
109
+ cdm_device_path=self.cdm_device,
110
+ headers=custom_headers,
111
+ payload=custom_payload
112
+ )
113
+
114
+ if not keys:
115
+ console.print("[red]No keys found, cannot proceed with download.[/red]")
116
+ return False
117
+
118
+ # Extract the first key for decryption
119
+ key = keys[0]
120
+ KID = key['kid']
121
+ KEY = key['key']
122
+
97
123
  for typ in ["video", "audio"]:
98
124
  rep = self.get_representation_by_type(typ)
99
125
  if rep:
100
126
  encrypted_path = os.path.join(self.encrypted_dir, f"{rep['id']}_encrypted.m4s")
101
127
 
102
- # If m4s file doesn't exist start downloading
128
+ # If m4s file doesn't exist, start downloading
103
129
  if not os.path.exists(encrypted_path):
104
130
  downloader = MPD_Segments(
105
131
  tmp_folder=self.encrypted_dir,
@@ -124,28 +150,6 @@ class DASH_Downloader:
124
150
  self.error = str(ex)
125
151
  return False
126
152
 
127
- if not self.parser.pssh:
128
- print("No PSSH found: segments are not encrypted, skipping decryption.")
129
- self.download_segments(clear=True)
130
- return True
131
-
132
- keys = get_widevine_keys(
133
- pssh=self.parser.pssh,
134
- license_url=self.license_url,
135
- cdm_device_path=self.cdm_device,
136
- headers=custom_headers,
137
- payload=custom_payload
138
- )
139
-
140
- if not keys:
141
- self.error = f"No key found, cannot decrypt {typ}"
142
- print(self.error)
143
- return False
144
-
145
- key = keys[0]
146
- KID = key['kid']
147
- KEY = key['key']
148
-
149
153
  decrypted_path = os.path.join(self.decrypted_dir, f"{typ}.mp4")
150
154
  result_path = decrypt_with_mp4decrypt(
151
155
  encrypted_path, KID, KEY, output_path=decrypted_path
@@ -169,46 +173,78 @@ class DASH_Downloader:
169
173
  pass
170
174
 
171
175
  def finalize_output(self):
176
+
177
+ # Definenition of decrypted files
172
178
  video_file = os.path.join(self.decrypted_dir, "video.mp4")
173
179
  audio_file = os.path.join(self.decrypted_dir, "audio.mp4")
174
-
175
- # fallback: if one of the two is missing, look in encrypted
176
- if not os.path.exists(video_file):
177
- for f in os.listdir(self.encrypted_dir):
178
- if f.endswith("_encrypted.m4s") and ("video" in f or f.startswith("1_")):
179
- video_file = os.path.join(self.encrypted_dir, f)
180
- break
181
- if not os.path.exists(audio_file):
182
- for f in os.listdir(self.encrypted_dir):
183
- if f.endswith("_encrypted.m4s") and ("audio" in f or f.startswith("0_")):
184
- audio_file = os.path.join(self.encrypted_dir, f)
185
- break
186
-
187
- # Usa il nome file originale per il file finale
188
180
  output_file = self.original_output_path
181
+
182
+ # Set the output file path for status tracking
183
+ self.output_file = output_file
184
+ use_shortest = False
189
185
 
190
186
  if os.path.exists(video_file) and os.path.exists(audio_file):
191
187
  audio_tracks = [{"path": audio_file}]
192
- join_audios(video_file, audio_tracks, output_file)
188
+ _, use_shortest = join_audios(video_file, audio_tracks, output_file)
189
+
193
190
  elif os.path.exists(video_file):
194
- join_video(video_file, output_file, codec=None)
191
+ _ = join_video(video_file, output_file, codec=None)
192
+
193
+ else:
194
+ console.print("[red]Video file missing, cannot export[/red]")
195
+ return None
196
+
197
+ # Handle failed sync case
198
+ if use_shortest:
199
+ new_filename = output_file.replace(".mp4", "_failed_sync.mp4")
200
+ os.rename(output_file, new_filename)
201
+ output_file = new_filename
202
+ self.output_file = new_filename
203
+
204
+ # Display file information
205
+ if os.path.exists(output_file):
206
+ file_size = internet_manager.format_file_size(os.path.getsize(output_file))
207
+ duration = print_duration_table(output_file, description=False, return_string=True)
208
+
209
+ panel_content = (
210
+ f"[cyan]File size: [bold red]{file_size}[/bold red]\n"
211
+ f"[cyan]Duration: [bold]{duration}[/bold]\n"
212
+ f"[cyan]Output: [bold]{os.path.abspath(output_file)}[/bold]"
213
+ )
214
+
215
+ console.print(Panel(
216
+ panel_content,
217
+ title=f"{os.path.basename(output_file.replace('.mp4', ''))}",
218
+ border_style="green"
219
+ ))
220
+
195
221
  else:
196
- print("Video file missing, cannot export")
222
+ console.print(f"[red]Output file not found: {output_file}")
197
223
 
198
- # Clean up: delete all tmp
224
+ # Clean up: delete only the tmp directory, not the main directory
199
225
  if os.path.exists(self.tmp_dir):
200
226
  shutil.rmtree(self.tmp_dir, ignore_errors=True)
201
227
 
202
- # Rimuovi la cartella principale se è vuota
203
- try:
204
- if os.path.exists(self.out_path) and not os.listdir(self.out_path):
205
- os.rmdir(self.out_path)
206
- except Exception as e:
207
- print(f"[WARN] Impossibile eliminare la cartella {self.out_path}: {e}")
228
+ # Only remove the temp base directory if it was created specifically for this download
229
+ # and if the final output is NOT inside this directory
230
+ output_dir = os.path.dirname(self.original_output_path)
208
231
 
232
+ # Check if out_path is different from the actual output directory
233
+ # and if it's empty, then it's safe to remove
234
+ if (self.out_path != output_dir and os.path.exists(self.out_path) and not os.listdir(self.out_path)):
235
+ try:
236
+ os.rmdir(self.out_path)
209
237
 
210
- return self.output_file
238
+ except Exception as e:
239
+ console.print(f"[red]Cannot remove directory {self.out_path}: {e}")
211
240
 
241
+ # Verify the final file exists before returning
242
+ if os.path.exists(output_file):
243
+ return output_file
244
+ else:
245
+ self.error = "Final output file was not created successfully"
246
+ return None
247
+
212
248
  def get_status(self):
213
249
  """
214
250
  Returns a dict with 'path', 'error', and 'stopped' for external use.
@@ -217,4 +253,4 @@ class DASH_Downloader:
217
253
  "path": self.output_file,
218
254
  "error": self.error,
219
255
  "stopped": self.stopped
220
- }
256
+ }
@@ -39,6 +39,7 @@ DOWNLOAD_SPECIFIC_AUDIO = config_manager.get_list('M3U8_DOWNLOAD', 'specific_lis
39
39
  DOWNLOAD_SPECIFIC_SUBTITLE = config_manager.get_list('M3U8_DOWNLOAD', 'specific_list_subtitles')
40
40
  MERGE_SUBTITLE = config_manager.get_bool('M3U8_DOWNLOAD', 'merge_subs')
41
41
  CLEANUP_TMP = config_manager.get_bool('M3U8_DOWNLOAD', 'cleanup_tmp_folder')
42
+ GET_ONLY_LINK = config_manager.get_int('M3U8_DOWNLOAD', 'get_only_link')
42
43
  FILTER_CUSTOM_RESOLUTION = str(config_manager.get('M3U8_CONVERSION', 'force_resolution')).strip().lower()
43
44
  RETRY_LIMIT = config_manager.get_int('REQUESTS', 'max_retry')
44
45
  MAX_TIMEOUT = config_manager.get_int("REQUESTS", "timeout")
@@ -63,7 +64,6 @@ class HLSClient:
63
64
  Returns:
64
65
  Response content/text or None if all retries fail
65
66
  """
66
- # Use unified HTTP client (inherits timeout/verify/proxy from config)
67
67
  client = create_client(headers=self.headers)
68
68
 
69
69
  for attempt in range(RETRY_LIMIT):
@@ -211,10 +211,10 @@ class M3U8Manager:
211
211
  # Get available subtitles and their languages
212
212
  available_subtitles = self.parser._subtitle.get_all_uris_and_names() or []
213
213
  available_sub_languages = [sub.get('language') for sub in available_subtitles]
214
-
214
+
215
215
  # If "*" is in DOWNLOAD_SPECIFIC_SUBTITLE, all languages are downloadable
216
216
  downloadable_sub_languages = available_sub_languages if "*" in DOWNLOAD_SPECIFIC_SUBTITLE else list(set(available_sub_languages) & set(DOWNLOAD_SPECIFIC_SUBTITLE))
217
-
217
+
218
218
  if available_sub_languages:
219
219
  console.print(
220
220
  f"[cyan bold]Subtitle [/cyan bold] [green]Available:[/green] [purple]{', '.join(available_sub_languages)}[/purple] | "
@@ -260,7 +260,7 @@ class DownloadManager:
260
260
 
261
261
  if result.get('stopped', False):
262
262
  self.stopped = True
263
-
263
+
264
264
  return self.stopped
265
265
 
266
266
  def download_audio(self, audio: Dict):
@@ -304,7 +304,7 @@ class DownloadManager:
304
304
  """
305
305
  return_stopped = False
306
306
  video_file = os.path.join(self.temp_dir, 'video', '0.ts')
307
-
307
+
308
308
  if not os.path.exists(video_file):
309
309
  if self.download_video(video_url):
310
310
  if not return_stopped:
@@ -360,6 +360,7 @@ class MergeManager:
360
360
  """
361
361
  video_file = os.path.join(self.temp_dir, 'video', '0.ts')
362
362
  merged_file = video_file
363
+ use_shortest = False
363
364
 
364
365
  if not self.audio_streams and not self.sub_streams:
365
366
  merged_file = join_video(
@@ -376,7 +377,7 @@ class MergeManager:
376
377
  } for a in self.audio_streams]
377
378
 
378
379
  merged_audio_path = os.path.join(self.temp_dir, 'merged_audio.mp4')
379
- merged_file = join_audios(
380
+ merged_file, use_shortest = join_audios(
380
381
  video_path=video_file,
381
382
  audio_tracks=audio_tracks,
382
383
  out_path=merged_audio_path,
@@ -396,7 +397,7 @@ class MergeManager:
396
397
  out_path=merged_subs_path
397
398
  )
398
399
 
399
- return merged_file
400
+ return merged_file, use_shortest
400
401
 
401
402
 
402
403
  class HLS_Downloader:
@@ -420,8 +421,20 @@ class HLS_Downloader:
420
421
  - is_master: Whether the M3U8 was a master playlist
421
422
  Or raises an exception if there's an error
422
423
  """
424
+
425
+ if GET_ONLY_LINK:
426
+ console.print(f"URL: [bold red]{self.m3u8_url}[/bold red]")
427
+ return {
428
+ 'path': None,
429
+ 'url': self.m3u8_url,
430
+ 'is_master': getattr(self.m3u8_manager, 'is_master', None),
431
+ 'msg': None,
432
+ 'error': None,
433
+ 'stopped': True
434
+ }
435
+
423
436
  console.print("[cyan]You can safely stop the download with [bold]Ctrl+c[bold] [cyan] \n")
424
-
437
+
425
438
  if TELEGRAM_BOT:
426
439
  bot = get_bot_instance()
427
440
 
@@ -439,7 +452,7 @@ class HLS_Downloader:
439
452
  if TELEGRAM_BOT:
440
453
  bot.send_message("Contenuto già scaricato!", None)
441
454
  return response
442
-
455
+
443
456
  self.path_manager.setup_directories()
444
457
 
445
458
  # Parse M3U8 and determine if it's a master playlist
@@ -467,9 +480,9 @@ class HLS_Downloader:
467
480
  sub_streams=self.m3u8_manager.sub_streams
468
481
  )
469
482
 
470
- final_file = self.merge_manager.merge()
483
+ final_file, use_shortest = self.merge_manager.merge()
471
484
  self.path_manager.move_final_file(final_file)
472
- self._print_summary()
485
+ self._print_summary(use_shortest)
473
486
  self.path_manager.cleanup()
474
487
 
475
488
  return {
@@ -495,7 +508,7 @@ class HLS_Downloader:
495
508
  'stopped': False
496
509
  }
497
510
 
498
- def _print_summary(self):
511
+ def _print_summary(self, use_shortest):
499
512
  """Prints download summary including file size, duration, and any missing segments."""
500
513
  if TELEGRAM_BOT:
501
514
  bot = get_bot_instance()
@@ -523,10 +536,21 @@ class HLS_Downloader:
523
536
 
524
537
  if missing_ts:
525
538
  panel_content += f"\n{missing_info}"
526
- os.rename(self.path_manager.output_path, self.path_manager.output_path.replace(".mp4", "_failed.mp4"))
539
+
540
+ new_filename = self.path_manager.output_path
541
+ if missing_ts and use_shortest:
542
+ new_filename = new_filename.replace(".mp4", "_failed_sync_ts.mp4")
543
+ elif missing_ts:
544
+ new_filename = new_filename.replace(".mp4", "_failed_ts.mp4")
545
+ elif use_shortest:
546
+ new_filename = new_filename.replace(".mp4", "_failed_sync.mp4")
547
+
548
+ if missing_ts or use_shortest:
549
+ os.rename(self.path_manager.output_path, new_filename)
550
+ self.path_manager.output_path = new_filename
527
551
 
528
552
  console.print(Panel(
529
553
  panel_content,
530
554
  title=f"{os.path.basename(self.path_manager.output_path.replace('.mp4', ''))}",
531
555
  border_style="green"
532
- ))
556
+ ))
@@ -249,7 +249,7 @@ class M3U8_Segments:
249
249
  self.info_nRetry += 1
250
250
 
251
251
  if attempt + 1 == REQUEST_MAX_RETRY:
252
- console.log(f"[red]Final retry failed for segment: {index}")
252
+ console.print(f"[red]Final retry failed for segment: {index}")
253
253
  self.queue.put((index, None)) # Marker for failed segment
254
254
  progress_bar.update(1)
255
255
  self.info_nFailed += 1
@@ -15,7 +15,7 @@ from StreamingCommunity.Util.os import os_manager, suppress_output, get_ffmpeg_p
15
15
 
16
16
 
17
17
  # Logic class
18
- from .util import need_to_force_to_ts, check_duration_v_a
18
+ from .util import need_to_force_to_ts, check_duration_v_a, get_video_duration
19
19
  from .capture import capture_ffmpeg_real_time
20
20
  from ..M3U8 import M3U8_Codec
21
21
 
@@ -99,6 +99,14 @@ def join_video(video_path: str, out_path: str, codec: M3U8_Codec = None):
99
99
  - out_path (str): The path to save the output file.
100
100
  - codec (M3U8_Codec): The video codec to use. Defaults to 'copy'.
101
101
  """
102
+ if video_path is None:
103
+ console.log("[red]No video path provided for joining.")
104
+ return None
105
+
106
+ if out_path is None:
107
+ console.log("[red]No output path provided for joining.")
108
+ return None
109
+
102
110
  ffmpeg_cmd = [get_ffmpeg_path()]
103
111
 
104
112
  # Enabled the use of gpu
@@ -175,10 +183,50 @@ def join_audios(video_path: str, audio_tracks: List[Dict[str, str]], out_path: s
175
183
  Parameters:
176
184
  - video_path (str): The path to the video file.
177
185
  - audio_tracks (list[dict[str, str]]): A list of dictionaries containing information about audio tracks.
178
- Each dictionary should contain the 'path' key with the path to the audio file.
186
+ Each dictionary should contain the 'path' and 'name' keys.
179
187
  - out_path (str): The path to save the output file.
180
188
  """
181
- video_audio_same_duration, duration_diff = check_duration_v_a(video_path, audio_tracks[0].get('path'))
189
+ if video_path is None:
190
+ console.log("[red]No video path provided for joining audios.")
191
+ return None, False
192
+
193
+ if audio_tracks is None or len(audio_tracks) == 0:
194
+ console.log("[red]No audio tracks provided for joining.")
195
+ return None, False
196
+
197
+ if out_path is None:
198
+ console.log("[red]No output path provided for joining audios.")
199
+ return None, False
200
+
201
+ use_shortest = False
202
+ duration_diffs = []
203
+
204
+ # Get video duration first
205
+ video_duration = get_video_duration(video_path, None)
206
+
207
+ for audio_track in audio_tracks:
208
+ audio_path = audio_track.get('path')
209
+ audio_lang = audio_track.get('name', 'unknown')
210
+ audio_duration, diff = check_duration_v_a(video_path, audio_path)
211
+
212
+ duration_diffs.append({
213
+ 'language': audio_lang,
214
+ 'difference': diff,
215
+ 'has_error': diff > 0.5,
216
+ 'video_duration': video_duration,
217
+ 'audio_duration': audio_duration
218
+ })
219
+
220
+ if diff > 0.5:
221
+ use_shortest = True
222
+ console.log("[red]Warning: Some audio tracks have duration differences (>0.5s)")
223
+
224
+ # Print duration differences for each track
225
+ if use_shortest:
226
+ for track in duration_diffs:
227
+ color = "red" if track['has_error'] else "green"
228
+ console.print(f"[{color}]Audio {track['language']}: Video duration: {track['video_duration']:.2f}s, Audio duration: {track['audio_duration']:.2f}s, Difference: {track['difference']:.2f}s[/{color}]")
229
+
182
230
 
183
231
  # Start command with locate ffmpeg
184
232
  ffmpeg_cmd = [get_ffmpeg_path()]
@@ -238,9 +286,8 @@ def join_audios(video_path: str, audio_tracks: List[Dict[str, str]], out_path: s
238
286
  else:
239
287
  ffmpeg_cmd.extend(['-preset', 'fast'])
240
288
 
241
- # Use shortest input path for video and audios
242
- if not video_audio_same_duration:
243
- console.log(f"[red]Use shortest input (Duration difference: {duration_diff:.2f} seconds)...")
289
+ # Use shortest input path if any audio track has significant difference
290
+ if use_shortest:
244
291
  ffmpeg_cmd.extend(['-shortest', '-strict', 'experimental'])
245
292
 
246
293
  # Overwrite
@@ -261,7 +308,7 @@ def join_audios(video_path: str, audio_tracks: List[Dict[str, str]], out_path: s
261
308
  capture_ffmpeg_real_time(ffmpeg_cmd, "[cyan]Join audio")
262
309
  print()
263
310
 
264
- return out_path
311
+ return out_path, use_shortest
265
312
 
266
313
 
267
314
  def join_subtitle(video_path: str, subtitles_list: List[Dict[str, str]], out_path: str):
@@ -274,6 +321,18 @@ def join_subtitle(video_path: str, subtitles_list: List[Dict[str, str]], out_pat
274
321
  Each dictionary should contain the 'path' key with the path to the subtitle file and the 'name' key with the name of the subtitle.
275
322
  - out_path (str): The path to save the output file.
276
323
  """
324
+ if video_path is None:
325
+ console.log("[red]No video path provided for joining subtitles.")
326
+ return None
327
+
328
+ if subtitles_list is None or len(subtitles_list) == 0:
329
+ console.log("[red]No subtitles provided for joining.")
330
+ return None
331
+
332
+ if out_path is None:
333
+ console.log("[red]No output path provided for joining subtitles.")
334
+ return None
335
+
277
336
  ffmpeg_cmd = [get_ffmpeg_path(), "-i", video_path]
278
337
 
279
338
  # Add subtitle input files first
@@ -47,15 +47,16 @@ def has_audio_stream(video_path: str) -> bool:
47
47
  return False
48
48
 
49
49
 
50
- def get_video_duration(file_path: str) -> float:
50
+ def get_video_duration(file_path: str, file_type: str = "file") -> float:
51
51
  """
52
- Get the duration of a video file.
52
+ Get the duration of a media file (video or audio).
53
53
 
54
54
  Parameters:
55
- - file_path (str): The path to the video file.
55
+ - file_path (str): The path to the media file.
56
+ - file_type (str): The type of the file ('video' or 'audio'). Defaults to 'file'.
56
57
 
57
58
  Returns:
58
- (float): The duration of the video in seconds if successful, None if there's an error.
59
+ (float): The duration of the media file in seconds if successful, None if there's an error.
59
60
  """
60
61
  try:
61
62
  ffprobe_cmd = [get_ffprobe_path(), '-v', 'error', '-show_format', '-print_format', 'json', file_path]
@@ -64,23 +65,23 @@ def get_video_duration(file_path: str) -> float:
64
65
  # Use a with statement to ensure the subprocess is cleaned up properly
65
66
  with subprocess.Popen(ffprobe_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) as proc:
66
67
  stdout, stderr = proc.communicate()
67
-
68
+
68
69
  if proc.returncode != 0:
69
70
  logging.error(f"Error: {stderr}")
70
71
  return None
71
-
72
+
72
73
  # Parse JSON output
73
74
  probe_result = json.loads(stdout)
74
75
 
75
- # Extract duration from the video information
76
+ # Extract duration from the media information
76
77
  try:
77
78
  return float(probe_result['format']['duration'])
78
-
79
+
79
80
  except Exception:
80
81
  return 1
81
82
 
82
83
  except Exception as e:
83
- logging.error(f"Get video duration error: {e}")
84
+ logging.error(f"Get {file_type} duration error: {e}, ffprobe path: {get_ffprobe_path()}, file path: {file_path}")
84
85
  sys.exit(0)
85
86
 
86
87
 
@@ -242,20 +243,22 @@ def check_duration_v_a(video_path, audio_path, tolerance=1.0):
242
243
  Returns:
243
244
  - tuple: (bool, float) -> True if the duration of the video and audio matches, False otherwise, along with the difference in duration.
244
245
  """
245
- video_duration = get_video_duration(video_path)
246
- audio_duration = get_video_duration(audio_path)
246
+ video_duration = get_video_duration(video_path, file_type="video")
247
+ audio_duration = get_video_duration(audio_path, file_type="audio")
247
248
 
248
249
  # Check if either duration is None and specify which one is None
249
250
  if video_duration is None and audio_duration is None:
250
251
  console.print("[yellow]Warning: Both video and audio durations are None. Returning 0 as duration difference.[/yellow]")
251
252
  return False, 0.0
253
+
252
254
  elif video_duration is None:
253
255
  console.print("[yellow]Warning: Video duration is None. Returning 0 as duration difference.[/yellow]")
254
256
  return False, 0.0
257
+
255
258
  elif audio_duration is None:
256
259
  console.print("[yellow]Warning: Audio duration is None. Returning 0 as duration difference.[/yellow]")
257
260
  return False, 0.0
258
-
261
+
259
262
  # Calculate the duration difference
260
263
  duration_difference = abs(video_duration - audio_duration)
261
264
 
@@ -263,4 +266,4 @@ def check_duration_v_a(video_path, audio_path, tolerance=1.0):
263
266
  if duration_difference <= tolerance:
264
267
  return True, duration_difference
265
268
  else:
266
- return False, duration_difference
269
+ return False, duration_difference
@@ -78,18 +78,4 @@ class M3U8_Decryption:
78
78
  else:
79
79
  raise ValueError("Invalid or unsupported method")
80
80
 
81
- """
82
- end = time.perf_counter_ns()
83
-
84
- # Calculate the elapsed time with high precision
85
- elapsed_nanoseconds = end - start
86
- elapsed_milliseconds = elapsed_nanoseconds / 1_000_000
87
- elapsed_seconds = elapsed_nanoseconds / 1_000_000_000
88
-
89
- # Log performance metrics
90
- logging.info("[Crypto Decryption Performance]")
91
- logging.info(f"Method: {self.method}")
92
- logging.info(f"Decryption Time: {elapsed_milliseconds:.4f} ms ({elapsed_seconds:.6f} s)")
93
- logging.info(f"Decrypted Content Length: {len(decrypted_content)} bytes")
94
- """
95
81
  return decrypted_content
@@ -1,7 +1,6 @@
1
1
  # 24.08.24
2
2
 
3
3
  import sys
4
- from typing import Dict
5
4
 
6
5
 
7
6
  # External libraries
@@ -95,7 +94,6 @@ class TheMovieDB:
95
94
  """
96
95
  self.api_key = api_key
97
96
  self.base_url = "https://api.themoviedb.org/3"
98
- #self.genres = self._fetch_genres()
99
97
  self._cached_trending_tv = None
100
98
  self._cached_trending_movies = None
101
99
 
@@ -120,16 +118,6 @@ class TheMovieDB:
120
118
 
121
119
  return response.json()
122
120
 
123
- def _fetch_genres(self) -> Dict[int, str]:
124
- """
125
- Fetch and return the genre names from TheMovieDB.
126
-
127
- Returns:
128
- Dict[int, str]: A dictionary mapping genre IDs to genre names.
129
- """
130
- genres = self._make_request("genre/movie/list")
131
- return {genre['id']: genre['name'] for genre in genres.get('genres', [])}
132
-
133
121
  def _display_top_5(self, category: str, data, name_key='title'):
134
122
  """
135
123
  Display top 5 most popular items in a single line with colors.
@@ -1,5 +1,5 @@
1
1
  __title__ = 'StreamingCommunity'
2
- __version__ = '3.3.0'
2
+ __version__ = '3.3.2'
3
3
  __author__ = 'Arrowar'
4
4
  __description__ = 'A command-line program to download film'
5
5
  __copyright__ = 'Copyright 2025'