forked from fandesfyf/JamTools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clientFilesTransmittertest.py
1639 lines (1484 loc) · 69.5 KB
/
clientFilesTransmittertest.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
import json
import os
import random
import socket
import sys
import time
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QStandardPaths, QSettings, QObject
from PyQt5.QtGui import QIcon
from PyQt5.QtNetwork import QNetworkInterface
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QLineEdit, \
QMessageBox, QFileDialog, QGroupBox, QCheckBox, QSpinBox, QScrollArea, QWidget, QProgressBar
import jamresourse
from jampublic import Commen_Thread
def getdirsize(dir):
size = 0
for root, dirs, files in os.walk(dir):
size += sum([os.path.getsize(os.path.join(root, name)) for name in files])
return size
def create_all_dirs(pathinfo, rootpath='.'):
try:
if not os.path.exists(rootpath):
os.mkdir(rootpath)
for info in pathinfo:
d = os.path.join(rootpath, os.path.split(info)[0])
if not os.path.exists(d):
os.makedirs(d)
except:
print(sys.exc_info(), 33)
print("已创建完文件夹!")
def fomatpath(p):
while p[0] == "/" or p[0] == "\\":
p = p[1:]
return p
def get_directory_info(rootpath):
infos = tuple(os.walk(rootpath))
# print(infos)
filesizedict = {}
fileslist = []
rootpathname = os.path.split(infos[0][0])[0]
for d0 in infos:
for name in d0[2]:
fp = os.path.join(d0[0], name)
fileslist.append(fp)
filesizedict[fomatpath(fp.replace(rootpathname, ''))] = os.path.getsize(fp)
size = sum(filesizedict.values())
# returninfo = filesizedict.keys()
# returninfo = [(fomatpath(i.replace(rootpathname, '')), j, k) for i, j, k in infos] # 发送出去的文件名列表
# fileslist = [os.path.join(d0[0], name) for d0 in infos for name in d0[2]] # 在本地遍历的文件名列表
# size = sum([os.path.getsize(name) for name in fileslist])
return fileslist, size, filesizedict
def get_ips(): # 获取ip
dv = QNetworkInterface.allInterfaces()
ips = [interface.addressEntries()[-1].ip().toString() for interface
in dv if
(len(interface.addressEntries()) and not interface.addressEntries()[
-1].ip().isLinkLocal() and interface.addressEntries()[
-1].ip().toString() != "127.0.0.1")]
print("all ips", ips)
return ips
# 128-191是b类
def get_Network_segments(ips):
segment = []
end = []
for ip in ips:
if 128 < int(ip[:3]) < 191:
segment.append("".join([ip.split('.')[0], "."]))
end.append("".join([ip.split('.')[-3], ".", ip.split('.')[-2], ".", ip.split('.')[-1]]))
else:
segment.append("".join(str(s) + "." for s in ip.split('.')[:-1]))
end.append("".join(ip.split('.')[-1:]))
print(segment, end)
return segment, end
# def get_all_networks_nameandip():
# """ 多网卡 mac 和 ip 信息 """
# dic = psutil.net_if_addrs()
# print(dic)
# networks = {}
# for adapter in dic:
# snicList = dic[adapter]
# ipv4 = '无 ipv4 地址'
# for snic in snicList:
# if snic.family.name == 'AF_INET':
# ipv4 = snic.address
# networks[adapter] = ipv4
# print(networks)
# return networks
class ClientFilesTransmitterGroupbox(QGroupBox):
showm_signal = pyqtSignal(str)
def __init__(self, text="", parent=None):
super(ClientFilesTransmitterGroupbox, self).__init__(title=text, parent=parent)
self.Transmitter = ClientFilesTransmitter(self)
# self.setAcceptDrops(True)
self.resize(560, 220)
self.allowCheckBox = QCheckBox("允许连接", self)
self.allowCheckBox.setToolTip("只有当该框勾选时才允许新的连接")
self.allowCheckBox.setGeometry(10, 18, 80, 25)
self.allowCheckBox.stateChanged.connect(self.allowconnectchange)
self.allowCheckBox.setChecked(
QSettings('Fandes', 'jamtools').value("clientfilestransmittertest/allowconnect", True, type=bool))
self.needallowconnection = QCheckBox("需要确认", self)
self.needallowconnection.setToolTip("不勾选则,自动确认所有连接请求")
self.needallowconnection.setGeometry(self.allowCheckBox.x() + self.allowCheckBox.width() + 12,
self.allowCheckBox.y(),
self.allowCheckBox.width() + 10, self.allowCheckBox.height())
self.needallowconnection.setChecked(
QSettings('Fandes', 'jamtools').value("clientfilestransmittertest/needallow", True, type=bool))
self.needallowconnection.stateChanged.connect(self.autoAllowchange)
self.disconnectallbtn = QPushButton("关闭所有连接", self)
self.disconnectallbtn.setToolTip("关闭所有连接,并禁止新的连接,需重新勾选允许连接才可用")
self.disconnectallbtn.move(self.allowCheckBox.x(),
self.allowCheckBox.height() + self.allowCheckBox.y() + 5)
self.disconnectallbtn.clicked.connect(self.killallconnection)
self.connectionstredit = QLineEdit(self.Transmitter.connectstr, self)
self.connectionstredit.setReadOnly(True)
self.connectionstredit.setToolTip("连接码")
self.connectionstredit.setGeometry(self.disconnectallbtn.x(),
self.disconnectallbtn.height() + self.disconnectallbtn.y() + 10, 70, 22)
self.connectionstrupdate = QPushButton(QIcon(":/update.png"), "", self)
self.connectionstrupdate.setGeometry(self.connectionstredit.x() + self.connectionstredit.width() + 3,
self.connectionstredit.y(), 22, 22)
self.connectionstrupdate.clicked.connect(self.Transmitter.update_connectionstr)
self.connectionstrupdate.setToolTip("更新连接码")
self.connectionstrupdate.setStatusTip("更新连接码")
copyconnectionstrbtn = QPushButton("复制连接码", self)
copyconnectionstrbtn.setGeometry(self.connectionstrupdate.x() + self.connectionstrupdate.width() + 3,
self.connectionstrupdate.y(), 90, 22)
copyconnectionstrbtn.clicked.connect(self.copyconnectionstr)
self.targetconnectionedit = QLineEdit(self)
self.targetconnectionedit.setPlaceholderText("连接码")
self.targetconnectionedit.setGeometry(self.connectionstredit.x(), copyconnectionstrbtn.y() + 28,
self.connectionstredit.width(), self.connectionstredit.height())
findserverbtn = QPushButton("连接", self)
findserverbtn.setGeometry(self.targetconnectionedit.x() + self.targetconnectionedit.width() + 5,
self.targetconnectionedit.y(), 50, 22)
findserverbtn.clicked.connect(lambda: self.Transmitter.findandconnectserver(self.targetconnectionedit.text()))
findserverbtn.setToolTip("输入连接码以连接")
connection_ScrollArea = QScrollArea(self)
connection_ScrollArea.setGeometry(200, 8, self.width() - 210, self.height() - 10)
self.connection_ScrollArea_widget = QWidget()
self.connection_ScrollArea_widget.setGeometry(connection_ScrollArea.geometry())
connection_ScrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
connection_ScrollArea.setWidget(self.connection_ScrollArea_widget)
self.labeltest = QLabel("当前无连接,\n请输入连接码创建连接", self.connection_ScrollArea_widget)
self.labeltest.setGeometry(10, 30, 120, 50)
self.setStyleSheet("QScrollBar{width: 5px;}")
self.connectionwidgetslist = []
self.autoallow = not self.needallowconnection.isChecked()
self.connectall()
def copyconnectionstr(self):
clipboard = QApplication.clipboard()
clipboard.setText(self.Transmitter.connectstr)
def connectall(self):
self.Transmitter.aconnectionsignal.connect(self.aconnectionsignalhandle)
self.Transmitter.reconnectionsignal.connect(self.reconnectionhandle)
self.Transmitter.foundserverMSGsignal.connect(self.foundserverMSGsignalhandle)
self.Transmitter.update_connectionstrchangesignal.connect(self.connectionstredit.setText)
self.Transmitter.show_warningsignal.connect(self.show_a_message)
self.Transmitter.showm_signal.connect(self.showm_signal.emit)
def foundserverMSGsignalhandle(self, foundresult: str):
if foundresult == "notfound":
QMessageBox.warning(self, "notfound!", "没有找到对方的设备,请检测对方是否允许连接、核对连接码并确保你们的设备处于同一网段!", QMessageBox.Yes)
elif foundresult == "outofdate":
QMessageBox.warning(self, "out of date!", "你的连接码已经过期了,请获取最新的连接码!", QMessageBox.Yes)
else:
infoBox = QMessageBox()
infoBox.setIcon(QMessageBox.Information)
infoBox.setText("{}在线\n正在等待对方确认连接...".format(foundresult))
infoBox.setStandardButtons(QMessageBox.Ok)
infoBox.button(QMessageBox.Ok).animateClick(3000) # 3秒自动关闭
infoBox.exec_()
# self.add_a_connection_widget(foundresult)
def reconnectionhandle(self, client_socket: socket.socket, client_address, fail=False):
if fail:
self.reconnectFail(client_address)
return
self.create_a_connection(client_socket, client_address)
self.showm_signal.emit("{}已连接!".format(client_address))
self.show_a_message("{}已连接!".format(client_address))
def aconnectionsignalhandle(self, client_socket: socket.socket, client_address, connectport):
if self.autoallow:
client_socket.send("allow".encode())
self.create_a_connection(client_socket, client_address, connectport)
self.showm_signal.emit("{}已连接!".format(client_address))
self.show_a_message("{}已连接!".format(client_address))
return
self.activateWindow()
result = QMessageBox.warning(self, "允许连接?", "收到来自{}的一个连接请求\n是否允许连接?".format(client_address),
QMessageBox.Yes | QMessageBox.No,
QMessageBox.Yes)
if result == QMessageBox.Yes:
client_socket.send("allow".encode())
self.create_a_connection(client_socket, client_address, connectport)
else:
client_socket.send("refuse".encode())
client_socket.close()
def show_a_message(self, message, delay=3000):
self.activateWindow()
infoBox = QMessageBox(self)
infoBox.setIcon(QMessageBox.Information)
infoBox.setText(message)
infoBox.setStandardButtons(QMessageBox.Ok)
infoBox.button(QMessageBox.Ok).animateClick(delay) # 3秒自动关闭
infoBox.exec_()
def create_a_connection(self, client_socket, client_address, connectport=0):
for aconnectionbox in self.connectionwidgetslist:
if aconnectionbox.ip == client_address:
aconnectionbox.update_state("已重新连接")
print("再次连接")
break
else:
self.labeltest.hide()
if connectport:
self.Transmitter.targetdict[client_address] = connectport
aconnectionbox = ClientConnectionbox(client_address, self.connection_ScrollArea_widget)
aconnectionbox.move(5, 10 + (aconnectionbox.height() + 5) * len(self.connectionwidgetslist))
aconnectionbox.show()
th = ClientListenThread(client_socket, self.Transmitter, client_address)
aconnectionbox.sendfilessignal.connect(th.sendfiles)
aconnectionbox.senddirssignal.connect(th.senddirs)
aconnectionbox.resetsignal.connect(self.reset)
aconnectionbox.rootpathchangesignal.connect(th.rootpathchange)
aconnectionbox.threadnum.valueChanged.connect(th.changethreadnum)
aconnectionbox.pausebtn.clicked.connect(th.pause)
aconnectionbox.cannelbtn.clicked.connect(th.cancel)
th.resetsignal.connect(self.beReset)
th.showm_signal.connect(self.showm_signal.emit)
th.update_state_signal.connect(aconnectionbox.update_state)
th.pausebtntext_signal.connect(aconnectionbox.pausebtn.setText)
th.reconnectsignal.connect(self.reconnectionhandle)
th.start()
self.connectionwidgetslist.append(aconnectionbox)
self.connection_ScrollArea_widget.resize(self.connection_ScrollArea_widget.width(),
20 + (aconnectionbox.height() + 5) * len(self.connectionwidgetslist))
self.Transmitter.clientthreads.append(th)
self.Transmitter.connectionips.add(client_address)
self.Transmitter.allowip.add(client_address)
print(client_address, "已连接")
# self.Transmitter.create_a_connection(client_socket, client_address)
def reset(self, ip):
for th in self.Transmitter.clientthreads:
if th.ip == ip:
th.quit()
try:
th.sendthreadmanager.quit()
except:
print(sys.exc_info())
self.Transmitter.clientthreads.remove(th)
break
try:
self.Transmitter.connectionips.remove(ip)
self.Transmitter.allowip.remove(ip)
except:
pass
self.showm_signal.emit("你移除了与{}的连接".format(ip))
print("已主动移除")
def beReset(self, ip):
print("bereset 444444444444")
for th in self.Transmitter.clientthreads:
if th.ip == ip:
self.reconnectthrea = Commen_Thread(th.reconnect)
self.reconnectthrea.start()
break
def reconnectFail(self, ip):
for th in self.Transmitter.clientthreads:
if th.ip == ip:
try:
self.Transmitter.clientthreads.remove(th)
except:
print(sys.exc_info(), 295)
print("已被移除")
for wid in self.connectionwidgetslist:
if wid.ip == ip:
wid.resetwidget()
self.showm_signal.emit("{}移除了你的一个连接".format(ip))
print(ip, self.Transmitter.connectionips)
try:
self.Transmitter.connectionips.remove(ip)
except:
print(sys.exc_info(), 284)
def autoAllowchange(self, e):
if e:
QSettings('Fandes', 'jamtools').setValue("clientfilestransmittertest/needallow", True)
self.autoallow = False
else:
QSettings('Fandes', 'jamtools').setValue("clientfilestransmittertest/needallow", False)
self.autoallow = True
def allowconnectchange(self, e):
if e:
QSettings('Fandes', 'jamtools').setValue("clientfilestransmittertest/allowconnect", True)
self.Transmitter.canconnect = True
self.Transmitter.start()
else:
QSettings('Fandes', 'jamtools').setValue("clientfilestransmittertest/allowconnect", False)
self.Transmitter.canconnect = False
def killallconnection(self):
if self.Transmitter.closeall():
return
for wid in self.connectionwidgetslist:
wid.resetwidget()
self.allowCheckBox.setChecked(False)
self.Transmitter.connectionips = set()
self.Transmitter.allowip = set()
class ClientConnectionbox(QGroupBox):
sendfilessignal = pyqtSignal(list)
senddirssignal = pyqtSignal(str)
resetsignal = pyqtSignal(str)
rootpathchangesignal = pyqtSignal(str)
def __init__(self, ip, parent: QWidget):
super(ClientConnectionbox, self).__init__("连接:{}".format(ip), parent)
self.ip = ip
self.parent = parent
self.resize(self.parent.width() - 10, 175)
self.setAcceptDrops(True)
self.disconnectbtn = QPushButton("断开", self)
self.disconnectbtn.setGeometry(5, 18, 40, 25)
self.disconnectbtn.clicked.connect(self.reset)
self.signallight = QPushButton("", self)
self.signallight.setStyleSheet("background-color:rgb(20,239,20);border:2px solid black;border-radius:6px;")
self.signallight.setGeometry(self.disconnectbtn.x() + self.disconnectbtn.width() + 18,
self.disconnectbtn.y() + 5, 12, 12)
self.sendfilesbtn = QPushButton("发送文件", self)
self.sendfilesbtn.setGeometry(5, self.disconnectbtn.y() + self.disconnectbtn.height(), 80, 25)
self.sendfilesbtn.clicked.connect(self.sendfiles)
self.senddirbtn = QPushButton("发送文件夹", self)
self.senddirbtn.setGeometry(self.sendfilesbtn.x() + self.sendfilesbtn.width() + 5, self.sendfilesbtn.y(),
self.sendfilesbtn.width(), self.sendfilesbtn.height())
self.senddirbtn.clicked.connect(self.senddirs)
self.threadnum = QSpinBox(self)
self.threadnum.setPrefix("线程数:")
self.threadnum.setValue(4)
self.threadnum.setMinimum(1)
self.threadnum.setMaximum(64)
self.threadnum.setGeometry(self.senddirbtn.x() + self.senddirbtn.width() + 5, self.senddirbtn.y(), 100,
self.senddirbtn.height())
self.rootpathshowedit = QLineEdit("接收路径:下载/jamreceive", self)
self.rootpathshowedit.setReadOnly(True)
self.rootpathshowedit.setGeometry(5, self.sendfilesbtn.y() + self.sendfilesbtn.height() + 8, 220, 20)
self.rootpathchangebtn = QPushButton("…", self)
# self.rootpathchangebtn.setStyleSheet('border-image: url(:/choice_path.png);')
self.rootpathchangebtn.setGeometry(self.rootpathshowedit.x() + self.rootpathshowedit.width() + 5,
self.rootpathshowedit.y(),
20, 20)
self.rootpathchangebtn.clicked.connect(self.rootpathchange)
self.rootpathchangebtn.setToolTip("改变接收路径")
self.conditionlabel = QLabel("状态:已就绪", self)
self.conditionlabel.move(5, self.rootpathshowedit.y() + self.rootpathshowedit.height() + 5)
self.conditionlabel.resize(self.width() - self.conditionlabel.x(), 55)
self.pbar = QProgressBar(self)
self.pbar.setMaximum(100)
self.pbar.setGeometry(5, 153, self.width() - 10, 18)
self.setStyleSheet("QPushButton{color:black;background-color:rgb(239,239,239);padding:1px 4px;}"
"QPushButton:hover{color:green;background-color:rgb(200,200,100);}")
self.pausebtn = QPushButton("暂停", self)
self.cannelbtn = QPushButton("取消", self)
self.pausebtn.setGeometry(self.width() - 40, self.conditionlabel.y(), 40, 25)
self.cannelbtn.setGeometry(self.pausebtn.x(), self.pausebtn.y() + self.pausebtn.height(),
self.pausebtn.width(), self.pausebtn.height())
self.cannelbtn.hide()
self.pausebtn.hide()
def update_state(self, state: str):
# print("update state", state)
self.conditionlabel.setText("状态:{}".format(state))
if "发送中" in state or "暂停" in state or "接收中" in state:
if self.pausebtn.isHidden():
self.pausebtn.setVisible(True)
self.cannelbtn.setVisible(True)
else:
if self.cannelbtn.isVisible():
self.pausebtn.hide()
self.cannelbtn.hide()
if "进度:" in state:
s = int(eval(state.split("进度:")[-1].split(" ")[0].replace("%", "")))
self.pbar.setValue(s)
if "成功" in state:
self.setalldisable(False)
self.signallight.setStyleSheet("background-color:rgb(20,239,20);border:2px solid black;border-radius:6px;")
self.pbar.setValue(100)
elif "重新连接" in state or "取消" in state:
self.setalldisable(False)
self.signallight.setStyleSheet("background-color:rgb(20,239,20);border:2px solid black;border-radius:6px;")
self.pbar.setValue(0)
self.disconnectbtn.setEnabled(True)
self.pbar.setStyleSheet("")
self.setStyleSheet(
"QPushButton{color:black;background-color:rgb(239,239,239);padding:1px 4px;}"
"QPushButton:hover{color:green;background-color:rgb(200,200,100);}")
elif "断开" in state or "掉线" in state:
self.pbar.setDisabled(True)
self.pbar.setValue(0)
self.resetwidget()
# self.signallight.setStyleSheet(
# "background-color:rgb(160,160,160);border:2px solid black;border-radius:6px;")
# self.setalldisable(True)
# self.disconnectbtn.setDisabled(True)
if "掉线" in state:
print("对方掉线已重置")
self.reset()
QApplication.processEvents()
else:
self.setalldisable(True)
self.signallight.setStyleSheet("background-color:rgb(239,239,50);border:2px solid black;border-radius:6px;")
# self.disconnectbtn.setStyleSheet("QPushButton{color:black;background-color:rgb(239,239,239);padding:1px 4px;}"
# "QPushButton:hover{color:green;background-color:rgb(200,200,100);}")
QApplication.processEvents()
def rootpathchange(self):
dir = QFileDialog.getExistingDirectory(self, "选择接收文件的根目录", QStandardPaths.writableLocation(
QStandardPaths.DownloadLocation))
if dir:
print(dir, "changedir")
self.rootpathshowedit.setText("接收路径:{}".format(dir))
self.rootpathchangesignal.emit(dir)
def resetwidget(self):
self.signallight.setStyleSheet("background-color:rgb(160,160,160);border:2px solid black;border-radius:6px;")
self.conditionlabel.setText("状态:已断开!")
self.pbar.setStyleSheet("""QProgressBar::chunk {
background-color: gray;
}""")
# self.sendfilesbtn.disconnect()
# self.senddirbtn.disconnect()
# self.disconnectbtn.disconnect()
self.setAcceptDrops(False)
self.setalldisable(True)
self.disconnectbtn.setDisabled(True)
self.setStyleSheet("QPushButton{color:rgb(120,120,120);background-color:rgb(200,200,200);}")
def setalldisable(self, d: bool):
if d:
# print("set disable")
self.sendfilesbtn.setStyleSheet("QPushButton{color:rgb(120,120,120);background-color:rgb(200,200,200);}")
self.senddirbtn.setStyleSheet("QPushButton{color:rgb(120,120,120);background-color:rgb(200,200,200);}")
self.rootpathchangebtn.setStyleSheet(
"QPushButton{color:rgb(120,120,120);background-color:rgb(200,200,200);}")
else:
# print("set not disable")
self.sendfilesbtn.setStyleSheet(
"QPushButton{color:black;background-color:rgb(239,239,239);padding:1px 4px;}"
"QPushButton:hover{color:green;background-color:rgb(200,200,100);}")
self.senddirbtn.setStyleSheet(
"QPushButton{color:black;background-color:rgb(239,239,239);padding:1px 4px;}"
"QPushButton:hover{color:green;background-color:rgb(200,200,100);}")
self.rootpathchangebtn.setStyleSheet(
"QPushButton{color:black;background-color:rgb(239,239,239);padding:1px 4px;}"
"QPushButton:hover{color:green;background-color:rgb(200,200,100);}")
self.sendfilesbtn.setDisabled(d)
self.senddirbtn.setDisabled(d)
self.rootpathchangebtn.setDisabled(d)
self.threadnum.setDisabled(d)
def reset(self):
self.resetwidget()
self.resetsignal.emit(self.ip)
def sendfiles(self):
files, l = QFileDialog.getOpenFileNames(self, "选择要发送的文件", "", "all files(*.*);;")
print(files)
if len(files):
self.sendfilessignal.emit(files)
def senddirs(self):
dir = QFileDialog.getExistingDirectory(self, "选择要发送的文件夹", "")
print(dir)
if len(dir):
self.senddirssignal.emit(dir)
def dragEnterEvent(self, e):
print("box", e.mimeData().urls())
e.acceptProposedAction()
def dropEvent(self, e):
print("boxdrop", e.mimeData().urls())
data = []
for i in range(len(e.mimeData().urls())):
data.append(e.mimeData().urls()[i].toLocalFile())
filelist = []
dirlist = []
for path in data:
if os.path.isfile(path):
filelist.append(path)
else:
dirlist.append(path)
if len(filelist):
self.sendfilessignal.emit(filelist)
else:
for d in dirlist:
if os.path.isdir(d):
self.senddirssignal.emit(d)
break
class ClientFilesTransmitter(QThread): # 客户端传输主要线程
aconnectionsignal = pyqtSignal(socket.socket, str, int)
reconnectionsignal = pyqtSignal(socket.socket, str)
foundserverMSGsignal = pyqtSignal(str)
update_connectionstrchangesignal = pyqtSignal(str)
show_warningsignal = pyqtSignal(str)
showm_signal = pyqtSignal(str)
def __init__(self, parent: ClientFilesTransmitterGroupbox):
super(ClientFilesTransmitter, self).__init__()
self.parent = parent
self.host = ""
self.allowports = [2110, 5124, 2589, 3645, 8457] # , 5124, 2589, 3645, 8457
self.portids = "zxcvb"
self.port = self.allowports[random.randint(0, len(self.allowports) - 1)]
print("端口", self.port, self.portids[self.allowports.index(self.port)])
self.ips = get_ips()
if len(self.ips) == 0:
self.show_warningsignal.emit("你的设备没有可用的网卡")
self.showm_signal.emit("未接入网络!请接入网络(局域网)后使用!")
self.targetdict = {}
self.clientthreads = []
self.connectionips = set()
self.allowip = set()
self.segments, self.endsegs = get_Network_segments(self.ips)
self.canconnect = False
self.targetendsegs = self.endsegs
self.targetport = self.port
if not os.path.exists(
os.path.join(QStandardPaths.writableLocation(QStandardPaths.DownloadLocation), "jamreceive")):
os.mkdir(os.path.join(QStandardPaths.writableLocation(QStandardPaths.DownloadLocation), "jamreceive"))
self.rootpath = os.path.join(QStandardPaths.writableLocation(QStandardPaths.DownloadLocation), "jamreceive")
self.connectstr = self.encode_ip()
self.targetconnectstr = ""
def openserver(self):
print("开启服务")
self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.serversocket.bind(("", self.port))
except OSError:
tport = self.allowports[random.randint(0, len(self.allowports) - 1)]
print("地址重复")
while tport == self.port:
tport = self.allowports[random.randint(0, len(self.allowports) - 1)]
self.port = tport
self.update_connectionstr()
self.serversocket.bind(("", self.port))
self.serversocket.listen()
def run(self):
self.openserver()
self.canconnect = True
while self.canconnect:
try:
client_socket, client_address = self.serversocket.accept()
except OSError:
print(sys.exc_info(), "l294")
if self.canconnect:
self.openserver()
continue
break
if not self.canconnect:
client_socket.close()
continue
try:
handupmes = client_socket.recv(1024).decode()
if handupmes.split(":")[0] == "searching":
print("被找到", handupmes)
if handupmes.split(":")[1] == self.connectstr:
client_socket.send("{}".format(client_address[0]).encode())
continue
else:
client_socket.send("outofdate".encode())
continue
elif handupmes == "reconnect":
if client_address[0] in self.allowip:
client_socket.send("allow".encode())
self.reconnectionsignal.emit(client_socket, client_address[0])
else:
client_socket.send("nopermit".encode())
else:
if handupmes.split(":")[0] == "connect":
port = handupmes.split(":")[1]
print("jjjj", client_address, self.connectionips, port)
if client_address[0] not in self.connectionips:
self.aconnectionsignal.emit(client_socket, client_address[0], int(port))
else:
print("已存在", client_address)
else:
continue
except:
print(sys.exc_info(), "l314")
client_socket.close()
continue
print("关闭服务")
def update_connectionstr(self):
self.updata_ips()
self.connectstr = self.encode_ip()
self.update_connectionstrchangesignal.emit(self.connectstr)
def updata_ips(self):
self.ips = get_ips()
self.segments, self.endsegs = get_Network_segments(self.ips)
def encode_ip(self): # qwer为主机(1)的个数,tyu为没有主机随机加的,poi为不足两位随机加的
def digitalpuss(d: int, p: int):
if d + p > 9:
return d - 10 + p
else:
return d + p
end = self.portids[self.allowports.index(self.port)]
mid = ""
e = 0
for seg in self.endsegs:
if "." not in seg:
if seg == str(1):
e += 1
else:
m = str(hex(int(seg)))[2:].lower()
if len(m) == 2:
mid += m
else:
mid += "poi"[random.randint(0, 2)] + m
else:
tm = []
for eseg in seg.split("."):
m = str(hex(int(eseg)))[2:].lower()
if len(m) == 2:
m = m
else:
m = "poi"[random.randint(0, 2)] + m
tm.append(m)
mid += tm[0] + "zxv"[random.randint(0, 2)] + tm[1] + "zxv"[random.randint(0, 2)] + tm[2]
randstr = mid + "qwrt"[e if e < 4 else 3] + end
print("编码前", randstr)
randstr = randstr.replace("a", "as?"[random.randint(0, 2)]).replace("b", "bnm"[random.randint(0, 2)]).replace(
"c", "cgh"[
random.randint(0, 2)]) \
.replace("d", "djk"[random.randint(0, 2)]).replace("e", "eyu"[random.randint(0, 2)]).replace("f", "fl+"[
random.randint(0, 2)])
randseed = random.randint(0, 9)
strlist = list(randstr)
for i, s in enumerate(strlist):
if s.isdigit():
strlist[i] = str(digitalpuss(int(s), randseed))
randstr = str(randseed) + "".join(strlist)
print(randstr)
return randstr
def decode_ip(self, randstr: str):
def digitalssub(d: int, s: int):
if d - s < 0:
return d + 10 - s
else:
return d - s
if randstr == self.connectstr:
print("企图连接自己?")
self.show_warningsignal.emit("请不要企图连接自己!")
return 0
if not randstr[0].isdigit():
self.show_warningsignal.emit("请输入正确的连接码!")
return 0
# try:
randseed = int(randstr[0])
randstrlist = list(randstr[1:])
for i, s in enumerate(randstrlist):
if s.isdigit():
randstrlist[i] = str(digitalssub(int(s), randseed))
randstr = "".join(randstrlist)
ra = {"as?": "a", "bnm": "b", "cgh": "c", "djk": "d", "eyu": "e", "fl+": "f"}
for b in ra.keys():
for s in b:
if s in randstr:
randstr = randstr.replace(s, ra[b])
print("解码后:", randstr)
if randstr[-1] not in self.portids:
self.show_warningsignal.emit("错误连接码!")
return 0
self.targetport = self.allowports[self.portids.index(randstr[-1])]
segmentstr = randstr[:-1]
print("segmentstr", segmentstr)
endsegs = []
def formatstr(s: str, replacestr: str):
for rs in replacestr:
s = s.replace(rs, "")
return s
havepoint = []
for i, s in enumerate(segmentstr):
if s in "zxv":
havepoint.append(i)
if len(havepoint) and len(havepoint) % 2 == 0:
havepoint = sorted(havepoint)
print("havepoint", havepoint)
for i in range(len(havepoint) // 2):
pos = havepoint[i * 2]
bseg = segmentstr[pos - 2:pos + 6].replace("z", ".").replace("x", ".").replace("v", ".")
print("b类主机位置", bseg)
endsegs.append("{}.{}.{}".format(int("0x" + formatstr(bseg.split(".")[0], "poi"), 16),
int("0x" + formatstr(bseg.split(".")[1], "poi"), 16),
int("0x" + formatstr(bseg.split(".")[2], "poi"), 16)))
segmentstr = segmentstr[:havepoint[0] - 2] + segmentstr[havepoint[-1] + 3:]
elif len(havepoint) % 2 != 0:
print("错误连接码")
self.show_warningsignal.emit("错误连接码")
return 0
if segmentstr[-1] not in "qwrt":
self.show_warningsignal.emit("连接码有误!")
return 0
havee = "qwrt".index(segmentstr[-1])
segmentstr = segmentstr[:-1]
if havee:
endsegs.append(str(1))
print("剩余普通endseg:", segmentstr)
while len(segmentstr) and len(segmentstr) % 2 == 0:
endsegs.append(str(int("0x" + segmentstr[:2], 16)))
segmentstr = segmentstr[2:]
print("endsegs", endsegs)
self.targetendsegs = endsegs
return 1
# except:
# s=sys.exc_info()
# print(s)
# self.show_warningsignal.emit("连接码解析错误!请联系作者反馈...({})".format(s))
def findserver(self):
self.findserverthread = ClientFindServer(self.targetport, self.targetendsegs, self.segments,
self.targetconnectstr, self.ips)
self.findserverthread.foundserversignal.connect(self.foundserver)
self.findserverthread.start()
QApplication.processEvents()
def foundserver(self, ip): # 找到可用连接
print((ip, self.targetport))
if ip in self.connectionips:
print(ip, "已经存在,不连接")
self.show_warningsignal.emit("该连接已经存在!")
return
if ip != "notfound" and ip != "outofdate":
self.waitAllowThread = clientWaitAllowThread(ip, self.targetport, self.port)
self.waitAllowThread.allowsignal.connect(self.allowsignalhandle)
self.waitAllowThread.start()
self.foundserverMSGsignal.emit(str(ip))
def allowsignalhandle(self, canconnect, address, clientsocket: socket.socket): # 等待确认完毕的信号
"""clientsocket:返回的链接socket"""
if canconnect:
self.targetdict[address] = self.targetport
self.parent.create_a_connection(clientsocket, address)
self.show_warningsignal.emit("已创建与{}的连接".format(address))
else:
self.show_warningsignal.emit("对方拒绝了你的连接请求!")
def findandconnectserver(self, randstr):
if len(randstr):
self.showm_signal.emit("正在查找并连接...")
self.targetconnectstr = randstr
if self.decode_ip(randstr):
self.findserver()
else:
self.showm_signal.emit("请输入连接码")
def disconnectserver(self, serverid=0):
self.clientthreads[serverid].quit()
self.clientthreads.pop(serverid)
def closeall(self):
result = QMessageBox.information(QWidget(), "重置?", "关闭所有连接并禁止被查找?", QMessageBox.Yes | QMessageBox.No,
QMessageBox.Yes)
if result == QMessageBox.No:
return 1
self.canconnect = False
for th in self.clientthreads:
th.quit()
del self.clientthreads
gc.collect()
self.clientthreads = []
try:
self.serversocket.close()
except AttributeError:
print("服务未开启")
self.quit()
print("已关闭所有")
class clientWaitAllowThread(QThread):
allowsignal = pyqtSignal(bool, str, socket.socket)
def __init__(self, ip, port, myport=8888):
super(clientWaitAllowThread, self).__init__()
self.ip = ip
self.myport = myport
self.targetport = port
def run(self):
asaclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
asaclient.connect((self.ip, self.targetport))
asaclient.send("connect:{}".format(self.myport).encode())
try:
connectresult = asaclient.recv(1024).decode()
except ConnectionResetError:
print("连接在确认中重置")
self.allowsignal.emit(False, self.ip, asaclient)
asaclient.close()
return
print("connectresult", connectresult)
if connectresult == "allow":
print("被允许连接")
self.allowsignal.emit(True, self.ip, asaclient)
else:
print("拒绝连接")
self.allowsignal.emit(False, self.ip, asaclient)
asaclient.close()
class ClientFindServer(QThread): # 根据连接码寻找服务器总线程
foundserversignal = pyqtSignal(str)
def __init__(self, targetport, targetendsegs, segments, connectstr, ips):
super(ClientFindServer, self).__init__()
print("target:", targetport, targetendsegs, segments, connectstr)
self.targetport, self.segments = targetport, segments
self.findthreads = []
self.found = False
self.connectstr = connectstr
self.ips = ips
self.bendseg = []
self.cendseg = []
for endseg in targetendsegs:
if "." in endseg:
self.bendseg.append(endseg)
else:
self.cendseg.append(endseg)
def run(self):
for segment in self.segments:
if len(segment.split(".")) == 2:
if len(self.bendseg):
print("解析b类地址")
thread = afindserverthread(self.targetport, segment, self.bendseg, self.connectstr, self.ips)
thread.foundsignal.connect(self.targetfound)
thread.start()
self.findthreads.append(thread)
else:
thread = afindserverthread(self.targetport, segment, self.cendseg, self.connectstr, self.ips)
thread.foundsignal.connect(self.targetfound)
thread.start()
self.findthreads.append(thread)
for thread in self.findthreads:
thread.wait()
if not self.found:
print("没有找到")
self.foundserversignal.emit("notfound")
def targetfound(self, ip):
self.found = True
print("找到:", ip)
for thread in self.findthreads:
thread.quit()
self.foundserversignal.emit(ip)
# for thread in self.findthreads:
# # thread.wait()
# self.wait()
del self.findthreads
gc.collect()
# self.findthreads = []
class afindserverthread(QThread): # 每个网段都开一个线程同时寻找
foundsignal = pyqtSignal(str)
def __init__(self, port, segment, targetendsegs, connectstr, ips):
super(afindserverthread, self).__init__()
self.targetport, self.segment, self.targetendsegs = port, segment, targetendsegs
self.fquit = False
self.connectstr = connectstr
self.ips = ips
def run(self):
for endseg in self.targetendsegs:
ip = self.segment + str(endseg)
if ip in self.ips:
print(ip, "是自己的ip")
continue
testclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
testclient.settimeout(3)
testclient.connect((ip, self.targetport))
except:
print(sys.exc_info(), "l557")
if self.fquit:
break
testclient.close()
continue
try:
testclient.send("searching:{}".format(self.connectstr).encode())
ip = testclient.recv(1024).decode()
print(ip)
if ip == "outofdate":
print("out of date")
self.foundsignal.emit("outofdate")
break
except:
print(sys.exc_info(), "l572")
if self.fquit:
break
testclient.close()
continue
if not self.fquit:
self.foundsignal.emit(self.segment + str(endseg))
break
try:
testclient.close()
except:
print(sys.exc_info())
def quit(self):
self.fquit = True
super(afindserverthread, self).quit()
class ClientListenThread(QThread): # 客户端连接后持续监听线程
resetsignal = pyqtSignal(str)
reconnectsignal = pyqtSignal(socket.socket, str, bool)
showm_signal = pyqtSignal(str)
update_state_signal = pyqtSignal(str)
pausebtntext_signal = pyqtSignal(str)
def __init__(self, clientsocket: socket.socket, parent: ClientFilesTransmitter, ip):
super(ClientListenThread, self).__init__()
self.ip = ip
self.parent = parent
self.clientsocket = clientsocket
self.onlistening = True
self.rootpath = self.receivepath = self.parent.rootpath
self.sendthreadnum = 4
def run(self):
self.onlistening = True
allbytes = "".encode()
while self.onlistening:
try:
a = self.clientsocket.recv(9999)
if len(a) == 0:
print("no data exit 878")
# self.resetsignal.emit(self.ip)
self.showm_signal.emit("{}已断开!".format(self.ip))
break