forked from XiaoYouChR/Ghost-Downloader-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGhostDownloader2.py
2389 lines (1981 loc) · 95.3 KB
/
GhostDownloader2.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 ssl
import sys
import threading
import time
import winreg
from datetime import timedelta
from glob import glob
from multiprocessing import freeze_support
from os import path, getcwd, makedirs, access, W_OK, startfile, remove
from re import findall, IGNORECASE, compile, sub
from urllib import request
from webbrowser import open_new_tab
import requests
from PySide2.QtCore import QRect, Signal, QSize, QLockFile, QObject,QPropertyAnimation, QEasingCurve
from PySide2.QtGui import Qt, QPixmap, QIcon, QMovie
from PySide2.QtWidgets import QScrollArea, QWidget, QPushButton, QSizePolicy, QLabel, QApplication, QMessageBox, \
QComboBox, QGroupBox, QHBoxLayout, QVBoxLayout, QTextEdit, QLineEdit, QSpacerItem, QFileDialog, \
QSystemTrayIcon, QFrame, QPlainTextEdit, QTableWidget, QTableWidgetItem, QRadioButton
from DownloadEngine import DownloadEngine
from framelesswindow import AcrylicWindow, AcrylicDialog
from titlebar import MainWindowTitleBar
# 槽
def Move(object, x, y):
object.move(x, y)
def SetText(object, text: str):
object.setText(text)
def Resize(object, width: int, height: int):
object.resize(width, height)
def MessageBox(icon: QPixmap, title: str, content: str):
MyMessageBox(icon, title, content)
# 全局信号类
class GlobalSignal(QObject):
# 自定义信号
move_object = Signal(QWidget, int, int)
change_text = Signal(QLabel, str)
resize_object = Signal(QWidget, int, int)
message_box = Signal(QPixmap, str, str)
# 实例化信号类并Connect
globalSignal = GlobalSignal()
globalSignal.move_object.connect(Move)
globalSignal.change_text.connect(SetText)
globalSignal.resize_object.connect(Resize)
globalSignal.message_box.connect(MessageBox)
# 全局函数
def countActionValues(start: int, end: int):
temp = end - start
# actionValuesList = [1 / 24, 1 / 24, 1 / 16, 1 / 12, 1 / 8, 1 / 4, 1 / 6, 1 / 12, 1 / 12, 1 / 16]
# actionValuesList = [0.015,0.05,0.1,0.2,0.35,0.6,0.8,0.9,0.95,1]
actionValuesList = [0.005, 0.015, 0.03, 0.05, 0.07, 0.1, 0.14, 0.2, 0.27, 0.35, 0.4, 0.6, 0.72, 0.8, 0.84, 0.9,
0.94, 0.96, 0.98, 1]
actionValuesList = [i * temp + start for i in actionValuesList]
return actionValuesList
def resizeAction(object, width: int, height: int):
def action():
objW = object.width()
objH = object.height()
if objW != width and objH != height:
actionWidthesList = countActionValues(objW, width)
actionHeightsList = countActionValues(objH, height)
for i in range(len(actionWidthesList)):
globalSignal.resize_object.emit(object, actionWidthesList[i], actionHeightsList[i])
time.sleep(0.013)
elif objW != width:
actionWidthesList = countActionValues(objW, width)
for i in actionWidthesList:
globalSignal.resize_object.emit(object, i, height)
time.sleep(0.013)
elif objH != height:
actionHeightsList = countActionValues(objH, height)
for i in actionHeightsList:
globalSignal.resize_object.emit(object, width, i)
time.sleep(0.013)
threading.Thread(target=action, daemon=True).start()
def moveAction(object, x: int, y: int, close=False):
def action():
objX = object.x()
objY = object.y()
if objX != x and objY != y:
actionXsList = countActionValues(objX, x)
actionYsList = countActionValues(objY, y)
for i in range(len(actionXsList)):
globalSignal.move_object.emit(object, actionXsList[i], actionYsList[i])
time.sleep(0.013)
elif objX != x:
actionValuesList = countActionValues(objX, x)
for i in actionValuesList:
globalSignal.move_object.emit(object, i, objY)
time.sleep(0.013)
elif objY != y:
actionValuesList = countActionValues(objY, y)
for i in actionValuesList:
globalSignal.move_object.emit(object, objX, i)
time.sleep(0.013)
if close == True:
object.close()
threading.Thread(target=action, daemon=True).start()
def changeConfig():
with open("config.cfg", "w", encoding="utf-8") as f:
f.write(f"{threadNum}\n{defaultPath}\n{skinName}\n{reduceSpeed}\n{reduceSpeed_2}\n{GUI}")
print(f"{threadNum}\n{defaultPath}\n{skinName}\n{reduceSpeed}\n{reduceSpeed_2}\n{GUI}")
f.close()
def decidePathWin(parent, texiEdit, default=False):
global defaultPath
filePath = QFileDialog.getExistingDirectory(parent, "选择文件夹", dir=defaultPath)
if not filePath == "":
if not default:
texiEdit.setText(filePath)
elif default:
defaultPath = filePath
texiEdit.setText(defaultPath)
changeConfig()
def newDownloadTask(iconPath: str, url: str, filename: str, download_dir: str, blocks_num: int, parent=None,
autoStarted=False):
global DownGroupBoxesList
if not autoStarted:
if path.exists("history.xml") == True:
with open("history.xml", "r", encoding="utf-8") as f:
tmp = f.read()
f.close()
tmp = findall(f"<hst><filename>{filename}</filename><downdir>{download_dir}</downdir>", tmp)
print(tmp)
if tmp:
globalSignal.message_box.emit(parent.logoImg, "你这是故意找茬啊", "有把同一个文件下载到同一个文件夹的人吗?")
return # 结束
elif not tmp:
with open("history.xml", "a", encoding="utf-8") as t:
t.write(f"<hst><filename>{filename}</filename><downdir>{download_dir}</downdir>"
f"<downurl>{url}</downurl><threadnum>{blocks_num}</threadnum><icon>{iconPath}</icon></hst>")
t.close()
else:
with open("history.xml", "w", encoding="utf-8") as f:
f.write(f"<hst><filename>{filename}</filename><downdir>{download_dir}</downdir>"
f"<downurl>{url}</downurl><threadnum>{blocks_num}</threadnum><icon>{iconPath}</icon></hst>")
f.close()
icon = QPixmap(iconPath)
DownGroupBoxesList.append(DownGroupBox(icon, url, filename, download_dir, blocks_num, parent))
ID = len(DownGroupBoxesList) - 1
try:
DownGroupBoxesList[ID].resize(window.w - 20, 73)
except:
DownGroupBoxesList[ID].resize(580, 73)
DownGroupBoxesList[ID].move(3, ID * 78 + 5)
DownGroupBoxesList[ID].show()
parent.downWidget.resize(parent.downWidget.width(), (ID + 1) * 78 + 5)
# 类
class PictureLabel(QLabel):
def __init__(self, parent, pixmap: QPixmap=None):
super(PictureLabel, self).__init__(parent)
self.setScaledContents(True)
if pixmap:
self.setPixmap(pixmap)
class BeggingWindow(AcrylicWindow):
def __init__(self, parent=None):
super(BeggingWindow, self).__init__(parent=parent, skinName=skinName)
# QSS
with open(f"{skinName}/GlobalQSS.qss", "r", encoding="utf-8") as f:
GlobalQSS = f.read()
# self.setStyleSheet(_)
f.close()
with open(f"{skinName}/MainQSS.qss", "r", encoding="utf-8") as f:
MainQSS = f.read()
# self.setStyleSheet(_)
f.close()
self.setStyleSheet(GlobalQSS + MainQSS)
self.setWindowTitle("赞助晓游ChR写出更好的 /病毒(划掉)/ 程序.")
self.setObjectName("BeggingWindow")
self.setFixedSize(800, 600)
self.QQLabel = PictureLabel(self)
self.QQLabel.setGeometry(20,40,210,300)
self.WechatLabel = PictureLabel(self)
self.WechatLabel.setGeometry(250,40,210,300)
self.AlipayLabel = PictureLabel(self)
self.AlipayLabel.setGeometry(480,40,210,300)
self.Label = QLabel(self)
self.setObjectName("Label")
self.Label.move(310,15)
self.Label.setText("感谢Thanks♪(・ω・)ノ捐赠!~ 谢谢您!~")
threading.Thread(target=lambda: self.__setPixmap("https://s1.ax1x.com/2022/12/27/zza3Of.png","QQ",self.QQLabel), daemon=True).start() # 设置图片
threading.Thread(target=lambda: self.__setPixmap("https://s1.ax1x.com/2022/12/27/zza16P.png","Wechat",self.WechatLabel), daemon=True).start() # 设置图片
threading.Thread(target=lambda: self.__setPixmap("https://s1.ax1x.com/2022/12/27/zzaGm8.jpg","Alipay",self.AlipayLabel), daemon=True).start() # 设置图片
self.textEdit = QTextEdit(self)
self.textEdit.setObjectName(u"textEdit")
self.textEdit.setGeometry(QRect(20,350,760,230))
self.textEdit.setReadOnly(True)
# response = requests.get("https://obs.cstcloud.cn/share/obs/xiaoyouchr/JuanZengInfomation.txt",headers=headers,proxies=proxies,verify=False)
# response.encoding = "utf-8"
# response = response.text
response = "感谢各位的每一笔捐赠鸭~!\n留下付款备注的话将会把您的大名写入捐赠榜哦!"
self.textEdit.setText(response)
self.show()
self.exec_()
def __setPixmap(self, url:str, name:str, label:QLabel):
global proxies
finished = False
while not finished:
try:
self.icon = requests.get(url, headers=headers, proxies=proxies).content
finished = True
except Exception as err:
print(err)
time.sleep(0.15)
with open(f'temp/{name}-icon', 'wb') as f:
f.write(self.icon)
f.close()
self.icon = QPixmap(f'temp/{name}-icon')
label.setPixmap(self.icon)
class CheckProxyServer:
def __init__(self):
self.__path = r'Software\Microsoft\Windows\CurrentVersion\Internet Settings'
self.__INTERNET_SETTINGS = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER,
self.__path, 0, winreg.KEY_ALL_ACCESS)
def get_server_form_Win(self):
"""获取代理配置的ip和端口号"""
ip, port = "", ""
if self.is_open_proxy_form_Win():
try:
ip, port = winreg.QueryValueEx(self.__INTERNET_SETTINGS, "ProxyServer")[0].split(":")
print("获取到代理信息:{}:{}".format(ip, port))
except FileNotFoundError as err:
print("没有找到代理信息:" + str(err))
except Exception as err:
print("有其他报错:" + str(err))
return f"{ip}:{port}"
else:
print("系统没有开启代理")
return False
def is_open_proxy_form_Win(self):
"""判断是否开启了代理"""
try:
if winreg.QueryValueEx(self.__INTERNET_SETTINGS, "ProxyEnable")[0] == 1:
return True
except FileNotFoundError as err:
print("没有找到代理信息:" + str(err))
except Exception as err:
print("有其他报错:" + str(err))
return False
class DownGroupBox(QGroupBox):
def __init__(self, icon: QPixmap, url: str, filename: str, download_dir: str, blocks_num: int, parent=None):
super().__init__(parent=parent.downWidget)
assert 1 <= blocks_num <= 2048
self.w = self.width()
self.h = self.height()
self.url = url
self.filename = filename
self.download_dir = download_dir
self.cache_dir = f"{self.download_dir}/.cache/"
self.blocks_num = blocks_num
self.__bad_url_flag = False
self.fileSize = self.__get_size()
if self.fileSize == 0:
self.clear()
else:
print(self.fileSize)
self.Paused = False
# setUpGUI
self.setStyleSheet(".QLabel {color: rgb(70, 70, 70);}")
self.imgLable = QLabel(self)
self.imgLable.setScaledContents(True)
self.imgLable.setPixmap(icon)
self.imgLable.setGeometry(QRect(5, 5, 64, 64))
self.progressBar = MyProgressBar(self)
self.progressBar.move(74, 26)
self.progressBar.resize(492, 21)
self.progressBar.setValue(100)
self.openFileBtn = QPushButton(self)
self.openFileBtn.setGeometry(QRect(441, 50, 71, 21))
self.openFileBtn.setProperty("round", True)
self.fileSizeLabel = QLabel(self)
self.fileSizeLabel.setGeometry(QRect(201, 49, 131, 18))
self.fileNameLabel = QLabel(self)
self.fileNameLabel.setGeometry(QRect(75, 5, 389, 18))
self.speedLabel = QLabel(self)
self.speedLabel.setGeometry(QRect(75, 49, 131, 18))
self.timeLabel = QLabel(self)
self.timeLabel.setGeometry(QRect(306, 49, 131, 18))
self.stateLabel = QLabel(self)
self.stateLabel.setGeometry(QRect(74, 25, 492, 21))
self.stateLabel.setStyleSheet("color: rgb(84, 84, 84)")
self.stateLabel.setAlignment(Qt.AlignCenter)
self.pauseBtn = QPushButton(self)
self.pauseBtn.setGeometry(QRect(521, 50, 21, 21))
self.threadNumLabel = QLabel(self)
self.threadNumLabel.setGeometry(QRect(464, 5, 200, 18))
self.JuanZengBtn = QPushButton(self)
self.JuanZengBtn.setGeometry(QRect(360, 5, 46, 21))
self.JuanZengBtn.setObjectName(u"JuanZengBtn")
self.JuanZengBtn.setProperty("round", True)
# Icon
self.pauseIcon = QIcon()
self.pauseIcon.addFile(f"{skinName}/pause", QSize(), QIcon.Normal, QIcon.Off)
self.playIcon = QIcon()
self.playIcon.addFile(f"{skinName}/play", QSize(), QIcon.Normal, QIcon.Off)
self.pauseBtn.setIcon(self.pauseIcon)
self.cancelBtn = QPushButton(self)
self.cancelBtn.setGeometry(QRect(551, 50, 21, 21))
# retranslateUi
self.JuanZengBtn.setText("Beg")
self.openFileBtn.setText("打开目录")
self.stateLabel.setText("正在准备...")
self.cancelBtn.setText("╳")
self.fileNameLabel.setText(self.filename)
self.fileSizeLabel.setText("大小:%s" % self.__get_readable_size(self.fileSize))
self.timeLabel.setText("剩余时间:Check...")
self.threadNumLabel.setText(f"线程数:{self.blocks_num}")
self.speedLabel.setText("速度:Check...")
# 连接函数
self.openFileBtn.clicked.connect(lambda: startfile(self.download_dir))
self.pauseBtn.clicked.connect(self.pause)
self.cancelBtn.clicked.connect(self.cancel)
self.JuanZengBtn.clicked.connect(BeggingWindow)
# CreatingProcess
self.Process = DownloadEngine(url, filename, download_dir, blocks_num, proxies)
self.Process.start()
threading.Thread(target=self.Supervise, daemon=True).start()
def Supervise(self):
"""万恶的督导:监视下载速度、进程数;提出整改意见;"""
REFRESH_INTERVAL = 1 # 每多久输出一次监视状态
LAG_COUNT = 10 # 计算过去多少次测量的平均速度
self.__download_record = []
percentage = 0
while True:
if percentage < 100:
dwn_size = sum([path.getsize(cachefile) for cachefile in self.__get_cache_filenames()])
self.__download_record.append({"timestamp": time.time(), "size": dwn_size})
if len(self.__download_record) > LAG_COUNT:
self.__download_record.pop(0)
s = self.__download_record[-1]["size"] - self.__download_record[0]["size"]
t = self.__download_record[-1]["timestamp"] - self.__download_record[0]["timestamp"]
if not t == 0 and self.Paused == False:
speed = s / t
readable_speed = self.__get_readable_size(speed) # 变成方便阅读的样式
percentage = self.__download_record[-1]["size"] / self.fileSize * 100
status_msg = f"\r[info] {percentage:.1f} % | {readable_speed}/s | {self.blocks_num}"
sys.stdout.write(status_msg)
# 更改界面
self.progressBar.setValue(percentage)
globalSignal.change_text.emit(self.stateLabel,
f"正在下载:{percentage:.1f}% ({self.__get_readable_size(self.__download_record[-1]['size'])})")
globalSignal.change_text.emit(self.speedLabel, f"速度:{readable_speed}/s")
if speed == 0:
globalSignal.change_text.emit(self.timeLabel, "剩余时间:Check...")
else:
globalSignal.change_text.emit(self.timeLabel, f"剩余时间:%s" % timedelta(seconds=
round((self.fileSize -
self.__download_record[
-1][
'size']) / speed)))
globalSignal.change_text.emit(self.threadNumLabel,
f"线程数:{self.blocks_num}")
time.sleep(REFRESH_INTERVAL)
elif percentage == 100:
time.sleep(0.3)
sewed_size = path.getsize(f"{self.download_dir}/{self.filename}")
sew_progress = (sewed_size / self.fileSize) * 100
sys.stdout.write(f"[info] sew_progress {sew_progress} %\n")
globalSignal.change_text.emit(self.stateLabel,
f"正在合并:{sew_progress}% ({self.__get_readable_size(sewed_size)})")
self.progressBar.setValue(sew_progress)
if (self.fileSize - sewed_size) == 0:
globalSignal.change_text.emit(self.stateLabel, "下载完成!")
self.progressBar.setValue(sew_progress)
systemTray.showMessage("Hey--下载完成了!", f"{self.filename} 已完成下载!", logoIcon)
systemTray.messageClicked.connect(lambda: startfile(self.download_dir))
break
else:
self.stop()
self.clear()
systemTray.showMessage("Hey--下载失败了!", f"{self.filename} 已失败下载!", logoIcon)
systemTray.messageClicked.connect(window.show)
globalSignal.change_text.emit(self.stateLabel, "下载完成!")
break
def __get_readable_size(self, size):
units = ["B", "KB", "MB", "GB", "TB", "PB"]
unit_index = 0
K = 1024.0
while size >= K:
size = size / K
unit_index += 1
return "%.2f %s" % (size, units[unit_index])
def __get_size(self):
try:
req = request.urlopen(self.url)
content_length = req.headers["Content-Length"]
req.close()
return int(content_length)
except Exception as err:
self.__bad_url_flag = True
print(f"[Error] {err}")
return 0
def resizeEvent(self, event):
self.w = self.width()
self.h = self.height()
self.progressBar.resize(self.w - 88, 21)
self.stateLabel.resize(self.w - 88, 21)
self.openFileBtn.move(self.w - 123, 49)
self.cancelBtn.move(self.w - 23, 49)
self.pauseBtn.move(self.w - 48, 49)
self.threadNumLabel.move(self.w - 116, 5)
self.JuanZengBtn.move(self.w - 220, 5)
self.speedLabel.move(self.w / 6 - 19, 50)
self.fileSizeLabel.move(self.w / 3 + 14, 50)
self.timeLabel.move(self.w / 2 + 26, 50)
def __get_readable_size(self, size):
units = ["B", "KB", "MB", "GB", "TB", "PB"]
unit_index = 0
K = 1024.0
while size >= K:
size = size / K
unit_index += 1
return "%.2f %s" % (size, units[unit_index])
def stop(self):
self.Process.kill()
def pause(self):
"""接受Pause按钮发出的暂停信号并进行操作"""
if self.Paused == False: # 没暂停就暂停
self.Paused = True
self.pauseBtn.setEnabled(False)
self.cancelBtn.setEnabled(False)
self.pauseBtn.setIcon(self.playIcon)
globalSignal.change_text.emit(self.stateLabel, "正在暂停:正在停止线程...")
self.stop()
self.pauseBtn.setEnabled(True)
self.cancelBtn.setEnabled(True)
globalSignal.change_text.emit(self.stateLabel, "正在暂停...")
elif self.Paused == True: # 暂停了就开始
self.pauseBtn.setEnabled(False)
self.cancelBtn.setEnabled(False)
self.pauseBtn.setIcon(self.pauseIcon)
globalSignal.change_text.emit(self.stateLabel, "正在开始:正在召回线程...")
# 再次召集 worker。不调用 start 的原因是希望他继续卡住主线程。
self.again()
self.pauseBtn.setEnabled(True)
self.cancelBtn.setEnabled(True)
self.Paused = False
def again(self):
self.Process = DownloadEngine(self.url, self.filename, self.download_dir, self.blocks_num, proxiesIP)
self.Process.start()
def cancel(self):
self.pauseBtn.setEnabled(False)
self.cancelBtn.setEnabled(False)
globalSignal.change_text.emit(self.stateLabel, "正在取消任务:正在暂停线程...")
self.Paused = True
self.stop()
globalSignal.change_text.emit(self.stateLabel, "正在取消任务:正在清理缓存...")
moveAction(self, self.w + 35, self.y(), True)
if len(DownGroupBoxesList) == 1:
del DownGroupBoxesList[0]
else:
ID = DownGroupBoxesList.index(self)
del DownGroupBoxesList[ID]
for i in range(len(DownGroupBoxesList)):
moveAction(DownGroupBoxesList[i], DownGroupBoxesList[i].x(), i * 78 + 5)
self.clear()
def clear(self, all_cache=False):
# 清除历史
with open("history.xml", "r", encoding="utf-8") as f:
tmp = f.read()
f.close()
tmp = sub(f"<hst><filename>{self.filename}</filename><downdir>{self.download_dir}</downdir>", "Deleted",
tmp)
print(tmp)
with open("history.xml", "w", encoding="utf-8") as f:
f.write(tmp)
f.close()
delSuccess = False
while not delSuccess:
try:
if all_cache: # TODO 需要交互提醒即将删除的文件夹 [Y]/N 确认。由于不安全,先不打算实现。
pass
else:
for filename in self.__get_cache_filenames():
remove(filename)
delSuccess = True
except PermissionError:
print("删除失败,正在重试!")
delSuccess = False
time.sleep(0.15)
def __get_cache_filenames(self):
return glob(f"{self.cache_dir}{self.filename}.*.gd2")
class NewNetTaskWindow(AcrylicDialog):
def __init__(self, icon, downurl, filename, parent=None):
super().__init__(skinName, parent)
self.icon = icon
self.parent = parent
self.threadNum = threadNum
# QSS
with open(f"{skinName}/GlobalQSS.qss", "r", encoding="utf-8") as f:
GlobalQSS = f.read()
# self.setStyleSheet(_)
f.close()
with open(f"{skinName}/MainQSS.qss", "r", encoding="utf-8") as f:
MainQSS = f.read()
# self.setStyleSheet(_)
f.close()
self.setStyleSheet(GlobalQSS + MainQSS)
print(f"{icon}\n{downurl}\n{filename}")
self.setUp()
# 自定义功能区
# WPSsupport = compile(u"\^\^\^\^\^", IGNORECASE).search(downurl)
# WPSSupport_2 = compile(u"\^\^\^\^\^\$\$\$\$\$", IGNORECASE).search(downurl)
# CSTsupport = compile(u"\$\$\$\$\$", IGNORECASE).search(downurl)
# print(WPSSupport_2)
# print("OD支持")
# self.WPSRadioBtn.setDisabled(True)
# self.CSTRadioBtn.setDisabled(True)
self.ODurl = downurl
self.ODname = filename
self.ODRadioBtn.setChecked(True) # 默认Onedrive
# if CSTsupport:
# print("CST支持")
# self.CSTRadioBtn.setDisabled(False)
# self.ODurl = findall(u"([\S\s]*)\^\^\^\^\^", downurl)[0]
# self.CSTurl = findall(u"\$\$\$\$\$([\S\s]*)", downurl)[0]
# self.ODname = findall(u"([\S\s]*)\^\^\^\^\^", filename)[0]
# self.CSTname = findall(u"\$\$\$\$\$([\S\s]*)", filename)[0]
# if WPSsupport and not WPSSupport_2:
# print("WPS支持")
# self.WPSRadioBtn.setDisabled(False)
# self.WPSurl = findall(u"\^\^\^\^\^([\S\s]*)\$\$\$\$\$", downurl)[0]
# self.WPSurl = findall(u",?([\S\s]*?),", self.WPSurl)
# print(self.WPSurl)
# self.WPSname = findall(u"\^\^\^\^\^([\S\s]*)\$\$\$\$\$", filename)[0]
# self.WPSname = findall(u",?([\S\s]*?),", self.WPSname)
# print(self.WPSname)
# self.WPSRadioBtn.setChecked(True) # 默认WPS
# 连接函数
self.threadNumC.currentIndexChanged.connect(self.changeThreadNum)
self.decidePathBtn.clicked.connect(lambda: decidePathWin(self, self.decidePathEdit, False))
self.startBtn.clicked.connect(self.startDownload)
# 保持运行
self.exec_()
def changeThreadNum(self):
temp = self.threadNum
self.threadNum = int(self.threadNumC.currentText())
print(self.threadNum)
if temp >= 32:
if self.threadNum < 32:
warning = MyQuestionBox(
'警告!',
'你选择的线程过低!很可能会造成下载速度过慢或其他BUG!\n\n你确定要选择小于32个下载线程吗?').Question()
if warning == QMessageBox.No:
self.threadNum = temp
self.threadNumC.setCurrentIndex(self.threadNum - 1)
elif temp <= 256:
if self.threadNum > 256:
counts = 3
warning = MyQuestionBox(
'警告!',
'你选择的线程过高!把您的电脑淦爆!\n\n你确定要选择大于256个下载线程吗?').Question()
while warning == QMessageBox.Yes:
warning = MyQuestionBox(
'警告!',
f'你选择的线程过高!可能会把您的电脑淦爆!\n\n你确定要选择大于256个下载线程吗?({counts})').Question()
if warning == QMessageBox.Yes:
counts -= 1
print(counts)
if counts == 0:
break
if warning == QMessageBox.No:
break
if warning == QMessageBox.No:
self.threadNum = temp
self.threadNumC.setCurrentIndex(self.threadNum - 1)
def setUp(self):
self.setObjectName(u"NewNetTaskWindow")
self.resize(500, 250)
self.setMinimumSize(QSize(500, 250))
self.verticalLayout = QVBoxLayout(self)
self.verticalLayout.setObjectName(u"verticalLayout")
self.verticalLayout.setContentsMargins(10, 26, 10, 10)
self.threadNumG = QGroupBox(self)
self.threadNumG.setObjectName(u"threadNumG")
self.horizontalLayout_2 = QHBoxLayout(self.threadNumG)
self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
self.warningLabel = QLabel(self.threadNumG)
self.warningLabel.setObjectName(u"warningLabel")
self.horizontalLayout_2.addWidget(self.warningLabel)
self.threadNumC = QComboBox(self.threadNumG)
self.threadNumC.setObjectName(u"threadNumC")
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.threadNumC.sizePolicy().hasHeightForWidth())
self.threadNumC.setSizePolicy(sizePolicy)
self.horizontalLayout_2.addWidget(self.threadNumC)
self.verticalLayout.addWidget(self.threadNumG)
self.decidePathG = QGroupBox(self)
self.decidePathG.setObjectName(u"decidePathG")
self.horizontalLayout = QHBoxLayout(self.decidePathG)
self.horizontalLayout.setObjectName(u"horizontalLayout")
self.decidePathEdit = QLineEdit(self.decidePathG)
self.decidePathEdit.setObjectName(u"decidePathEdit")
self.decidePathEdit.setReadOnly(True)
sizePolicy1 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Ignored)
sizePolicy1.setHorizontalStretch(0)
sizePolicy1.setVerticalStretch(0)
sizePolicy1.setHeightForWidth(self.decidePathEdit.sizePolicy().hasHeightForWidth())
self.decidePathEdit.setSizePolicy(sizePolicy1)
self.horizontalLayout.addWidget(self.decidePathEdit)
self.decidePathBtn = QPushButton(self.decidePathG)
self.decidePathBtn.setObjectName(u"decidePathBtn")
self.decidePathBtn.setProperty("round", True)
sizePolicy2 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Ignored)
sizePolicy2.setHorizontalStretch(0)
sizePolicy2.setVerticalStretch(0)
sizePolicy2.setHeightForWidth(self.decidePathBtn.sizePolicy().hasHeightForWidth())
self.decidePathBtn.setSizePolicy(sizePolicy2)
self.horizontalLayout.addWidget(self.decidePathBtn)
self.verticalLayout.addWidget(self.decidePathG)
self.decideSourceG = QGroupBox(self)
self.decideSourceG.setObjectName(u"decideSourceG")
self.horizontalLayout_3 = QHBoxLayout(self.decideSourceG)
self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")
# self.WPSRadioBtn = QRadioButton(self.decideSourceG)
# self.WPSRadioBtn.setObjectName(u"WPSRadioBtn")
# sizePolicy2.setHeightForWidth(self.WPSRadioBtn.sizePolicy().hasHeightForWidth())
# self.WPSRadioBtn.setSizePolicy(sizePolicy2)
#
# self.horizontalLayout_3.addWidget(self.WPSRadioBtn)
self.ODRadioBtn = QRadioButton(self.decideSourceG)
self.ODRadioBtn.setObjectName(u"ODRadioBtn")
sizePolicy2.setHeightForWidth(self.ODRadioBtn.sizePolicy().hasHeightForWidth())
self.ODRadioBtn.setSizePolicy(sizePolicy2)
self.horizontalLayout_3.addWidget(self.ODRadioBtn)
# self.CSTRadioBtn = QRadioButton(self.decideSourceG)
# self.CSTRadioBtn.setObjectName(u"CSTRadioBtn")
# sizePolicy2.setHeightForWidth(self.CSTRadioBtn.sizePolicy().hasHeightForWidth())
# self.CSTRadioBtn.setSizePolicy(sizePolicy2)
#
# self.horizontalLayout_3.addWidget(self.CSTRadioBtn)
self.ODRadioBtn.raise_()
# self.WPSRadioBtn.raise_()
# self.CSTRadioBtn.raise_()
self.verticalLayout.addWidget(self.decideSourceG)
self.startBtn = QPushButton(self)
self.startBtn.setObjectName(u"startBtn")
self.startBtn.setProperty("round", True)
sizePolicy3 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
sizePolicy3.setHorizontalStretch(0)
sizePolicy3.setVerticalStretch(0)
sizePolicy3.setHeightForWidth(self.startBtn.sizePolicy().hasHeightForWidth())
self.startBtn.setSizePolicy(sizePolicy3)
self.verticalLayout.addWidget(self.startBtn)
# 设置文本
self.setWindowTitle(u"\u65b0\u5efa\u4e0b\u8f7d\u4efb\u52a1")
self.threadNumG.setTitle(u"\u786e\u5b9a\u60a8\u7684\u4e0b\u8f7d\u7ebf\u7a0b\u6570")
self.threadNumC.addItems([str(i + 1) for i in range(2048)])
self.threadNumC.setCurrentIndex(threadNum - 1)
self.warningLabel.setText(
u"\u8bf7\u52ff\u8bbe\u7f6e\u8fc7\u9ad8\u7684\u4e0b\u8f7d\u7ebf\u7a0b,\u56e0\u4e3a\u8fd9\u53ef\u80fd\u9020\u6210\u7535\u8111\u5361\u987f\u548c\u4e0b\u8f7d\u5931\u8d25!")
self.decidePathG.setTitle(u"\u786e\u5b9a\u60a8\u7684\u4e0b\u8f7d\u8def\u5f84")
self.decidePathEdit.setText(defaultPath)
self.decidePathBtn.setText(u"\u9009\u62e9\u8def\u5f84")
self.decideSourceG.setTitle(u"\u9009\u62e9\u60a8\u7684\u4e0b\u8f7d\u6e90!")
# self.WPSRadioBtn.setText(u"金山云(移动电信)")
self.ODRadioBtn.setText(u"OneDrive (因资金原因暂时停用其他下载方式)")
# self.CSTRadioBtn.setText(u"科技网(三网优化)")
self.startBtn.setText(u"\u5f00\u59cb\u4e0b\u8f7d")
# def getWPSDownloadLink(self):
# DownloadLink = [] # 生成空列表
# session = requests.Session()
# session.headers.update(headers)
# for i in self.WPSurl:
# session.get("https://www.kdocs.cn/view/l/ssazQO5dfN4s")
# response = session.get(url=i, allow_redirects=False).text
# URL = findall(r"\"url\":\"([\S\s]*)\",\"sha1", response)
# URL = URL[0].encode("utf-8").decode("unicode_escape")
# print(URL)
# DownloadLink.append(URL)
# return DownloadLink
def startDownload(self):
print(self.threadNum)
print(self.decidePathEdit.text())
# if self.WPSRadioBtn.isChecked() == True: # WPS
# DownloadLink = self.getWPSDownloadLink()
# for i in range(len(DownloadLink)):
# newDownloadTask(self.icon, DownloadLink[i], self.WPSname[i], self.decidePathEdit.text(), self.threadNum,
# window)
# elif self.ODRadioBtn.isChecked() == True: # OD
newDownloadTask(self.icon, self.ODurl, self.ODname, self.decidePathEdit.text(), self.threadNum, window)
# elif self.CSTRadioBtn.isChecked() == True: # CST
# newDownloadTask(self.icon, self.CSTurl, self.CSTname, self.decidePathEdit.text(), self.threadNum, window)
self.close()
class NewTaskWindow(AcrylicWindow):
def __init__(self, parent=None):
super().__init__(parent=parent, skinName=skinName)
self.titleBar.maxBtn.setEnabled(True)
self.setObjectName("NewTaskWindow")
self.resize(400, 400)
self.setMinimumSize(QSize(360, 292))
# QSS
with open(f"{skinName}/GlobalQSS.qss", "r", encoding="utf-8") as f:
GlobalQSS = f.read()
# self.setStyleSheet(_)
f.close()
with open(f"{skinName}/MainQSS.qss", "r", encoding="utf-8") as f:
MainQSS = f.read()
# self.setStyleSheet(_)
f.close()
self.setStyleSheet(GlobalQSS + MainQSS)
# logo
self.logoPixmap = QPixmap(f"{skinName}/logo.png")
self.verticalLayout = QVBoxLayout(self)
self.verticalLayout.setObjectName(u"verticalLayout")
self.verticalLayout.setSpacing(6)
self.verticalLayout.setContentsMargins(6, 30, 6, 6)
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.horizontalLayout.setSpacing(3)
self.urlEdit = QPlainTextEdit(self)
self.urlEdit.setObjectName("urlEdit")
self.horizontalLayout.addWidget(self.urlEdit)
self.addTableButton = QPushButton(self)
self.addTableButton.setObjectName("addTableButton")
self.addTableButton.setProperty("round", True)
sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.addTableButton.sizePolicy().hasHeightForWidth())
self.addTableButton.setSizePolicy(sizePolicy)
self.horizontalLayout.addWidget(self.addTableButton)
self.verticalLayout.addLayout(self.horizontalLayout)
self.infoTableWidget = QTableWidget(self)
self.infoTableWidget.setObjectName("infoTableWidget")
self.infoTableWidget.setColumnCount(3)
__qtablewidgetitem = QTableWidgetItem()
self.infoTableWidget.setHorizontalHeaderItem(0, __qtablewidgetitem)
__qtablewidgetitem1 = QTableWidgetItem()
self.infoTableWidget.setHorizontalHeaderItem(1, __qtablewidgetitem1)
__qtablewidgetitem2 = QTableWidgetItem()
self.infoTableWidget.setHorizontalHeaderItem(2, __qtablewidgetitem2)
self.infoTableWidget.setColumnWidth(0, 225)
self.infoTableWidget.setColumnWidth(1, 50)
self.infoTableWidget.setColumnWidth(2, 90)
self.verticalLayout.addWidget(self.infoTableWidget)
self.allSizeLabel = QLabel(self)
self.verticalLayout.addWidget(self.allSizeLabel)
self.horizontalLayout_2 = QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.pathEdit = QLineEdit(self)
self.pathEdit.setObjectName("pathEdit")
self.horizontalLayout_2.addWidget(self.pathEdit)
self.decidePathBtn = QPushButton(self)
self.decidePathBtn.setObjectName("decidePathBtn")
self.decidePathBtn.setProperty("round", True)
self.horizontalLayout_2.addWidget(self.decidePathBtn)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.addTaskBtn = QPushButton(self)
self.addTaskBtn.setObjectName("addTaskBtn")
self.addTaskBtn.setProperty("round", True)
self.verticalLayout.addWidget(self.addTaskBtn)
self.verticalLayout.setStretch(0, 2)
self.verticalLayout.setStretch(1, 6)
self.addTaskBtn.setEnabled(False)
# retranslateUi
self.setWindowTitle(u"\u65b0\u5efa\u4e0b\u8f7d\u4efb\u52a1")
self.urlEdit.setPlaceholderText(
u"\u5728\u8fd9\u91cc\u952e\u5165\u4e0b\u8f7d\u8fde\u63a5 (\u5982\u9700\u52a0\u5165\u591a\u4e2a,\u8bf7\u7528\u6362\u884c\u7b26\u5206\u9694)")
self.addTableButton.setText(u"\u6dfb\u52a0")
___qtablewidgetitem = self.infoTableWidget.horizontalHeaderItem(0)
___qtablewidgetitem.setText(u"\u6587\u4ef6\u540d")
___qtablewidgetitem1 = self.infoTableWidget.horizontalHeaderItem(1)
___qtablewidgetitem1.setText(u"\u7c7b\u578b")
___qtablewidgetitem2 = self.infoTableWidget.horizontalHeaderItem(2)
___qtablewidgetitem2.setText(u"\u5927\u5c0f")
__sortingEnabled = self.infoTableWidget.isSortingEnabled()
self.infoTableWidget.setSortingEnabled(False)
self.infoTableWidget.setSortingEnabled(__sortingEnabled)
self.pathEdit.setPlaceholderText(u"\u5728\u6b64\u952e\u5165\u4e0b\u8f7d\u8def\u5f84.")
self.decidePathBtn.setText(u"\u9009\u62e9\u8def\u5f84")
self.addTaskBtn.setText(u"\u4e0b\u8f7d")
self.pathEdit.setText(defaultPath)
self.pathEdit.setEnabled(False)
# 连接函数
self.addTableButton.clicked.connect(self.addTabel)
self.decidePathBtn.clicked.connect(lambda: decidePathWin(self, self.pathEdit))
self.addTaskBtn.clicked.connect(self.addTask)
self.show()
def addTabel(self):
self.addTableButton.setEnabled(False)
self.addTaskBtn.setEnabled(False)
self.addTableButton.setText("正在\n添加")
# 清空QTableWidget & 二维列表
self.tableList = []
self.infoTableWidget.setColumnCount(3)
self.infoTableWidget.setRowCount(0)
self.allSizeLabel.setText("")
self.url = self.urlEdit.toPlainText()
self.url = self.url.split('\n')
print(self.url)
def analysis():
allSize = 0
for i in range(len(self.url)):
_ = urlRe.search(self.url[i])
if _:
print("进入getinfo")
info = self.getFileInfo(self.url[i])
print(info)
if info == 0:
continue
else:
# 增加数据
self.infoTableWidget.setRowCount(self.infoTableWidget.rowCount() + 1)
self.tableList.append([0, 0, 0, 0])
# 文件名
self.tableList[i][1] = QTableWidgetItem()
self.infoTableWidget.setItem(i, 0, self.tableList[i][1])