-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathmain.py
2573 lines (2058 loc) · 115 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import gc
gc.disable()
import sys
import time
import httpx
import random
import shutil
import tarfile
import os.path
import zipfile
import argparse
import markdown
import traceback
import src.frontend.resources # Your IDE may tell you that this is an unused import statement, but that is WRONG!
from threading import Event
from io import TextIOWrapper
from itertools import islice, chain
from hqporner_api.api import Sort as hq_Sort
from src.backend.shared_gui import *
from src.backend.class_help import *
from src.backend.shared_functions import *
from src.backend.log_config import setup_logging
from src.frontend.ui_form_license import Ui_SetupLicense
from src.frontend.ui_form_desktop import Ui_PornFetch_Desktop
from src.frontend.ui_form_android import Ui_PornFetch_Android
from src.frontend.ui_form_range_selector import Ui_PornFetchRangeSelector
from src.frontend.ui_form_install_dialog import Ui_SetupInstallDialog
from src.frontend.ui_form_keyboard_shortcuts import Ui_KeyboardShortcuts
from PySide6.QtCore import (QFile, QTextStream, Signal, QRunnable, QThreadPool, QObject, QSemaphore, Qt, QLocale,
QTranslator, QCoreApplication, QSize)
from PySide6.QtWidgets import QWidget, QApplication, QTreeWidgetItem, QButtonGroup, QFileDialog, QHeaderView, QInputDialog
from PySide6.QtGui import QIcon, QFont, QFontDatabase, QPixmap, QShortcut, QKeySequence
"""
Copyright (C) 2023-2025 Johannes Habel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Contact:
E-Mail: EchterAlsFake@proton.me
Discord: echteralsfake (faster response)
"""
__license__ = "GPL 3"
__version__ = "3.5"
__build__ = "desktop" # android or desktop
__author__ = "Johannes Habel"
__next_release__ = "3.6"
total_segments = 0
downloaded_segments = 0
stop_flag = Event()
if __build__ == "android":
os.environ['QT_ANDROID_ENABLE_WORKAROUND_TO_DISABLE_PREDICTIVE_TEXT'] = '1'
os.environ['QT_ANDROID_DISABLE_GLYPH_CACHE_WORKAROUND'] = '1'
os.environ['QT_ANDROID_BACKGROUND_ACTIONS_QUEUE_SIZE'] = '3'
# Just don't ask, thank you :)
url_linux = "https://johnvansickle.com/ffmpeg/builds/ffmpeg-git-amd64-static.tar.xz"
url_windows = "https://www.gyan.dev/ffmpeg/builds/ffmpeg-git-essentials.7z"
url_macOS = "https://evermeet.cx/ffmpeg/ffmpeg-7.1.zip"
session_urls = [] # This list saves all URls used in the current session. Used for the URL export function
total_downloaded_videos = 0 # All videos that actually successfully downloaded
total_downloaded_videos_attempt = 0 # All videos the user tries to download
logger = setup_logging()
logger.setLevel(logging.DEBUG)
class VideoData:
"""
This class stores the video objects and their loaded data across Porn Fetch.
It allows for re-fetching data if needed, update data if needed and handles caching thanks to
a dictionary.
(Okay, I am overhyping it a bit, but yeah, let's put that away xD)
"""
data_objects = {}
consistent_data = {} # This dictionary stores other important data which will be re-used for the entire
# run of Porn Fetch
"""
If a video object isn't used anymore e.g., the video finished downloading or the tree widget was loaded with other
videos, than those videos will be cleaned up in the dictionary, to be as memory and performance efficient as
possible.
"""
def clean_dict(self, video_titles):
if not isinstance(video_titles, list): # In case we only have one video title to delete
video_titles = [video_titles]
for video_title in video_titles:
del self.data_objects[video_title] # Del is faster than pop :)
class Signals(QObject):
"""Signals for the Download class"""
# Progress Signal
total_progress = Signal(int, int) #
progress_add_to_tree_widget = Signal(int, int) # Tracks the number of videos
# loaded and processed into the tree widget
progress_pornhub = Signal(int, int) # Video download progress for pornhub
progress_hqporner = Signal(int, int) # Video download progress for hqporner
progress_eporner = Signal(int, int) # Video download progress for eporner
progress_xnxx = Signal(int, int) # Video download progress for xnxx
progress_xvideos = Signal(int, int) # Video download progress for xvideos
progress_missav = Signal(int, int) # Video download progress for missav
progress_xhamster = Signal(int, int) # Video download progress for xhamster
ffmpeg_converting_progress = Signal(int, int) # Video converting progress for FFmpeg
# Animations
start_undefined_range = Signal() # Starts the loading animation progressbar
stop_undefined_range = Signal() # Stops the loading animation progressbar
# Operations / Reportings
install_finished = Signal(object) # Reports if the Porn Fetch installation was finished
internet_check = Signal(object) # Reports if the internet checks were successful
result = Signal(dict) # Reports the result of the internet checks if something went wrong
error_signal = Signal(object) # A general error signal, which will show errors using a Pop-up
clear_tree_widget_signal = Signal() # A signal to clear the tree widget
text_data_to_tree_widget = Signal(int) # Sends the text data in the form of a dictionary to the main class
download_completed = Signal(object) # Reports a successfully downloaded video
progress_send_video = Signal(object, object) # Sends the selected video objects from the tree widget to the main class
# to download them
url_iterators = Signal(object) # Sends the processed URLs from the file to Porn Fetch
ffmpeg_download_finished = Signal() # Reports the successful download / install of FFmpeg
class License(QWidget):
"""License class to display the GPL 3 License to the user.
And handle the other UI popups"""
def __init__(self, parent=None):
super().__init__(parent)
self.main_widget = None
self.conf = ConfigParser()
self.conf.read("config.ini")
self.android_startup = None
self.install_widget = None
# Set up the UI for License widget
self.ui = Ui_SetupLicense()
self.ui.setupUi(self)
self.ui.button_accept.clicked.connect(self.accept)
self.ui.button_deny.clicked.connect(self.denied)
def check_license_and_proceed(self):
if self.conf["Setup"]["license_accepted"] == "true":
self.show_android_startup_or_main() # License accepted, proceed with Android or main widget
else:
self.show() # License not accepted, show the license widget
def accept(self):
self.conf.set("Setup", "license_accepted", "true")
with open("config.ini", "w") as config_file: # type: TextIOWrapper
self.conf.write(config_file)
self.show_android_startup_or_main()
def denied(self):
self.conf.set("Setup", "license_accepted", "false")
with open("config.ini", "w") as config_file: #type: TextIOWrapper
self.conf.write(config_file)
logger.error("License was denied, closing application")
self.close()
sys.exit(0)
def show_android_startup_or_main(self):
""" Check if running on Android and show the appropriate startup screen. """
self.close()
if __build__ == "android":
self.show_main()
else:
self.show_install_dialog()
def show_install_dialog(self):
if sys.platform == "darwin":
self.show_main() # Installation not supported on macOS
return
if self.conf["Setup"]["install"] == "unknown":
self.install_widget = InstallDialog()
self.install_widget.show()
else:
self.show_main()
def show_main(self):
self.main_widget = PornFetch()
self.main_widget.show()
class InstallDialog(QWidget):
def __init__(self):
super().__init__()
self.conf = ConfigParser()
self.conf.read("config.ini")
self.main_widget = None
self.ui = Ui_SetupInstallDialog()
self.ui.setupUi(self)
self.ui.button_install.clicked.connect(self.start_install)
self.ui.button_portable.clicked.connect(self.start)
def start_install(self):
self.conf.set("Setup", "install", "installed")
with open("config.ini", "w") as config: #type: TextIOWrapper
self.conf.write(config)
self.close()
app_name = self.ui.lineedit_custom_app_name.text() or "Porn Fetch"
logging.info(f"App Name: {app_name}")
self.main_widget = PornFetch(start_installation=True, app_name=app_name)
self.main_widget.show()
def start(self):
self.conf.set("Setup", "install", "portable")
with open("config.ini", "w") as config: #type: TextIOWrapper
self.conf.write(config)
self.close()
self.main_widget = PornFetch()
self.main_widget.show()
class InstallThread(QRunnable):
def __init__(self, app_name):
super(InstallThread, self).__init__()
self.app_name = app_name
self.signals = Signals()
def run(self):
try:
self.signals.start_undefined_range.emit()
if sys.platform == "linux":
filename = "PornFetch_Linux_GUI_x64.bin"
destination_path_tmp = os.path.expanduser("~/.local/share/")
destination_path_final = os.path.expanduser("~/.local/share/pornfetch/")
destination_install = os.path.expanduser("~/.local/share/applications/")
shortcut_path = os.path.join(destination_install, "pornfetch.desktop")
if not os.path.exists(destination_path_tmp):
ui_popup(QCoreApplication.translate(context="main", key="""The path ~/.local/share/ does not exist. This path is typically used for installing applications and their settings
in a users local account. Since you don't have that, you can't install it. Probably because your Linux does not follow
the XDG Desktop Portal specifications. It's your own decision and I don't create the directory for you, or force you to
do that. If you still wish to install Porn Fetch, look Online how to setup XDK-Desktop-Portal on your Linux distribution,
head over to the setting and down there you will be able to try the installation again. Otherwise, you can just keep
using the portable version, which will work just fine.
If you believe, that this is a mistake, please report it on GitHub, so that I can fix it :)""", disambiguation=None))
return
try:
os.makedirs(destination_path_final, exist_ok=True)
except PermissionError:
ui_popup("""You do not have permissions to create the folder 'pornfetch' inside {destination_path_tmp}!
The installation process will stop now. You can either run Porn Fetch with elevated privileges, or use the portable
version.""")
return
pornfetch_exe = os.path.join(destination_path_final, filename)
if os.path.exists(pornfetch_exe):
os.remove(pornfetch_exe)
shutil.move("PornFetch_Linux_GUI_x64.bin", dst=destination_path_final)
logger.info(f"Moved the PornFetch binary to: {destination_path_final}")
if not os.path.exists(os.path.join(destination_path_final, "config.ini")):
shutil.move("config.ini", dst=destination_path_final)
logger.info("Moved configuration file")
logger.info(f"Downloading additional asset: icon")
if not os.path.exists(os.path.join(destination_path_final, "Logo.png")):
img = BaseCore().fetch(
"https://github.com/EchterAlsFake/Porn_Fetch/blob/master/src/frontend/graphics/android_app_icon.png?raw=true", get_response=True)
if not img.status_code == 200:
ui_popup("Couldn't download the Porn Fetch logo. Installation will still be successfully, but please"
"report this error on GitHub. Thank you.")
elif img.status_code == 200:
with open("Logo.png", "wb") as logo:
logo.write(img.content)
shutil.move("Logo.png", dst=destination_path_final)
entry_content = f"""[Desktop Entry]
Name={self.app_name}
Exec={destination_path_final}PornFetch_Linux_GUI_x64.bin %F
Icon={destination_path_final}Logo.png
Type=Application
Terminal=false
Categories=Utility;"""
if os.path.exists(shortcut_path):
os.remove(shortcut_path)
with open("pornfetch.desktop", "w") as entry_file:
entry_file.write(entry_content)
shutil.move("pornfetch.desktop", shortcut_path)
logger.info("Successfully installed Porn Fetch!")
os.chmod(mode=0o755,
path=destination_path_final + "PornFetch_Linux_GUI_x64.bin") # Setting executable permission
elif sys.platform == "win32":
import win32com.client # Only available on Windows
filename = "PornFetch_Windows_GUI_x64.exe"
target_dir = os.path.join(os.getenv("LOCALAPPDATA"), "pornfetch")
os.makedirs(target_dir, exist_ok=True)
if os.path.exists(os.path.join(target_dir, filename)):
os.remove(os.path.join(target_dir, filename))
# Move the executable to the target directory
shutil.move(filename, target_dir)
if not os.path.exists(os.path.join(target_dir, "config.ini")):
shutil.move("config.ini", target_dir) # Prevent overriding the old configuration file
# Define paths for the shortcut creation
app_name = self.app_name
app_exe_path = os.path.join(target_dir, filename) # Full path to the executable
start_menu_path = os.path.join(os.getenv("APPDATA"), "Microsoft", "Windows", "Start Menu", "Programs")
shortcut_path = os.path.join(start_menu_path, f"{app_name}.lnk")
# Create the shortcut
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortcut(shortcut_path)
shortcut.TargetPath = app_exe_path # Path to the executable
shortcut.WorkingDirectory = target_dir # Set working directory to the target directory
shortcut.IconLocation = app_exe_path
shortcut.Save()
except Exception:
error = traceback.format_exc()
self.signals.install_finished.emit([False, error])
self.signals.stop_undefined_range.emit()
self.signals.stop_undefined_range.emit()
self.signals.install_finished.emit([True, ""])
# Porn Fetch installation is finished
class InternetCheck(QRunnable):
def __init__(self):
super(InternetCheck, self).__init__()
self.websites = [
"https://www.pornhub.com",
"https://hqporner.com",
"https://www.xvideos.com",
"https://www.xnxx.com",
"https://www.missav.ws",
"https://www.xhamster.com"
# Append new URLs here
]
self.website_results = {}
self.signals = Signals()
def run(self):
for idx, website in enumerate(self.websites, start=1):
logger.debug(f"[{idx}|{len(self.websites)}] Testing: {website}")
try:
logging.info(f"Testing Internet [{idx / len(self.websites)}] : {website}")
status = BaseCore().fetch(website, get_response=True)
if status.status_code == 200:
self.website_results.update({website: "✔"})
elif status.status_code == 404:
if not website == "https://www.missav.ws": # Could get taken down, so yeah ;)
self.website_results.update({website: "Failed, website doesn't exist? Please report this error"})
except Exception:
error = traceback.format_exc()
self.signals.error_signal.emit(error)
self.signals.internet_check.emit(self.website_results)
class CheckUpdates(QRunnable):
def __init__(self):
super(CheckUpdates, self).__init__()
self.signals = Signals()
def run(self):
url = f"https://github.com/EchterAlsFake/Porn_Fetch/releases/tag/{__next_release__}"
try:
request = BaseCore().fetch(url, get_response=True)
if request.status_code == 200:
logger.info("NEW UPDATE IS AVAILABLE!")
self.signals.result.emit(True)
else:
logger.info("Checked for updates, no update is available.")
self.signals.result.emit(False)
except AttributeError:
logger.info("Checked for updates, no update is available.")
self.signals.result.emit(False) # Please just don't ask, thanks :)
except Exception:
error = traceback.format_exc()
logger.error(f"Could not check for updates. Please report the following error on GitHub: {error}")
self.signals.error_signal.emit(error)
class FFMPEGDownload(QRunnable):
"""Downloads ffmpeg into the execution path of Porn Fetch"""
def __init__(self, url, extract_path, mode):
super().__init__()
self.url = url
self.extract_path = extract_path
self.mode = mode
self.signals = Signals()
@staticmethod
def delete_dir():
deleted_any = False
cwd = os.getcwd()
for entry in os.listdir(cwd):
if "ffmpeg" in entry.lower():
full_path = os.path.join(cwd, entry)
if os.path.isdir(full_path):
try:
shutil.rmtree(full_path)
logger.info(f"Deleted folder: {full_path}")
deleted_any = True
except Exception as e:
logger.error(f"Error deleting folder {full_path}: {e}")
return deleted_any
def run(self):
# Download the file
logger.debug(f"Downloading: {self.url}")
logger.debug("FFMPEG: [1/4] Starting the download")
with httpx.stream("GET", self.url) as r:
r.raise_for_status()
if self.url == url_windows or self.url == url_macOS:
total_length = int(r.headers.get('content-length'))
else:
total_length = 41964060
self.signals.total_progress.emit(0, total_length) # Initialize progress bar
dl = 0
filename = self.url.split('/')[-1]
with open(filename, 'wb') as f:
for chunk in r.iter_bytes(chunk_size=8192):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
dl += len(chunk)
self.signals.total_progress.emit(dl, total_length)
logger.debug("FFMPEG: [2/4] Starting file extraction")
# Extract the file based on OS mode
if self.mode == "linux" and filename.endswith(".tar.xz"):
with tarfile.open(filename, "r:xz") as tar:
total_members = len(tar.getmembers())
for idx, member in enumerate(tar.getmembers()):
if 'ffmpeg' in member.name and (member.name.endswith('ffmpeg')):
tar.extract(member, self.extract_path, filter="data")
extracted_path = os.path.join(self.extract_path, member.path)
shutil.move(extracted_path, "./")
self.signals.total_progress.emit(idx, total_members)
os.chmod("ffmpeg", 0o755)
elif self.mode == "windows" and filename.endswith(".zip"):
with zipfile.ZipFile(filename, 'r') as zip_ref:
total = len(zip_ref.namelist())
for idx, member in enumerate(zip_ref.namelist()):
if 'ffmpeg.exe' in member:
zip_ref.extract(member, self.extract_path)
extracted_path = os.path.join(self.extract_path, member)
shutil.move(extracted_path, ".")
self.signals.total_progress.emit(idx, total)
elif self.mode == "macOS" and filename.endswith(".zip"):
with zipfile.ZipFile(filename, mode='r') as archive:
archive.extractall(path=self.extract_path)
os.chmod("ffmpeg", 0o755) # Sets executable, read and write permissions
logger.debug("FFMPEG: [3/4] Finished Extraction")
# Finalize
self.signals.total_progress.emit(total_length, total_length) # Ensure progress bar reaches 100%
os.remove(filename) # Clean up downloaded archive
if self.delete_dir():
logger.debug("FFMPEG: [4/4] Cleaned Up")
else:
logger.error("The Regex for finding the FFmpeg version failed. Please report this on GitHub!, Thanks.")
self.signals.ffmpeg_download_finished.emit()
class AddToTreeWidget(QRunnable):
def __init__(self, iterator, is_reverse, is_checked, last_index):
super(AddToTreeWidget, self).__init__()
self.signals = Signals() # Processing signals for progress and information
self.iterator = iterator # The video iterator (Search or model object yk)
self.reverse = is_reverse # If the user wants to display the videos in reverse
self.stop_flag = stop_flag # If the user pressed the stop process button
self.is_checked = is_checked # If the "do not clear videos" checkbox is checked
self.last_index = last_index # The last index (video) of the tree widget to maintain a correct order of numbers
self.consistent_data = VideoData().consistent_data
self.output_path = self.consistent_data.get("output_path")
self.search_limit = self.consistent_data.get("search_limit")
def process_video(self, video, index):
logger.debug(f"Requesting video processing of: {video.url}")
try:
data = load_video_attributes(video)
video_id = random.randint(0, 99999999) # Creates a random ID for each video
stripped_title = BaseCore().strip_title(data.get("title")) # Strip the title so that videos with special chars can be
# saved on windows. it would raise an OSError otherwise
logger.debug(f"Created ID: {video_id} for: {stripped_title}")
if self.consistent_data.get("directory_system"): # If the directory system is enabled, this will create an additional folder
author_path = os.path.join(self.output_path, data.get("author"))
os.makedirs(author_path, exist_ok=True)
output_path = os.path.join(str(author_path), stripped_title + ".mp4") if self.consistent_data.get(
"directory_system") else os.path.join(self.output_path, stripped_title + ".mp4")
else:
output_path = os.path.join(self.output_path, stripped_title + ".mp4")
# Emit the loaded signal with all the required information
data.update(
{
"title": stripped_title,
"output_path": output_path,
"index": index,
"video": video
})
VideoData().data_objects.update({video_id: data})
return video_id
except (errors.PremiumVideo, IndexError):
logger.error(f"Warning: The video {video.url} is a Premium-only video and will be skipped.")
self.signals.error_signal.emit(f"Premium-only video skipped: {video.url}")
return False
except errors.RegionBlocked:
logger.error(f"Warning: The video {video.url} is region-blocked or private and will be skipped.")
self.signals.error_signal.emit(f"Region-blocked video skipped: {video.url}")
return False
except Exception:
error = traceback.format_exc()
logger.exception(f"Unexpected error while processing video: {error}")
self.signals.error_signal.emit(f"Unexpected error occurred: {error}")
return False
def run(self):
if not self.is_checked:
self.signals.clear_tree_widget_signal.emit() # Clears the tree widget
self.signals.start_undefined_range.emit() # Starts the progressbar, but with a loading animation
if self.is_checked:
index = self.last_index
start = index
self.search_limit += self.search_limit
else:
start = 1
self.last_index = start
try:
logger.debug(f"Result Limit: {str(self.search_limit)}")
if self.reverse:
logger.debug("Reversing Videos. This may take some time...")
# Use islice to limit the number of items fetched from the iterator
videos = list(islice(self.iterator, self.search_limit)) # Can take A LOT of time (like really)
videos.reverse() # Reverse the list (to show videos in reverse order)
else:
videos = islice(self.iterator, self.search_limit)
success = False
for i, video in enumerate(videos, start=start):
if self.stop_flag.is_set():
return # Stop processing if user pressed the stop button
try_attempt = True
while try_attempt:
try:
if i >= self.search_limit + 1:
break # Respect search limit
video_id = self.process_video(video, i) # Passes video and index object / int
if success is False:
self.signals.stop_undefined_range.emit() # Stop the loading animation
success = True
self.signals.progress_add_to_tree_widget.emit(self.search_limit, i)
self.signals.text_data_to_tree_widget.emit(video_id)
try_attempt = False # Processing succeeded
except errors.RegexError as e:
logger.error(f"Regex error: {e}")
self.signals.error_signal.emit(f"Regex error: {e}. Please report this issue.")
continue
except (ConnectionError, ConnectionAbortedError, ConnectionResetError) as e:
logger.error(f"Connection error: {e}")
self.signals.error_signal.emit(f"Connection error: {e}. Retrying in 20 seconds...")
time.sleep(20)
continue
except Exception:
error = traceback.format_exc()
logger.exception(f"Fatal error in run: {error}")
self.signals.error_signal.emit(f"Fatal error: {error}")
finally:
self.signals.stop_undefined_range.emit()
class DownloadThread(QRunnable):
"""Refactored threading class to download videos with improved performance and logic."""
def __init__(self, video, video_id):
super().__init__()
self.ffmpeg = None
self.video = video
self.video_id = video_id
self.consistent_data = VideoData().consistent_data
self.quality = self.consistent_data.get("quality")
data_object: dict = VideoData().data_objects[self.video_id]
self.output_path = data_object.get("output_path")
self.threading_mode = self.consistent_data.get("threading_mode")
self.signals = Signals()
self.stop_flag = stop_flag
self.skip_existing_files = self.consistent_data.get("skip_existing_files")
self.workers = int(self.consistent_data.get("workers"))
self.timeout = int(self.consistent_data.get("timeout"))
self.video_progress = {}
self.last_update_time = 0
self.progress_signals = {
'pornhub': self.signals.progress_pornhub,
'hqporner': self.signals.progress_hqporner,
'eporner': self.signals.progress_eporner,
'xnxx': self.signals.progress_xnxx,
'xvideos': self.signals.progress_xvideos,
'missav': self.signals.progress_missav,
'xhamster': self.signals.progress_xhamster
}
def generic_callback(self, pos, total, signal, video_source, ffmpeg=False):
"""Generic callback function to emit progress signals with rate limiting."""
current_time = time.time()
if self.stop_flag.is_set():
return
if ffmpeg:
self.update_ffmpeg_progress(pos, total)
signal.emit(pos, total)
else:
# Emit signal for individual progress
if video_source == "hqporner" or video_source == "eporner":
# Check if the current time is at least 0.5 seconds greater than the last update time
if current_time - self.last_update_time < 0.5:
# If not, do not update the progress and return immediately
return
scaling_factor = 1024 * 1024
pos = int(pos / scaling_factor)
total = int(total / scaling_factor)
signal.emit(pos, total)
# Update total progress only if the video source uses segments
if video_source not in ['hqporner', 'eporner']:
self.update_total_progress(ffmpeg)
# Update the last update time to the current time
self.last_update_time = current_time
def update_ffmpeg_progress(self, pos, total):
"""Update progress for ffmpeg downloads."""
print(f"\r\033[KProgress: [{pos} / 100]", end='', flush=True) # I don't know why, but this fixes the progress.
video_title = self.video.title
self.video_progress[
video_title] = pos / total * 100 # video title as video id, to keep track which video has how much progress done
total_progress = sum(self.video_progress.values()) / len(self.video_progress)
self.signals.total_progress.emit(total_progress, 100)
def update_total_progress(self, ffmpeg):
"""Update total download progress."""
if not ffmpeg:
global downloaded_segments
downloaded_segments += 1
self.signals.total_progress.emit(downloaded_segments, total_segments)
def run(self):
"""Run the download in a thread, optimizing for different video sources and modes."""
try:
if os.path.isfile(self.output_path):
if self.skip_existing_files:
logger.debug("The file already exists, skipping...")
self.signals.download_completed.emit(True)
return
else:
logger.debug("The file already exists, appending random number...")
path = str(self.output_path).split(".")
path = path[0] + str(random.randint(0, 1000)) + ".mp4"
self.output_path = path
logger.debug(f"Downloading Video to: {self.output_path}")
if self.threading_mode == "FFMPEG" or self.threading_mode == download.FFMPEG:
self.ffmpeg = True
if isinstance(self.video, Video): # Assuming 'Video' is the class for Pornhub
video_source = "pornhub"
path = self.output_path
logger.debug("Starting the Download!")
try:
self.video.download(downloader=self.threading_mode, path=path, quality=self.quality,
display=lambda pos, total: self.generic_callback(pos, total,
self.signals.progress_pornhub,
video_source, self.ffmpeg))
except TypeError:
self.video.download(downloader=self.threading_mode, path=path, quality=self.quality,
display=lambda pos, total: self.generic_callback(pos, total,
self.signals.progress_pornhub,
video_source, self.ffmpeg))
# We need to specify the sources, so that it knows which individual progressbar to use
elif isinstance(self.video, hq_Video):
video_source = "hqporner"
self.video.download(quality=self.quality, path=self.output_path, no_title=True,
callback=lambda pos, total: self.generic_callback(pos, total,
self.signals.progress_hqporner,
video_source, self.ffmpeg))
elif isinstance(self.video, ep_Video):
video_source = "eporner"
self.video.download(quality=self.quality, path=self.output_path, no_title=True,
callback=lambda pos, total: self.generic_callback(pos, total,
self.signals.progress_eporner,
video_source, self.ffmpeg))
elif isinstance(self.video, xn_Video):
video_source = "xnxx"
self.video.download(downloader=self.threading_mode, path=self.output_path, quality=self.quality, no_title=True,
callback=lambda pos, total: self.generic_callback(pos, total,
self.signals.progress_xnxx,
video_source, self.ffmpeg))
elif isinstance(self.video, xv_Video):
video_source = "xvideos"
self.video.download(downloader=self.threading_mode, path=self.output_path, quality=self.quality, no_title=True,
callback=lambda pos, total: self.generic_callback(pos, total,
self.signals.progress_xvideos,
video_source, self.ffmpeg))
elif isinstance(self.video, mv_Video):
video_source = "missav"
self.video.download(downloader=self.threading_mode, path=self.output_path, quality=self.quality, no_title=True,
callback=lambda pos, total: self.generic_callback(pos, total,
self.signals.progress_missav,
video_source, self.ffmpeg))
elif isinstance(self.video, xh_Video):
video_source = "xhamster"
self.video.download(downloader=self.threading_mode, path=self.output_path, quality=self.quality, no_title=True,
callback=lambda pos, total: self.generic_callback(pos, total,
self.signals.progress_xhamster,
video_source, self.ffmpeg))
# ... other video types ...
finally:
self.signals.download_completed.emit(self.video_id)
class PostProcessVideoThread(QRunnable):
"""
This class will be executed (if enabled by the user) to convert the final video into different formats and apply
metadata to it.
"""
def __init__(self, video_id):
super(PostProcessVideoThread, self).__init__()
self.signals = Signals()
self.consistent_data = VideoData().consistent_data
self.data = VideoData().data_objects.get(video_id)
self.write_tags_ = self.consistent_data.get("write_metadata")
self.ffmpeg_path = self.consistent_data.get("ffmpeg_path")
self.video_format = self.consistent_data.get("video_format")
self.path = self.data.get("output_path")
def run(self):
if self.ffmpeg_path is None:
logger.warning("FFmpeg couldn't be found during initialization. Video post processing will be skipped!")
return
try:
os.rename(f"{self.path}", f"{self.path}_.tmp")
logger.debug(f"FFMPEG PATH: {self.ffmpeg_path}")
# Keeping a local variable space, because otherwise variables get messed up
temp_path = f"{self.path}_.tmp"
target_mp4_path = self.path
other_format_path_ = str(self.path).replace(".mp4", "") # Videos are by default downloaded in .mp4, that's why I need to strip the mp4 out
other_format_path = f"{other_format_path_}.{self.video_format}"
if self.video_format == "mp4":
cmd = [self.ffmpeg_path, "-i", temp_path, "-c", "copy", target_mp4_path]
path_for_tags = target_mp4_path
else:
cmd = [self.ffmpeg_path, '-i', temp_path, other_format_path]
path_for_tags = other_format_path
ff = FfmpegProgress(cmd)
for progress in ff.run_command_with_progress():
self.signals.ffmpeg_converting_progress.emit(round(progress), 100)
os.remove(temp_path)
if self.video_format == "mp4":
if self.write_tags_:
write_tags(path=path_for_tags, data=self.data)
else:
logger.warning(f"You've set your format to: {self.video_format}. Writing metadata tags is not supported in this case!")
except Exception:
error = traceback.format_exc()
self.signals.error_signal.emit(error)
class QTreeWidgetDownloadThread(QRunnable):
"""Threading class for the QTreeWidget (sends objects to the download class defined above)"""
def __init__(self, tree_widget, semaphore):
super(QTreeWidgetDownloadThread, self).__init__()
self.treeWidget = tree_widget
self.signals = Signals()
self.consistent_data = VideoData().consistent_data
self.threading_mode = self.consistent_data.get("threading_mode")
self.quality = self.consistent_data.get("quality")
self.semaphore = semaphore
def run(self):
self.signals.start_undefined_range.emit()
video_objects = []
data_objects = []
for i in range(self.treeWidget.topLevelItemCount()):
item = self.treeWidget.topLevelItem(i)
check_state = item.checkState(0)
if check_state == Qt.CheckState.Checked:
video_objects.append(item.data(0, Qt.ItemDataRole.UserRole))
data_objects.append(item.data(1, Qt.ItemDataRole.UserRole))
if not self.threading_mode == "FFMPEG":
logger.debug("Getting segments...")
global total_segments, downloaded_segments
total_segments += sum(
[len(list(video.get_segments(quality=self.quality))) for video in video_objects if
hasattr(video, 'get_segments')])
logger.debug("Got segments")
# This basically looks how many segments exist in all videos together, so that we can calculate the total
# progress
else:
logger.debug("Progress tracking: FFMPEG")
# FFMPEG has always 0-100 as progress callback, that is why I specify 100 for each video instead of the
# total segments
counter = 0
for _ in video_objects:
counter += 100
total_segments = counter
downloaded_segments = 0
self.signals.stop_undefined_range.emit()
for idx, video in enumerate(video_objects):
self.semaphore.acquire() # Trying to start the download if the thread isn't locked
logger.debug("Semaphore Acquired")
self.signals.progress_send_video.emit(video, data_objects[idx]) # Now emits the video to the main class for further processing
class AddUrls(QRunnable):
"""
This class is used to add the URLs from the 'open file' function, because the UI doesn't respond until
all URLs / Models / Search terms have been processed. This is why I made this threading class
"""
def __init__(self, file, delay):
super(AddUrls, self).__init__()
self.signals = Signals()
self.file = file
self.delay = delay
def run(self):
iterator = []
model_iterators = []
search_iterators = []
with open(self.file, "r") as url_file:
content = url_file.read().splitlines()
for idx, line in enumerate(content):
if len(line) == 0:
continue
total = len(content)
if line.startswith("model#"):
line = line.split("#")[1]
model_iterators.append(line)
search_iterators.append(line)
elif line.startswith("search#"):
query = line.split("#")[1]
site = line.split("#")[2]
search_iterators.append({"website": site,
"query": query})
else:
video = check_video(line)
if video is not False:
iterator.append(video)
self.signals.total_progress.emit(idx, total)
self.signals.url_iterators.emit(iterator, model_iterators, search_iterators)
class PornFetch(QWidget):
def __init__(self, parent=None, start_installation=False, app_name="Porn Fetch"):
super().__init__(parent)
# Variable initialization:
self.app_name = app_name
# Threads
self.install_thread = None