-
Notifications
You must be signed in to change notification settings - Fork 0
/
cutiefeed.py
executable file
·1497 lines (1190 loc) · 48.3 KB
/
cutiefeed.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
#!/usr/bin/env python3
from PyQt5 import QtCore, QtGui, QtWidgets, uic
import sys
from getcfg import *
from ii_functions import *
import network
import webfetch
import writemsg
import sender
import re
import webbrowser
from threading import Thread
import ctypes
import queue
import json, shutil, math, uuid
import urllib.parse
urltemplate=re.compile("(https?|ftp|file)://?[-A-Za-zА-Яа-я0-9+&@#/%?=~_|!:,.;]+[-A-Za-zА-Яа-я0-9+&@#/%=~_|]")
quotetemplate=re.compile(r"^\s?[\w_А-Яа-я\-]{0,20}(>)+.+$", re.MULTILINE | re.IGNORECASE)
commenttemplate=re.compile(r"(^|(\w\s+))(PS|P\.S|ЗЫ|З\.Ы|\/\/|#)(.+$)", re.MULTILINE | re.IGNORECASE)
ii_link=re.compile(r"ii:\/\/(\w[\w.-]+\w+)", re.MULTILINE)
def get_favorites():
try:
f=open(paths.favoritesfile)
storage=json.load(f)
f.close()
return storage
except:
return {"list":[], "subjes":{}}
def save_favorites(array):
try:
f=open(paths.favoritesfile, "w")
json.dump(array, f)
f.close()
except Exception as e:
print("Ошибка сохранения списка избранных сообщений: "+str(e))
def outbox_id_by_address(addr):
for server in config["servers"]:
if server["adress"] == addr:
return server["outbox_storage_id"]
return None
def outbox_id_by_echoarea(echoarea):
for server in config["servers"]:
if echoarea in server:
return server["outbox_storage_id"]
return None
def getproxy():
proxy=None
if config["useProxy"]:
proxy={config["proxyType"]: config["proxy"]}
return proxy
def get_pos_cache():
try:
f=open(paths.echopositionfile)
pos_cache=json.load(f)
f.close()
return pos_cache
except:
return {}
def get_position(echo, cache):
if not echo in cache.keys():
return None
else:
return cache[echo]
def save_pos_cache(cache):
try:
f=open(paths.echopositionfile, "w")
json.dump(cache, f)
f.close()
except Exception as e:
print("Ошибка сохранения кэша позиции: "+str(e))
def get_subj_cache(echo):
filename=os.path.join(paths.subjcachedir, echo)
try:
cache=read_file(filename).splitlines()
return cache
except:
touch(filename)
return []
def cache_exists(echo):
filename=os.path.join(paths.subjcachedir, echo)
return os.path.exists(filename)
def append_subj_cache(subj_data, echo):
if type(subj_data) == list:
subj_data="\n".join(subj_data)
try:
filename=os.path.join(paths.subjcachedir, echo)
f=open(filename, "a")
f.write(subj_data+"\n")
f.close()
return True
except:
print("error append cache")
return False
def load_raw_file(adress, data=None):
def loadFunction():
try:
string=network.getfile(adress, getproxy(), data, timeout=config["connectionTimeout"])
form.newmsgq.put(string)
except Exception as e:
form.errorsq.put(["Ошибка скачивания: ", e])
form.newmsgq.put("")
return form.processNewThread(loadFunction)
def prettier_size(n,pow=0,b=1024,u='B',pre=['']+[p+'i'for p in'KMGTPEZY']):
r,f=min(int(math.log(max(n*b**pow,1),b)),len(pre)-1),'{:,.%if} %s%s'
return (f%(abs(r%(-r-1)),pre[r],u)).format(n*b**pow/b**float(r))
def xfile_download(server, filename, savename, signal):
data = urllib.parse.urlencode({'pauth': server["authstr"], 'filename':filename}).encode('utf8')
try:
out = network.getfile(server["adress"] + 'x/file', getproxy(), data, return_descriptor=True, timeout=config["connectionTimeout"])
except Exception as e:
form.errorsq.put(["Ошибка скачивания: ", e])
form.newmsgq.put("Ну не получилось, чего поделаешь!")
return
file_size=0
block_size=8192
f=open(savename, "wb")
while True:
buffer=out.read(block_size)
if not buffer:
break
file_size+=len(buffer)
f.write(buffer)
signal.emit(file_size)
f.close()
form.newmsgq.put("Скачали "+str(prettier_size(file_size)))
def updatemsg():
global msgnumber,msgid_answer,msglist,echo
echocount=len(msglist)
if echocount == 0: # если мы в пустой эхе, кнопки нам не нужны
return
msgid_answer=msglist[msgnumber]
msg=getMsgEscape(msgid_answer)
repto=msg.get("repto") or "-"
if (repto!="-"):
repto="<a href='#ii:"+repto+"'>"+repto+"</a>"
msgtext="msgid: "+msgid_answer+"<br />"+"Ответ на: "+repto+"<br />"+formatDate(msg.get('time'))+"<br />"+msg.get('subj')+"<br /><b>"+msg.get('sender')+" ("+msg.get('addr')+") -> "+msg.get('to')+"</b><br />"
form.listWidget.setCurrentRow(msgnumber)
form.textBrowser.setHtml(msgtext+"<br />"+reparseMessage(msg.get('msg')))
form.label.setText( echo + " | " + str(echocount - msgnumber) + " из " + str(echocount))
if config["rememberEchoPosition"] and form.echoPosition != None:
form.echoPosition[echo]=echocount-msgnumber
if msgid_answer in form.favorites_array["list"]:
form.checkBox.setChecked(True)
else:
form.checkBox.setChecked(False)
def msgminus(event):
global msgnumber
if(msgnumber>0):
msgnumber-=1;
updatemsg()
def msgplus(event):
global msgnumber
if(msgnumber<=listlen):
msgnumber+=1;
updatemsg()
def lbselect():
global msgnumber
msgnumber=form.listWidget.currentRow()
updatemsg()
def c_writeNew(event):
global echo, curr_outbox_id
writemsg.writeNew(echo, curr_outbox_id)
def answer(event):
global msgid_answer, curr_outbox_id
writemsg.answer(msgid_answer, curr_outbox_id)
def sendWrote_operation():
countsent=0
def errorCb(tossfile, error):
form.errorsq.put(["Ошибка ноды при отправке "+tossfile+": ", error])
try:
countsent=sender.sendMessages(getproxy(), errorCb)
except stoppedDownloadException as e:
form.newmsgq.put(e)
except Exception as e:
form.newmsgq.put(e)
form.errorsq.put(["Ошибка отправки: ", e])
form.newmsgq.put(countsent)
def sendWrote(event):
result=form.processNewThread(sendWrote_operation)
if (not isinstance(result, Exception)):
mbox("Отправлено сообщений: "+str(result))
def setUIResize(filename, object):
# подгрузка интерфейса с учётом предыдущего размера окна
currentsize=object.size()
uic.loadUi(filename,object)
object.resize(currentsize) # восстанавливаем предыдущий размер
def mbox(text):
form.mbox.setText(text)
form.mbox.exec_()
def editItem(event):
lw=event.listWidget()
event.setFlags(QtCore.Qt.ItemFlags(1|2|32)) # ставим, что элемент активный, что его можно править, и что он выбираемый
lw.editItem(event)
def deleteItem(event):
form.currLw.takeItem(form.currLw.currentRow())
def addItem(event):
newListItem=QtWidgets.QListWidgetItem("echoarea.15")
newListItem.setFlags(QtCore.Qt.ItemFlags(1|2|32))
targetRow=form.currLw.currentRow()+1
form.currLw.insertItem(targetRow, newListItem)
form.currLw.setCurrentRow(targetRow)
form.currLw.editItem(newListItem)
def itemUp(event):
targetRow=form.currLw.currentRow()-1
if (targetRow>=0):
tookItem=form.currLw.takeItem(targetRow+1)
form.currLw.insertItem(targetRow, tookItem)
form.currLw.setCurrentRow(targetRow)
def itemDown(event):
targetRow=form.currLw.currentRow()+1
count=form.currLw.count()
if (targetRow<count):
tookItem=form.currLw.takeItem(targetRow-1)
form.currLw.insertItem(targetRow, tookItem)
form.currLw.setCurrentRow(targetRow)
def reparseMessage(string):
global urltemplate, quotetemplate, commenttemplate, ii_link
string=urltemplate.sub("<a href='\g<0>'>\g<0></a>", string)
string=quotetemplate.sub("<font color='green'>\g<0></font>", string)
string=commenttemplate.sub("\g<1><font color='brown'>\g<3>\g<4></font>", string)
string=ii_link.sub("<a href='#ii:\g<1>'>\g<0></a>", string)
strings=string.splitlines()
pre_flag=False
for i in range(0, len(strings)):
if strings[i]=="====":
if not pre_flag:
pre_flag=True
strings[i]="<pre style='font-family: monospace;'>===="
else:
pre_flag=False
strings[i]="====</pre>"
return "<br />".join(strings)
def openLink(link):
global curr_outbox_id
link=link.toString()
if (link.startswith("#")): # если перед нами ii-ссылка
link=link[1:] # срезаем первые ненужные символы
data=link.split(":")
if not len(data) > 1:
print(data)
return
word=data[0]
link=data[1]
if word == "ii":
if "." in link:
curr_outbox_id = outbox_id_by_echoarea(link)
form.viewwindow(link, curr_outbox_id) # идём в эху
else:
form.openMessageView(link) # смотрим сообщение
elif word == "answer": # отвечаем на msgid
if not curr_outbox_id:
target_outbox_id = outbox_id_by_echoarea(getMsg(link).get("echo"))
if target_outbox_id is not None:
writemsg.answer(link, target_outbox_id)
else:
curr_outbox_id = config["servers"][0]["outbox_storage_id"]
writemsg.answer(link, curr_outbox_id)
curr_outbox_id = None
else:
writemsg.answer(link, curr_outbox_id)
else:
print("opening link in default browser")
webbrowser.open(link)
class Form(QtWidgets.QMainWindow):
updateSignal=QtCore.pyqtSignal(str, name="update_signal")
dl_label_signal=QtCore.pyqtSignal(int, name="dl_label_signal")
def __init__(self):
global msglist,msgnumber,listlen
super(Form, self).__init__()
windowIcon = QtGui.QIcon('artwork/cutiefeed.svg')
stylesheet = read_file('qtgui-files/style.qss')
self.setStyleSheet(stylesheet)
self.newmsgq=queue.Queue()
self.errorsq=queue.Queue()
self.loadviewq=queue.Queue()
self.networkingThread=Thread()
self.loadViewThread=Thread()
self.updateTB=Thread()
self.setWindowIcon(windowIcon)
self.mbox=QtWidgets.QMessageBox()
self.mbox.setText("")
self.boldFont=QtGui.QFont()
self.boldFont.setBold(True)
self.favoritesChanged=False
# настраиваем диалог удаления тоссов
self.clearMessages=QtWidgets.QMessageBox(QtWidgets.QMessageBox.Question, "Подтверждение", "Удалить исходящие сообщения?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
self.deleteAll=QtWidgets.QCheckBox("В том числе отправленные")
self.clearMessages.setCheckBox(self.deleteAll)
self.clearXC=QtWidgets.QMessageBox(QtWidgets.QMessageBox.Question, "Подтверждение", "Удалить данные /x/c?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
self.clearCache=QtWidgets.QMessageBox(QtWidgets.QMessageBox.Question, "Подтверждение", "Удалить кэш для эх?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
self.echoPosition=None
self.setupClientConfig()
self.setupServersConfig()
self.setupUnsentView()
self.setupAdditional()
self.setupFavorites()
self.setupMenu()
self.setupHelp()
# если запускаем клиент в первый раз, сначала показываются настройки
if (config["firstrun"]==True):
config["firstrun"]=False
global form
form=self # костыль, иначе запрос списка эх не заработает
self.execServersConfig()
if not config["autoSaveChanges"]:
self.saveChanges()
try:
f=open(paths.sessioncache)
self.sessionCache=json.load(f)
f.close()
self.currentStation = self.sessionCache["currentStation"]
except:
self.sessionCache={}
self.currentStation = 0
self.mainwindow()
if config["maximized"]:
self.setWindowState(QtCore.Qt.WindowMaximized)
else:
self.resize(580, 452)
def mainwindow(self):
setUIResize("qtgui-files/mainwindow.ui",self)
global echo, msgid_answer # для правильной работы открытия ii-ссылок в окне просмотра исходящих
echo="none"
msgid_answer="none"
self.pushButton.clicked.connect(self.getNewText)
self.pushButton_2.clicked.connect(sendWrote)
self.pushButton_3.clicked.connect(self.displayOfflineEchos)
self.pushButton_4.clicked.connect(self.updateMainView)
self.menuButton.setMenu(self.clMenu)
for server in servers:
self.comboBox.addItem(server["adress"])
if self.currentStation >= len(servers):
self.currentStation = 0
self.comboBox.setCurrentIndex(self.currentStation)
self.listWidget.addItems(servers[self.currentStation]["echoareas"])
self.comboBox.currentIndexChanged.connect(self.loadEchoList)
self.listWidget.itemActivated.connect(self.openViewWindow)
def viewwindow(self, echoarea, outbox_id):
global msglist,msgnumber,listlen,echo,curr_outbox_id
echo=echoarea
curr_outbox_id=outbox_id
setUIResize("qtgui-files/viewwindow.ui",self)
self.setWindowTitle("Просмотр сообщений: "+echoarea)
msglist=getMsgList(echo)
listlen=len(msglist)
if config["rememberEchoPosition"]:
if self.echoPosition == None:
self.echoPosition=get_pos_cache()
msgnumber=get_position(echo, self.echoPosition)
if msgnumber == None or msgnumber >= listlen:
msgnumber = 0
else:
msgnumber = listlen - msgnumber
else:
msgnumber = 0
self.processProgressBar(self.loadEchoBase)
msglist.reverse()
self.listWidget.currentRowChanged.connect(lbselect)
self.listWidget.setCurrentRow(msgnumber)
self.pushButton.clicked.connect(self.mainwindow)
self.pushButton_2.clicked.connect(msgminus)
self.pushButton_3.clicked.connect(msgplus)
self.pushButton_4.clicked.connect(sendWrote)
self.pushButton_5.clicked.connect(answer)
self.pushButton_6.clicked.connect(c_writeNew)
self.pushButton_7.clicked.connect(self.getNewText)
self.checkBox.clicked.connect(self.favorites_toggle)
self.menuButton.setMenu(self.clMenu)
self.textBrowser.anchorClicked.connect(openLink)
def getDialog(self):
setUIResize("qtgui-files/getwindow.ui",self)
self.pushButton.clicked.connect(self.getNewText)
self.pushButton_2.clicked.connect(self.mainwindow)
self.newMsgTextBrowser.setParent(self)
self.verticalLayout.addWidget(self.newMsgTextBrowser)
global curr_outbox_id
curr_outbox_id = None # для открытия ii-ссылок для ответа на сообщения
def processNewThread(self, function, args=[], takeResult=True):
if self.networkingThread.is_alive():
return
debugform.appear()
self.networkingThread=Thread(target=function, args=args)
self.networkingThread.daemon=True
self.networkingThread.start()
while (self.networkingThread.is_alive()):
if (not gprintq.empty()):
debugform.addText(gprintq.get())
app.processEvents()
while (not self.errorsq.empty()):
error=self.errorsq.get()
mbox(error[0]+'\n\n'+str(error[1]))
self.networkingThread.join()
debugform.disappear()
if takeResult:
return self.newmsgq.get()
def loadEchoBase(self):
global msglist, listlen
with self.loadviewq.mutex:
self.loadviewq.queue.clear()
subjes=get_subj_cache(echo)
if len(subjes) != listlen:
cache=open(os.path.join(paths.subjcachedir, echo), "w")
for i in range(listlen):
subj=getMsg(msglist[i]).get('subj')
self.loadviewq.put_nowait([i,subj])
cache.write(subj+"\n")
cache.close()
else:
for i in range(listlen):
self.loadviewq.put_nowait([i,subjes[i]])
def processProgressBar(self, function):
self.setVisible(0)
self.progress=QtWidgets.QProgressDialog(self)
self.progress.setLabel(QtWidgets.QLabel("Подгружаем эху..."))
self.progress.setAutoClose(True)
self.progress.setMaximum(listlen-1)
self.progress.show()
self.loadViewThread=Thread(target=function)
self.loadViewThread.daemon=True
self.loadViewThread.start()
while True:
app.processEvents()
queueFull=(not self.loadviewq.empty())
threadAlive=self.loadViewThread.is_alive()
if (queueFull or threadAlive):
if (queueFull):
element=self.loadviewq.get(timeout=5)
self.listWidget.insertItem(0, element[1]) # это сабж вообще-то
self.progress.setValue(element[0]) # а это - значение прогрессбара
else:
break
self.loadViewThread.join()
self.setVisible(1)
self.progress.hide()
self.progress.destroy()
def getNewMessages(self):
def fx(msgids):
if len(msgids) > 0:
self.newmsgq.put(msgids)
proxy_config=getproxy()
for server in servers:
if not server["fetch_enabled"]:
print("skip fetching " + server["adress"])
continue
try:
if (server["advancedue"] == False):
uelimit=False
else:
uelimit=server["uelimit"]
# uelimit - сколько msgid скачивать максимум при наличии расширенной схемы
# если стоит в False, то скачиваем все
msgidsNew=webfetch.fetch_messages(server["adress"], server["echoareas"], server["xcenable"], fetch_limit=uelimit, one_request_limit=config["oneRequestLimit"], proxy=proxy_config, pervasive_ue=server["pervasiveue"], callback=fx, cut_remote_index=server["cut_remote_index"], connTimeout=config["connectionTimeout"])
except stoppedDownloadException:
break
except Exception as e:
self.errorsq.put([server["adress"]+": ошибка получения сообщений (проблемы с интернетом?)", e])
def getNewText(self):
self.newMsgTextBrowser=QtWidgets.QTextBrowser(None)
self.newMsgTextBrowser.anchorClicked.connect(openLink)
self.newMsgTextBrowser.setOpenLinks(False)
self.updateSignal.connect(self.newMsgTextBrowser.append, QtCore.Qt.QueuedConnection)
self.gotMsgs=False
self.windowFlag=False
def updateTextBrowser(signal):
while True:
if not self.newmsgq.empty():
if not self.gotMsgs:
self.newMsgTextBrowser.insertHtml("Новые сообщения:")
self.gotMsgs=True
msgids=self.newmsgq.get()
htmlcode=""
for msgid in msgids:
arr=getMsgEscape(msgid)
msgid=arr.get('id')
echo=arr.get('echo')
subj=arr.get('subj')
if cache_exists(echo):
append_subj_cache(subj, echo)
htmlcode+="<hr /><br /><a href='#ii:"+echo+"'>"+echo+"</a><br />msgid: <a href='#answer:"+msgid+"'>"+msgid+"</a><br />"+formatDate(arr.get('time'))+"<br />"+subj+"<br /><b>"+arr.get('sender')+' ('+arr.get('addr')+') -> '+arr.get('to')+"</b><br /><br />"+reparseMessage(arr.get('msg'))
signal.emit(htmlcode)
else:
if not self.networkingThread.is_alive():
return
if self.networkingThread.is_alive() or self.updateTB.is_alive():
return
debugform.appear()
self.networkingThread=Thread(target=self.getNewMessages)
self.networkingThread.daemon=True
self.networkingThread.start()
self.updateTB=Thread(target=updateTextBrowser, args=[self.updateSignal])
self.updateTB.daemon=True
self.updateTB.start()
while (self.networkingThread.is_alive()):
if self.gotMsgs and not self.windowFlag:
self.getDialog()
self.windowFlag=True
if (not gprintq.empty()):
debugform.addText(gprintq.get())
app.processEvents()
while (not self.errorsq.empty()):
error=self.errorsq.get()
mbox(error[0]+'\n\n'+str(error[1]))
self.networkingThread.join()
self.updateTB.join()
debugform.disappear()
if not self.gotMsgs:
self.newMsgTextBrowser.destroy()
mbox('Новых сообщений нет.')
else:
global curr_outbox_id
curr_outbox_id = None
def deleteTosses(self):
answer=self.clearMessages.exec_()
counter=0
if answer == QtWidgets.QMessageBox.Yes:
for server in config["servers"]:
outbox_id = server["outbox_storage_id"]
path = os.path.join(paths.tossesdir, outbox_id)
for filename in os.listdir(path):
if self.deleteAll.isChecked() or filename[-5:] == ".toss":
counter+=1
delete(os.path.join(path, filename))
if counter>0:
mbox("Удалено сообщений: "+str(counter))
else:
mbox("Удалять нечего")
def deleteXC(self):
answer=self.clearXC.exec_()
counter=0
if answer == QtWidgets.QMessageBox.Yes:
for filename in os.listdir(paths.datadir):
if filename[:5]=="base-":
counter+=1
delete(os.path.join(paths.datadir, filename))
if counter>0:
mbox("Удалено файлов: "+str(counter))
else:
mbox("Удалять нечего")
def deleteCache(self):
answer=self.clearCache.exec_()
counter=0
if answer == QtWidgets.QMessageBox.Yes:
if os.path.exists(paths.echopositionfile):
delete(paths.echopositionfile)
counter+=1
if os.path.exists(paths.sessioncache):
delete(paths.sessioncache)
counter+=1
if self.echoPosition != None:
self.echoPosition=None
self.currentStation = 0
for filename in os.listdir(paths.subjcachedir):
delete(os.path.join(paths.subjcachedir, filename))
counter+=1
if counter>0:
mbox("Удалено файлов: "+str(counter))
else:
mbox("Удалять нечего")
def deleteOneEcho(self):
echoarea=self.additional.comboBox_2.currentText()
question=QtWidgets.QMessageBox(QtWidgets.QMessageBox.Question, "Подтверждение", "Удалить эху "+echoarea+"?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
answer=question.exec_()
question.destroy()
if (answer == QtWidgets.QMessageBox.Yes):
global echo
if echo == echoarea:
self.mainwindow()
def function():
msglist=getMsgList(echoarea)
for msgid in msglist:
delete(os.path.join(paths.msgdir, msgid))
delete(os.path.join(paths.indexdir, echoarea))
delete(os.path.join(paths.subjcachedir, echoarea))
self.processNewThread(function, takeResult=False)
self.additional_update_echoes()
def deleteAllEchoes(self):
countItems=self.additional.comboBox_2.count()
echoes=[]
for i in range(countItems):
echoes.append(self.additional.comboBox_2.itemText(i))
question=QtWidgets.QMessageBox(QtWidgets.QMessageBox.Question, "Подтверждение", "Удалить ВСЮ БАЗУ ДАННЫХ?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
answer=question.exec_()
question.destroy()
if (answer == QtWidgets.QMessageBox.Yes):
self.mainwindow()
def function():
for echo in echoes:
msglist=getMsgList(echo)
for msgid in msglist:
delete(os.path.join(paths.msgdir, msgid))
delete(os.path.join(paths.indexdir, echo))
delete(os.path.join(paths.subjcachedir, echo))
self.processNewThread(function, takeResult=False)
self.additional_update_echoes()
def setupMenu(self):
self.clMenu=QtWidgets.QMenu()
clientSettingsAction=QtWidgets.QAction("Настройки клиента", self)
serversSettingsAction=QtWidgets.QAction("Настройки станций", self)
saveSettingsAction=QtWidgets.QAction("Сохранить настройки", self)
additionalFeaturesAction=QtWidgets.QAction("Дополнительные фичи", self)
deleteTossesAction=QtWidgets.QAction("Удалить исходящие", self)
deleteXCAction=QtWidgets.QAction("Удалить данные /x/c", self)
deleteCacheAction=QtWidgets.QAction("Удалить кэш", self)
helpAction=QtWidgets.QAction("Справка", self)
unsentViewAction=QtWidgets.QAction("Просмотр исходящих", self)
favoritesAction=QtWidgets.QAction("Избранные сообщения", self)
clientSettingsAction.triggered.connect(self.execClientConfig)
serversSettingsAction.triggered.connect(self.execServersConfig)
saveSettingsAction.triggered.connect(self.saveChanges)
additionalFeaturesAction.triggered.connect(self.execAdditional)
deleteTossesAction.triggered.connect(self.deleteTosses)
deleteXCAction.triggered.connect(self.deleteXC)
deleteCacheAction.triggered.connect(self.deleteCache)
helpAction.triggered.connect(self.showHelp)
unsentViewAction.triggered.connect(self.execUnsentView)
favoritesAction.triggered.connect(self.execFavorites)
self.clMenu.addAction(unsentViewAction)
self.clMenu.addAction(favoritesAction)
self.clMenu.addSeparator()
self.clMenu.addAction(clientSettingsAction)
self.clMenu.addAction(serversSettingsAction)
self.clMenu.addAction(saveSettingsAction)
self.clMenu.addAction(additionalFeaturesAction)
self.clMenu.addSeparator()
self.clMenu.addAction(deleteTossesAction)
self.clMenu.addAction(deleteXCAction)
self.clMenu.addAction(deleteCacheAction)
self.clMenu.addSeparator()
self.clMenu.addAction(helpAction)
def setupClientConfig(self):
self.clientConfig=uic.loadUi("qtgui-files/clientconfig.ui")
self.clientConfig.listWidget.itemDoubleClicked.connect(editItem)
self.clientConfig.pushButton.clicked.connect(addItem) # кнопка Добавить
self.clientConfig.pushButton_2.clicked.connect(deleteItem) # кнопка Удалить
self.clientConfig.pushButton_3.clicked.connect(itemUp) # кнопка Вверх
self.clientConfig.pushButton_4.clicked.connect(itemDown) # кнопка Вниз
self.clientConfig.accepted.connect(self.applyClientConfig)
def setupServersConfig(self):
self.serversConfig=uic.loadUi("qtgui-files/stations.ui")
self.serversConfig.tabBar=QtWidgets.QTabBar(self.serversConfig)
self.serversConfig.tabBar.setMovable(True)
self.serversConfig.horizontalLayout.addWidget(self.serversConfig.tabBar)
self.serversConfig.horizontalLayout.addWidget(self.serversConfig.addTabButton)
self.serversConfig.horizontalLayout.addWidget(self.serversConfig.deleteTabButton)
for i in range(len(servers)):
self.serversConfig.tabBar.addTab(str(i+1))
self.oldCurrentTab=0
self.serversConfig.tabBar.currentChanged.connect(self.updateInfo_servers_fromTab)
self.serversConfig.tabBar.tabMoved.connect(self.tabMovedEvent)
self.serversConfig.listWidget.itemDoubleClicked.connect(editItem)
self.serversConfig.pushButton.clicked.connect(addItem) # кнопка Добавить
self.serversConfig.pushButton_2.clicked.connect(deleteItem) # кнопка Удалить
self.serversConfig.pushButton_3.clicked.connect(itemUp) # кнопка Вверх
self.serversConfig.pushButton_4.clicked.connect(itemDown) # кнопка Вниз
self.serversConfig.pushButton_5.clicked.connect(self.load_list_txt) # получение списка эх с ноды
self.serversConfig.pushButton_6.clicked.connect(self.x_features_autoConfig) # автонастройка
self.serversConfig.addTabButton.clicked.connect(self.tabAddRequest)
self.serversConfig.deleteTabButton.clicked.connect(self.tabDeleteRequest)
self.serversConfig.accepted.connect(self.applyServersConfigFromButton)
def setupUnsentView(self):
def updateView(item):
if item == None: # например, если мы удалили последнее
self.unsentView.textBrowser.clear()
return
filename = item.data(QtCore.Qt.UserRole)
s=getOutMsgEscape(filename)
repto=s.get("repto") or "-"
if (repto!="-"):
repto="<a href='#ii:"+repto+"'>"+repto+"</a>"
output="Ответ на: "+repto+"<br />"+s.get("echo")+"<br />"+s.get("subj")+"<br /><b>"+s.get("to")+"</b><br /><br />"+reparseMessage(s.get("msg"))
self.unsentView.textBrowser.setHtml(output)
def left():
msgnumber=self.unsentView.listWidget.currentRow()
if(msgnumber>0):
msgnumber-=1;
self.unsentView.listWidget.setCurrentRow(msgnumber)
def right():
msgnumber=self.unsentView.listWidget.currentRow()
listlen=self.unsentView.listWidget.count()
if(msgnumber<(listlen-1)):
msgnumber+=1;
self.unsentView.listWidget.setCurrentRow(msgnumber)
def edit():
item=self.unsentView.listWidget.currentItem()
if item != None:
filename=item.data(QtCore.Qt.UserRole)
writemsg.openEditor(filename)
def deleteFile():
msgnumber=self.unsentView.listWidget.currentRow()
item=self.unsentView.listWidget.takeItem(msgnumber)
if item != None:
filename=item.data(QtCore.Qt.UserRole)
delete(filename)
def delTosses():
self.deleteTosses()
self.loadUnsentView()
self.unsentView=uic.loadUi("qtgui-files/unsent.ui")
self.unsentView.pushButton.clicked.connect(delTosses)
self.unsentView.pushButton_2.clicked.connect(left)
self.unsentView.pushButton_3.clicked.connect(right)
self.unsentView.pushButton_4.clicked.connect(sendWrote)
self.unsentView.pushButton_5.clicked.connect(deleteFile)
self.unsentView.pushButton_6.clicked.connect(edit)
self.unsentView.pushButton_7.clicked.connect(self.loadUnsentView)
self.unsentView.textBrowser.anchorClicked.connect(openLink)
self.unsentView.listWidget.currentItemChanged.connect(updateView)
def setupAdditional(self):
self.additional=uic.loadUi("qtgui-files/additional.ui")
self.additional.filename=""
self.additional.pushButton.clicked.connect(self.download_blacklist_txt)
self.additional.pushButton_2.clicked.connect(self.choose_blacklist_file)
self.additional.pushButton_3.clicked.connect(self.blacklist_cleanup)
self.additional.pushButton_4.clicked.connect(self.try_load_xfilelist)
self.additional.pushButton_5.clicked.connect(self.deleteAllEchoes)
self.additional.pushButton_6.clicked.connect(self.deleteOneEcho)
self.additional.pushButton_7.clicked.connect(self.copy_blacklist_txt)
self.dl_label_signal.connect(self.dl_set_label, QtCore.Qt.QueuedConnection)
self.additional.tableView.doubleClicked.connect(self.try_load_file)
self.additional.tableView.horizontalHeader().setStretchLastSection(True)
def setupFavorites(self):
def updateView(item):
if item == None:
self.favorites.textBrowser.clear()
return
msgid = item.data(QtCore.Qt.UserRole)
msg=getMsgEscape(msgid)
echo=msg.get("echo")
repto=msg.get("repto") or "-"
if repto!="-":
repto="<a href='#ii:"+repto+"'>"+repto+"</a>"
msgtext="<a href='#ii:"+echo+"'>"+echo+"</a><br />msgid: <a href='#answer:"+msgid+"'>"+msgid+"</a><br />"+"Ответ на: "+repto+"<br />"+formatDate(msg.get('time'))+"<br />"+msg.get('subj')+"<br /><b>"+msg.get('sender')+" ("+msg.get('addr')+") -> "+msg.get('to')+"</b><br />"
self.favorites.textBrowser.setHtml(msgtext+"<br />"+reparseMessage(msg.get('msg')))
def left():
msgnumber=self.favorites.listWidget.currentRow()
if(msgnumber>0):
msgnumber-=1;
self.favorites.listWidget.setCurrentRow(msgnumber)
def right():
msgnumber=self.favorites.listWidget.currentRow()
listlen=self.favorites.listWidget.count()
if(msgnumber<(listlen-1)):
msgnumber+=1;
self.favorites.listWidget.setCurrentRow(msgnumber)
def deleteFavorite():
self.favoritesChanged=True
msgnumber=self.favorites.listWidget.currentRow()
item=self.favorites.listWidget.takeItem(msgnumber)
if item != None:
msgid=item.data(QtCore.Qt.UserRole)
self.favorites_array["list"].remove(msgid)
del self.favorites_array["subjes"][msgid]
self.favorites=uic.loadUi("qtgui-files/favorites.ui")
self.favorites.pushButton_2.clicked.connect(left)
self.favorites.pushButton_3.clicked.connect(right)
self.favorites.pushButton_5.clicked.connect(deleteFavorite)
self.favorites.listWidget.currentItemChanged.connect(updateView)
self.favorites.textBrowser.anchorClicked.connect(openLink)
self.favorites_array = get_favorites()
def loadInfo_client(self):
self.clientConfig.lineEdit.setText(config["editor"])
self.clientConfig.lineEdit_2.setText(config["proxy"])
self.clientConfig.lineEdit_3.setText(config["proxyType"])
self.clientConfig.listWidget.clear()
self.clientConfig.listWidget.addItems(config["offline-echoareas"])
if (len(config["offline-echoareas"])>0):
self.clientConfig.listWidget.setCurrentRow(0)
self.clientConfig.checkBox.setChecked(config["defaultEditor"])
self.clientConfig.checkBox_2.setChecked(config["firstrun"])
self.clientConfig.checkBox_3.setChecked(config["autoSaveChanges"])
self.clientConfig.checkBox_4.setChecked(config["useProxy"])
self.clientConfig.checkBox_5.setChecked(config["rememberEchoPosition"])
self.clientConfig.checkBox_6.setChecked(config["maximized"])
self.clientConfig.spinBox.setValue(config["oneRequestLimit"])
self.clientConfig.spinBox_2.setValue(config["connectionTimeout"])
def loadInfo_servers(self, index=0):
curr=servers[index]
self.serversConfig.lineEdit.setText(curr["adress"])
self.serversConfig.lineEdit_2.setText(curr["authstr"])
self.serversConfig.listWidget.clear()
self.serversConfig.listWidget.addItems(curr["echoareas"])
if (len(curr["echoareas"])>0):
self.serversConfig.listWidget.setCurrentRow(0)
self.serversConfig.checkBox.setChecked(curr["xcenable"])
self.serversConfig.checkBox_2.setChecked(curr["advancedue"])
self.serversConfig.checkBox_3.setChecked(curr["pervasiveue"])
self.serversConfig.checkBox_4.setChecked(curr["fetch_enabled"])
self.serversConfig.spinBox.setValue(curr["uelimit"])
self.serversConfig.spinBox_2.setValue(curr["cut_remote_index"])
is_ue_enabled=curr["advancedue"]
self.serversConfig.checkBox_3.setEnabled(is_ue_enabled)
self.serversConfig.spinBox.setEnabled(is_ue_enabled)
def loadInfo_additional(self):
self.additional.comboBox.clear()
self.additional.comboBox_3.clear()
for server in servers:
self.additional.comboBox.addItem(server["adress"])
self.additional.comboBox_3.addItem(server["adress"])
self.additional_update_echoes()
def loadInfo_favorites(self):