-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathMacAttack.pyw
More file actions
5840 lines (5205 loc) · 278 KB
/
MacAttack.pyw
File metadata and controls
5840 lines (5205 loc) · 278 KB
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
# TODO:
# Clean up code, remove redundancy
VERSION = "4.7.6"
import semver
import urllib.parse
import webbrowser
import base64
import configparser
import hashlib
import json
import logging
import os
import random
from random import choice
import re
import socket
import sys
import threading
from threading import Lock
import traceback
import time
from datetime import datetime, timezone
from contextlib import contextmanager
from collections import deque
# Add the directory containing libvlc.dll to the PATH
script_dir = os.path.dirname(os.path.abspath(__file__))
os.environ["PATH"] = script_dir + os.pathsep + os.environ.get("PATH", "")
import vlc
from PyQt5.QtCore import (
QBuffer,
QByteArray,
QEasingCurve,
QEvent,
QPropertyAnimation,
Qt,
QThread,
QTimer,
pyqtSignal,
)
from PyQt5.QtGui import (
QFont,
QIcon,
QMouseEvent,
QPixmap,
QStandardItem,
QStandardItemModel,
QTextCursor,
)
from PyQt5.QtWidgets import (
QAbstractItemView,
QApplication,
QCheckBox,
QFrame,
QHBoxLayout,
QLabel,
QLineEdit,
QListView,
QMainWindow,
QMessageBox,
QProgressBar,
QPushButton,
QSizePolicy,
QSlider,
QSpacerItem,
QSpinBox,
QTabWidget,
QTextEdit,
QVBoxLayout,
QWidget,
QFileDialog,
QRadioButton,
QButtonGroup,
QComboBox,
)
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import quote, urlparse, urlunparse
logging.basicConfig(level=logging.ERROR)
portaltype = None
player_portaltype = None
@contextmanager
def no_proxy_environment():
"""Context manager that temporarily unsets environment proxy settings."""
# Save the original proxy environment variables
original_http_proxy = os.environ.get("http_proxy")
original_https_proxy = os.environ.get("https_proxy")
try:
# Temporarily remove the environment proxy settings
if "http_proxy" in os.environ:
del os.environ["http_proxy"]
if "https_proxy" in os.environ:
del os.environ["https_proxy"]
yield # Allow the code inside the block to execute
finally:
# Restore the original proxy environment variables
if original_http_proxy is not None:
os.environ["http_proxy"] = original_http_proxy
if original_https_proxy is not None:
os.environ["https_proxy"] = original_https_proxy
def get_token(session, url, mac, timeout=30):
global player_portaltype
player_portal_type_detected = None
player_portaltype = None
# Get and parse the IPTV link
parsed_url = urlparse(url)
parsed_path = parsed_url.path
logging.debug(parsed_path)
# Remove the c/ from the path
if parsed_path.endswith("c"):
parsed_path = parsed_path[:-1]
if parsed_path.endswith("c/"):
parsed_path = parsed_path[:-2]
logging.debug(parsed_path)
host = parsed_url.hostname
port = parsed_url.port or 80
base_url = f"http://{host}:{port}"
headers = {
"User-Agent": "Mozilla/5.0 (QtEmbedded; U; Linux; C) AppleWebKit/533.3 (KHTML, like Gecko) MAG200 stbapp ver: 2 rev: 250 Safari/533.3",
"Accept-Encoding": "identity",
"Accept": "*/*",
"Connection": "keep-alive",
}
if not player_portal_type_detected: # Check for type portal
version_url = f"{base_url}/c/version.js"
try:
response = requests.get(version_url, headers=headers) # Add headers here
response.raise_for_status() # Raise an exception for HTTP errors
# Extract the version using a regex
match = re.search(r"var ver = ['\"](.*?)['\"];", response.text)
if match:
portal_version = match.group(1) # Extracted version string
logging.debug(version_url)
logging.info(
f"\n\n\nPortal type: PORTAL version: {portal_version}\n\n\n"
)
player_portal_type_detected = "portal"
logging.info("Portal type selected: Portal")
player_portaltype = "portal.php"
else:
logging.debug("Version declaration not found in the file.")
except requests.RequestException as e:
logging.debug(f"Not type PORTAL: {e}")
if not player_portal_type_detected: # check for type stalker_portal
version_url = f"{base_url}/stalker_portal/c/version.js"
try:
response = requests.get(version_url, headers=headers) # Add headers here
response.raise_for_status() # Raise an exception for HTTP errors
# Extract the version using a regex
match = re.search(r"var ver = ['\"](.*?)['\"];", response.text)
if match:
portal_version = match.group(1) # Extracted version string
logging.debug(version_url)
logging.info(
f"\n\n\nPortal type: STALKER_PORTAL version: {portal_version}\n\n\n"
)
player_portal_type_detected = "stalker_portal"
player_portaltype = "stalker_portal/server/load.php"
else:
logging.debug("Version declaration not found in the file.")
except requests.RequestException as e:
logging.debug(f"Not type STALKER_PORTAL")
if not player_portal_type_detected: # Others failed, default to "portal"
player_portaltype = "portal.php"
portal_version = "5.3.1"
logging.debug(f"Not type STALKER_PORTAL")
base_url = f"http://{host}:{port}{parsed_path}"
# If both url and method co1antain "stalker_portal/" then remove it from the url
if "stalker_portal/" in base_url and "stalker_portal/" in player_portaltype:
base_url = base_url.replace("stalker_portal/", "")
logging.debug(base_url)
logging.debug(player_portaltype)
handshake_url = f"{url}/{player_portaltype}?action=handshake&type=stb&token=&JsHttpRequest=1-xml"
try:
serialnumber = hashlib.md5(mac.encode()).hexdigest().upper()
sn = serialnumber[0:13]
device_id = hashlib.sha256(sn.encode()).hexdigest().upper()
device_id2 = hashlib.sha256(mac.encode()).hexdigest().upper()
hw_version_2 = hashlib.sha1(mac.encode()).hexdigest()
snmac = f"{sn}{mac}"
sig = hashlib.sha256(snmac.encode()).hexdigest().upper()
cookies = {
"adid": hw_version_2,
"debug": "1",
"device_id2": device_id2,
"device_id": device_id,
"hw_version": "1.7-BD-00",
"mac": mac,
"sn": sn,
"stb_lang": "en",
"timezone": "America/Los_Angeles",
}
headers = {
"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (QtEmbedded; U; Linux; C) AppleWebKit/533.3 (KHTML, like Gecko) MAG200 stbapp ver: 2 rev: 250 Safari/533.3",
"Accept-Encoding": "identity",
"Accept": "*/*",
}
response = session.get(
handshake_url, cookies=cookies, headers=headers, timeout=timeout
)
logging.debug(response.headers)
logging.debug(response.text)
response.raise_for_status()
token = response.json().get("js", {}).get("token")
if token:
token_random = (
response.json().get("js", {}).get("random")
) # Extract 'random' if present
if token_random:
logging.debug(f"RANDOM: {token_random}")
sig = hashlib.sha256(token_random.encode()).hexdigest().upper()
metrics = {
"mac": mac,
"sn": sn,
"type": "STB",
"model": "MAG250",
"uid": device_id,
"random": token_random,
}
json_string = json.dumps(metrics)
encoded_string = urllib.parse.quote(json_string)
logging.debug(encoded_string)
session.headers.update(
{
"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (QtEmbedded; U; Linux; C) AppleWebKit/533.3 (KHTML, like Gecko) MAG200 stbapp ver: 2 rev: 250 Safari/533.3",
"Accept-Encoding": "identity",
"Accept": "*/*",
"Authorization": f"Bearer {token}",
"X-Random": f"{token_random}",
}
)
session.cookies.update(
{
"adid": hw_version_2,
"debug": "1",
"device_id2": device_id2,
"device_id": device_id,
"hw_version": "1.7-BD-00",
"mac": mac,
"sn": sn,
"stb_lang": "en",
"timezone": "America/Los_Angeles",
}
)
url1_a = f"{url}/{player_portaltype}?type=stb&action=get_profile&hd=1&ver=ImageDescription: 0.2.18-r23-250; ImageDate: Wed Aug 29 10:49:53 EEST 2018; PORTAL version: {portal_version}; API Version: JS API version: 343; STB API version: 146; Player Engine version: 0x58c&num_banks=2&sn={sn}&stb_type=MAG250&client_type=STB&image_version=218&video_out=hdmi&device_id={device_id2}&device_id2={device_id2}&sig={sig}&auth_second_step=1&hw_version=1.7-BD-00¬_valid_token=0&metrics={metrics}&hw_version_2={hw_version_2}×tamp={round(time.time())}&api_sig=262&prehash=0"
res1_a = session.get(url1_a)
logging.debug(res1_a.text)
else:
token_random = "0"
logging.info(f"Token retrieved: {token}")
return (token, token_random)
else:
logging.error("Token not found in handshake response.")
return None, None
except Exception as e:
logging.error(f"Error getting token: {e}")
logging.error(f"Error getting token: {e}")
return None, None
class SavePoolWorker(QThread):
save_complete = pyqtSignal()
def __init__(self, mac_dict, file_name):
super().__init__()
self.mac_dict = mac_dict
self.file_name = file_name
def run(self):
mac_list = list(self.mac_dict)
with open(self.file_name, "w") as file:
for mac in mac_list:
file.write(mac + "\n") # Write each MAC address followed by a newline
self.save_complete.emit()
class UpdateWorker(QThread):
update_checked = pyqtSignal(str, str, str)
def run(self):
self.get_update()
def get_update(self):
url = "https://api.github.com/repos/Evilvir-us/MacAttack/releases/latest"
try:
response = requests.get(url)
response.raise_for_status()
latest_release = response.json()
latest_version = latest_release["tag_name"]
release_url = latest_release["html_url"]
logging.info(f"Latest version on GitHub: {latest_version}")
if latest_version.startswith("v"):
latest_version = latest_version[1:]
if semver.compare(VERSION, latest_version) < 0:
logging.info(
f"Update available! Current version: {VERSION}, Latest version: {latest_version}"
)
self.update_checked.emit(VERSION, latest_version, release_url)
else:
logging.info(
f"You are up to date! Current version: {VERSION}, Latest version: {latest_version}"
)
except requests.RequestException as e:
logging.error(f"Error fetching update info: {e}")
self.update_checked.emit("", "", "") # If Error, return nothing
class ProxyFetcher(QThread):
update_proxy_output_signal = pyqtSignal(str)
update_proxy_textbox_signal = pyqtSignal(str)
def __init__(self):
super().__init__()
self.proxy_fetching_speed = 10
self.proxy_testing_speed = 100
def run(self):
self.fetch_and_test_proxies()
def fetch_and_test_proxies(self):
# Fetch proxies
all_proxies = self.fetch_proxies()
if not all_proxies:
self.update_proxy_output_signal.emit(
"No proxies found, check internet connection."
)
return
original_count = len(all_proxies)
all_proxies = list(set(all_proxies)) # Remove duplicates
duplicates_removed = original_count - len(all_proxies)
self.update_proxy_output_signal.emit(
f"Total proxies fetched: {original_count}\n"
)
self.update_proxy_output_signal.emit(
f"Duplicates removed: {duplicates_removed}\n"
)
# Start tracking time for testing proxies
start_time = time.time()
# Test proxies
working_proxies = []
self.update_proxy_output_signal.emit("Testing proxies...")
with ThreadPoolExecutor(max_workers=self.proxy_testing_speed) as executor:
future_to_proxy = {
executor.submit(self.test_proxy, proxy): proxy for proxy in all_proxies
}
for future in as_completed(future_to_proxy):
proxy = future_to_proxy[future]
try:
proxy, is_working = future.result()
if is_working:
self.update_proxy_output_signal.emit(
f"Proxy {proxy} is working."
)
working_proxies.append(proxy)
else:
self.update_proxy_output_signal.emit(f"Proxy {proxy} failed.")
except Exception as e:
logging.debug(f"Error testing proxy {proxy}: {str(e)}")
# End tracking time for testing proxies
end_time = time.time()
testing_time = end_time - start_time # Time in seconds
# Convert seconds to minutes and seconds
minutes = int(testing_time // 60)
seconds = int(testing_time % 60)
# Format testing time as "X Minutes Y Seconds"
formatted_testing_time = f"{minutes} Minutes {seconds} Seconds"
if working_proxies:
self.update_proxy_textbox_signal.emit("\n".join(working_proxies))
self.update_proxy_output_signal.emit(
f"██████╗░░█████╗░███╗░░██╗███████╗\n"
f"██╔══██╗██╔══██╗████╗░██║██╔════╝\n"
f"██║░░██║██║░░██║██╔██╗██║█████╗░░\n"
f"██║░░██║██║░░██║██║╚████║██╔══╝░░\n"
f"██████╔╝╚█████╔╝██║░╚███║███████╗\n"
f"╚═════╝░░╚════╝░╚═╝░░╚══╝╚══════╝ Testing took {formatted_testing_time}\n"
)
else:
self.update_proxy_output_signal.emit("No working proxies found.")
def fetch_proxies(self):
proxies = []
sources = [
"https://spys.me/proxy.txt",
"https://free-proxy-list.net/",
"https://www.us-proxy.org/",
"https://www.sslproxies.org/",
"https://free-proxy-list.net/anonymous-proxy.html",
"https://www.freeproxy.world/?type=http&anonymity=4&country=&speed=400&port=&page=1",
"https://www.freeproxy.world/?type=http&anonymity=4&country=&speed=400&port=&page=2",
"https://www.freeproxy.world/?type=http&anonymity=4&country=&speed=400&port=&page=3",
"https://www.freeproxy.world/?type=http&anonymity=4&country=&speed=400&port=&page=4",
"https://www.freeproxy.world/?type=http&anonymity=4&country=&speed=400&port=&page=5",
]
with ThreadPoolExecutor(max_workers=self.proxy_fetching_speed) as executor:
futures = {
executor.submit(self.fetch_from_source, url): url for url in sources
}
for future in as_completed(futures):
source_url = futures[future]
try:
source_proxies = future.result()
proxies.extend(source_proxies)
except Exception as e:
self.update_proxy_output_signal.emit(
f"Error fetching from {source_url}: {e}"
)
return proxies
def fetch_from_source(self, url):
proxies = []
try:
with no_proxy_environment(): # Bypass the enviroment proxy set in the video player tab
response = requests.get(url, timeout=10)
if response.status_code == 200:
if "spys.me" in url:
regex = r"[0-9]+(?:\.[0-9]+){3}:[0-9]+"
matches = re.finditer(regex, response.text, re.MULTILINE)
proxies.extend([match.group() for match in matches])
elif (
"free-proxy-list.net" in url
or "us-proxy.org" in url
or "sslproxies.org" in url
):
html_content = response.text
ip_port_pattern = re.compile(
r"<td>(\d+\.\d+\.\d+\.\d+)</td><td>(\d+)</td>"
)
matches = ip_port_pattern.findall(html_content)
proxies.extend([f"{ip}:{port}" for ip, port in matches])
elif "freeproxy.world" in url:
html_content = response.text
ip_port_pattern = re.compile(
r'<td class="show-ip-div">\s*(\d+\.\d+\.\d+\.\d+)\s*</td>\s*'
r'<td>\s*<a href=".*?">(\d+)</a>\s*</td>'
)
matches = ip_port_pattern.findall(html_content)
proxies.extend([f"{ip}:{port}" for ip, port in matches])
except requests.exceptions.RequestException as e:
logging.debug(f"Error fetching from {url}: {e}")
return proxies
def test_proxy(self, proxy):
# Check if the returned JSON contains 'user': 'Evilvirus' and that the 'origin' matches the proxy IP.
url = "http://httpbin.org/anything?user=Evilvirus&application=MacAttack"
proxies = {"http": f"http://{proxy}", "https": f"http://{proxy}"}
proxy_ip = urlparse(f"http://{proxy}").hostname
def try_proxy():
try:
with no_proxy_environment(): # Bypass the environment proxy set in the video player tab
response = requests.get(url, proxies=proxies, timeout=30)
if response.status_code == 200:
json_response = response.json()
user = json_response.get("args", {}).get("user")
origin = json_response.get("origin")
logging.info(f"Proxy: {proxy}, Origin: {origin}")
# Check if the user is 'Evilvirus' and the origin matches the proxy IP
if user == "Evilvirus" and origin == proxy_ip:
return True
except requests.RequestException as e:
logging.debug(f"Error testing proxy {proxy}: {str(e)}")
return False
# Try testing the proxy twice (currently disabled)
if try_proxy():
return proxy, True
# elif try_proxy(): # Retry once more if the first attempt fails
# return proxy, True
return proxy, False
class ProxyTester(QThread):
update_proxy_output_signal = pyqtSignal(str)
update_proxy_textbox_signal = pyqtSignal(str)
clear_textbox_signal = pyqtSignal()
def __init__(self, proxy_textbox):
super().__init__()
self.proxy_textbox = proxy_textbox
def run(self):
self.test_proxies()
def test_proxies(self):
# Extract proxies from the text box
proxies = self.proxy_textbox.toPlainText().splitlines()
# Strip empty lines
proxies = [proxy.strip() for proxy in proxies if proxy.strip()]
if not proxies:
self.update_proxy_output_signal.emit("No proxies in the text box.")
return
self.update_proxy_output_signal.emit("Testing proxies...")
working_proxies = []
with ThreadPoolExecutor(max_workers=100) as executor:
future_to_proxy = {
executor.submit(self.test_proxy, proxy): proxy for proxy in proxies
}
for future in as_completed(future_to_proxy):
proxy = future_to_proxy[future]
try:
proxy, is_working = future.result()
if is_working:
self.update_proxy_output_signal.emit(
f"Proxy {proxy} is working."
)
working_proxies.append(proxy)
else:
self.update_proxy_output_signal.emit(f"Proxy {proxy} failed.")
except Exception as e:
logging.debug(f"Error testing proxy {proxy}: {str(e)}")
logging.debug(f"Working proxies: {working_proxies}")
self.clear_textbox_signal.emit() # Clear the textbox
# Remove Dupes
working_proxies = list(set(working_proxies))
logging.debug(f"Unique working proxies: {working_proxies}")
if working_proxies:
# Emit the list of working proxies to the main thread
self.update_proxy_textbox_signal.emit("\n".join(working_proxies))
self.update_proxy_output_signal.emit("Done!")
else:
self.update_proxy_output_signal.emit("No working proxies found.")
def test_proxy(self, proxy):
url = "http://httpbin.org/anything?user=Evilvirus&application=MacAttack"
proxies = {"http": f"http://{proxy}", "https": f"http://{proxy}"}
# Extract the IP address from the proxy, ignoring the port
proxy_ip = urlparse(f"http://{proxy}").hostname
try:
with no_proxy_environment(): # Bypass the environment proxy set in the video player tab
response = requests.get(url, proxies=proxies, timeout=30)
# Check for a successful response and if the returned JSON contains the user value
if response.status_code == 200:
json_response = response.json()
user = json_response.get("args", {}).get("user")
origin = json_response.get("origin")
# Log the proxy and origin values
logging.info(f"Proxy: {proxy}, Origin: {origin}")
# Check if the user is 'Evilvirus' and the origin matches the proxy IP (ignoring the port)
if user == "Evilvirus" and origin == proxy_ip:
logging.debug(f"Proxy {proxy} passed the test")
return proxy, True
else:
logging.debug(f"Proxy {proxy} failed the test")
return proxy, False
except requests.RequestException as e:
logging.debug(f"Error testing proxy {proxy}: {str(e)}")
logging.debug(f"Proxy {proxy} failed due to exception")
return proxy, False
class RequestThread(QThread):
request_complete = pyqtSignal(dict) # Signal to emit when request is complete
update_progress = pyqtSignal(int) # Signal to emit progress updates
channels_loaded = pyqtSignal(list) # Signal to emit channels when loaded
def __init__(
self,
base_url,
mac,
session,
token,
token_random,
category_type=None,
category_id=None,
num_threads=5,
):
super().__init__()
self.base_url = base_url
self.mac = mac
self.session = session
self.token = token
self.token_random = token_random
self.category_type = category_type
self.category_id = category_id
self.num_threads = num_threads
def run(self):
try:
logging.debug("RequestThread started.")
session = self.session
url = self.base_url
mac = self.mac
token = self.token
token_random = self.token_random
# Define cookies and headers for subsequent requests, including the token
serialnumber = hashlib.md5(mac.encode()).hexdigest().upper()
sn = serialnumber[0:13]
device_id = hashlib.sha256(sn.encode()).hexdigest().upper()
device_id2 = hashlib.sha256(mac.encode()).hexdigest().upper()
hw_version_2 = hashlib.sha1(mac.encode()).hexdigest()
cookies = {
"adid": hw_version_2,
"debug": "1",
"device_id2": device_id2,
"device_id": device_id,
"hw_version": "1.7-BD-00",
"mac": mac,
"sn": sn,
"stb_lang": "en",
"timezone": "America/Los_Angeles",
"token": token,
}
headers = {
"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (QtEmbedded; U; Linux; C) "
"AppleWebKit/533.3 (KHTML, like Gecko) "
"MAG200 stbapp ver: 2 rev: 250 Safari/533.3",
"Authorization": f"Bearer {token}",
}
if token_random:
logging.debug(f"RANDOM:{token_random}")
headers = {
"User-Agent": "Mozilla/5.0 (QtEmbedded; U; Linux; C) AppleWebKit/533.3 (KHTML, like Gecko) MAG200 stbapp ver: 2 rev: 250 Safari/533.3",
"Accept-Encoding": "identity",
"Accept": "*/*",
"Connection": "keep-alive",
"Authorization": f"Bearer {token}",
"X-Random": f"{token_random}",
}
cookies = {
"adid": hw_version_2,
"debug": "1",
"device_id2": device_id2,
"device_id": device_id,
"hw_version": "1.7-BD-00",
"mac": mac,
"sn": sn,
"stb_lang": "en",
"timezone": "America/Los_Angeles",
}
if self.category_type and self.category_id:
# Fetch channels in a category
self.update_progress.emit(0) # Start of channel fetching
logging.debug("Fetching channels.")
channels = self.get_channels(
session,
url,
mac,
token,
token_random,
self.category_type,
self.category_id,
self.num_threads,
cookies,
headers,
)
self.update_progress.emit(100)
self.channels_loaded.emit(channels)
else:
# Fetch playlist (Live, Movies, Series) concurrently
data = {}
progress_lock = Lock()
progress = 0
with ThreadPoolExecutor(max_workers=1) as executor:
futures = {
executor.submit(
self.get_genres,
session,
url,
mac,
token,
token_random,
cookies,
headers,
): "Live",
executor.submit(
self.get_vod_categories,
session,
url,
mac,
token,
token_random,
cookies,
headers,
): "Movies",
executor.submit(
self.get_series_categories,
session,
url,
mac,
token,
token_random,
cookies,
headers,
): "Series",
}
total_tasks = (
len(futures) + 2
) # +2 for get_profile and get_main_info
completed_tasks = (
2 # Since get_profile and get_main_info are already done
)
self.update_progress.emit(
int((completed_tasks / total_tasks) * 100)
)
for future in as_completed(futures):
tab_name = futures[future]
try:
result = future.result()
data[tab_name] = result
except Exception as e:
logging.error(f"Error fetching {tab_name}: {e}")
data[tab_name] = []
finally:
with progress_lock:
completed_tasks += 1
progress_percent = int(
(completed_tasks / total_tasks) * 100
)
self.update_progress.emit(progress_percent)
logging.debug(f"Progress: {progress_percent}%")
self.request_complete.emit(data)
except Exception as e:
logging.error(f"Request thread error: {str(e)}")
traceback.print_exc()
self.request_complete.emit({}) # Emit empty data in case of an error
self.update_progress.emit(0) # Reset progress on error
def get_genres(self, session, url, mac, token, token_random, cookies, headers):
try:
genres_url = f"{url}/{player_portaltype}?type=itv&action=get_genres&JsHttpRequest=1-xml"
response = session.get(
genres_url, cookies=cookies, headers=headers, timeout=10
)
logging.debug(response.text)
response.raise_for_status()
genre_data = response.json().get("js", [])
if genre_data:
genres = [
{
"name": i["title"],
"category_type": "IPTV",
"category_id": i["id"],
}
for i in genre_data
]
# Sort genres alphabetically by name
genres.sort(key=lambda x: x["name"])
logging.debug(f"Genres fetched: {genres}")
return genres
else:
logging.warning("No genres data found.")
return []
except Exception as e:
logging.error(f"Error getting genres: {e}")
self.request_complete.emit({}) # Emit empty data if no genres are found
return []
def get_vod_categories(
self, session, url, mac, token, token_random, cookies, headers
):
try:
vod_url = f"{url}/{player_portaltype}?type=vod&action=get_categories&JsHttpRequest=1-xml"
response = session.get(
vod_url, cookies=cookies, headers=headers, timeout=10
)
response.raise_for_status()
categories_data = response.json().get("js", [])
if categories_data:
categories = [
{
"name": category["title"],
"category_type": "VOD",
"category_id": category["id"],
}
for category in categories_data
]
# Sort categories alphabetically by name
categories.sort(key=lambda x: x["name"])
logging.debug(f"VOD categories fetched: {categories}")
return categories
else:
logging.warning("No VOD categories data found.")
return []
except Exception as e:
logging.error(f"Error getting VOD categories: {e}")
return []
def get_series_categories(
self, session, url, mac, token, token_random, cookies, headers
):
try:
series_url = f"{url}/{player_portaltype}?type=series&action=get_categories&JsHttpRequest=1-xml"
response = session.get(
series_url, cookies=cookies, headers=headers, timeout=10
)
logging.debug(response.text)
response.raise_for_status()
response_json = response.json()
logging.debug(f"Series categories response: {response_json}")
if not isinstance(response_json, dict) or "js" not in response_json:
logging.debug("Unexpected response structure for series categories.")
return []
categories_data = response_json.get("js", [])
categories = [
{
"name": category["title"],
"category_type": "Series",
"category_id": category["id"],
}
for category in categories_data
]
# Sort categories alphabetically by name
categories.sort(key=lambda x: x["name"])
logging.debug(f"Series categories fetched: {categories}")
return categories
except Exception as e:
logging.error(f"Error getting series categories: {e}")
return []
def get_channels(
self,
session,
url,
mac,
token,
token_random,
category_type,
category_id,
num_threads,
cookies,
headers,
):
try:
channels = []
# First, get total number of items
logging.debug("get_channels func started")
page_number = 0
total_items = None
initial_url = ""
if category_type == "IPTV":
initial_url = f"{url}/{player_portaltype}?type=itv&action=get_ordered_list&genre={category_id}&JsHttpRequest=1-xml&p=0"
logging.debug(initial_url)
elif category_type == "VOD":
initial_url = f"{url}/{player_portaltype}?type=vod&action=get_ordered_list&category={category_id}&JsHttpRequest=1-xml&p=0"
elif category_type == "Series":
initial_url = f"{url}/{player_portaltype}?type=series&action=get_ordered_list&category={category_id}&p=0&JsHttpRequest=1-xml"
response = session.get(
initial_url, cookies=cookies, headers=headers, timeout=10
)
response.raise_for_status()
response_json = response.json()
logging.debug(response.text)
total_items = int(response_json.get("js", {}).get("total_items", 0))
items_per_page = len(response_json.get("js", {}).get("data", []))
# Don't divide by zero
if items_per_page > 0:
total_pages = (total_items + items_per_page - 1) // items_per_page
else:
total_pages = 0
# First page data
channels_data = response_json.get("js", {}).get("data", [])
for channel in channels_data:
channel["item_type"] = (
"series"
if category_type == "Series"
else "vod" if category_type == "VOD" else "channel"
)
channels.extend(channels_data)
self.update_progress.emit(int(1 / max(total_pages, 1) * 100))
# Prepare page numbers to fetch (exclude page 0 which is already fetched)
if total_pages > 1:
page_numbers = list(range(1, total_pages))
else:
page_numbers = []
# Use ThreadPoolExecutor to fetch pages concurrently
with ThreadPoolExecutor(max_workers=num_threads) as executor:
futures = []
progress_lock = Lock()
progress = 1 # Already fetched page 0
for p in page_numbers:
if category_type == "IPTV":
channels_url = f"{url}/{player_portaltype}?type=itv&action=get_ordered_list&genre={category_id}&JsHttpRequest=1-xml&p={p}"
elif category_type == "VOD":
channels_url = f"{url}/{player_portaltype}?type=vod&action=get_ordered_list&category={category_id}&JsHttpRequest=1-xml&p={p}"
elif category_type == "Series":
channels_url = f"{url}/{player_portaltype}?type=series&action=get_ordered_list&category={category_id}&p={p}&JsHttpRequest=1-xml"
else:
logging.error(f"Unknown category_type: {category_type}")
continue
futures.append(
executor.submit(
self.fetch_page,
channels_url,
cookies,
headers,
category_type,
p,
)
)
total_pages = max(total_pages, 1)
for future in as_completed(futures):
page_channels = future.result()
channels.extend(page_channels)
# Update progress
with progress_lock:
progress += 1
progress_percent = int((progress / total_pages) * 100)
self.update_progress.emit(progress_percent)
logging.debug(f"Progress: {progress_percent}%")
# Deduplicate channels based on their unique identifiers
unique_channels = {}
for channel in channels:
channel_id = channel.get("id")
if channel_id not in unique_channels:
unique_channels[channel_id] = channel
channels = list(unique_channels.values())
# Sort channels alphabetically by name
channels.sort(key=lambda x: x.get("name", ""))
logging.debug(f"Total channels fetched: {len(channels)}")
return channels
except Exception as e:
logging.error(f"An error occurred while retrieving channels: {str(e)}")
return []
def fetch_page(self, url, cookies, headers, category_type, page_number):
try:
logging.debug(f"Fetching page {page_number} from URL: {url}")
session = requests.Session()
response = session.get(url, cookies=cookies, headers=headers, timeout=10)
response.raise_for_status()
response_json = response.json()
channels_data = response_json.get("js", {}).get("data", [])
for channel in channels_data:
channel["item_type"] = (
"series"
if category_type == "Series"