-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
467 lines (371 loc) · 18.1 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
import datetime
import platform
import sys
from PyQt5.QtCore import Qt, QSize, pyqtSignal, pyqtSlot
from PyQt5.QtGui import QIcon, QCursor, QCloseEvent, QKeySequence
from PyQt5.QtWidgets import QApplication, QAction, qApp, QMainWindow, QHBoxLayout, QFrame, QSplitter, QVBoxLayout, QMenu, \
QTabWidget, QShortcut
from callback.callbacks import *
from client import client_base
from client.models.messages import Data
from iotools.sql_base import SQLManager, DB_MESSAGING
from iotools.sql_utils import init_databases, save_databases, delete_messages_table_for_dialog, create_messages_table_for_dialog
from iotools.storage import AppStorage
from models.logging import Logger, FileLogChannel
from models.storage import Category
from notifications.notifier import NotificationService
from theming import styles
from theming.theme_loader import ThemeLoader
from tools import full_strip
from widgets.dialogs.dialogs_head import DialogsListHeadWidget
from widgets.message_boxes.basic import ConfirmationMessageBox
from widgets.messages.message_input import MessageInputWidget
from widgets.windows.settings_window import SettingsWindow
main_window = None
settings_window = None
Logger.get_channel("SQL", True).disable()
Logger.set_channel(FileLogChannel("FILE", f"{datetime.datetime.today().strftime('%Y-%m-%d-%H:%M:%S')}.txt"))
general_log = Logger.get_channel("GENERAL", True)
init_databases()
# noinspection PyUnresolvedReferences
class MainWindow(QMainWindow):
new_message_signal = pyqtSignal(Packet, Peer)
@pyqtSlot(Packet, Peer)
def new_message_received_slot(self, packet: Packet, peer: Peer):
new_message_callback(packet, peer, main_window)
def __init__(self):
super().__init__()
self.new_message_signal.connect(self.new_message_received_slot)
self.init_ui()
def init_ui(self):
toggle_listening_action = QAction("Toggle &listening", parent=self)
toggle_listening_action.setCheckable(True)
toggle_listening_action.setChecked(False)
toggle_listening_action.setShortcut('Ctrl+L')
toggle_listening_action.triggered.connect(toggle_listening_callback)
settings_action = QAction("&Settings", parent=self)
settings_action.setShortcut("Ctrl+Shift+S")
settings_action.triggered.connect(self.open_settings)
exit_action = QAction(QIcon('images/exit.png'), '&Quit', self)
exit_action.setShortcut('Ctrl+Q')
exit_action.triggered.connect(qApp.quit)
menu_bar = self.menuBar()
file_menu = menu_bar.addMenu('File')
file_menu.addAction(toggle_listening_action)
file_menu.addAction(settings_action)
file_menu.addAction(exit_action)
self.setStyleSheet(ThemeLoader.loaded_theme.apply_to_stylesheet(styles.main_window_style))
self.setCentralWidget(RootWidget())
self.setGeometry(100, 100, 800, 800)
self.setWindowTitle('Core Messenger')
self.setWindowIcon(QIcon('images/app-icon.png'))
def show(self):
super().show()
if not bool(int(AppStorage.get_settings().get(Category("general", "General"), "save_startup_data").value)):
while 1:
nickname, ok = QInputDialog.getText(self, 'Nickname', 'Enter nickname:')
if ok:
if len(full_strip(nickname)):
break
else:
self.close()
while 1:
port, ok = QInputDialog.getText(self, 'Port', 'Enter listening port:')
port = full_strip(port)
'''
port must me
decimal
less than 655536 (2^16)
not reserved (ftp, ssh, http, https)
needs further improvement (port checking)
'''
if ok:
if len(port) \
and port.isdecimal() \
and int(port) < 65536 \
and int(port) not in (21, 22, 80, 443):
break
else:
self.close()
else:
nickname = AppStorage.get_storage().get("nickname")
port = int(AppStorage.get_storage().get("port"))
client_base.nickname = nickname
general_log.log('nickname: {}'.format(nickname))
client_base.local_port = int(port)
general_log.log('listening port: {}'.format(port))
AppStorage.get_storage().set("nickname", nickname)
AppStorage.get_storage().set("port", port)
client_base.init_socket()
client_base.new_message_callback = lambda message, peer: self.new_message_signal.emit(message, peer)
client_base.invalid_message_callback = invalid_message_callback
@staticmethod
def open_settings():
settings_window.show()
def closeEvent(self, a0: QCloseEvent):
client_base.finish()
class RootWidget(QWidget):
def __init__(self):
super().__init__()
self.splitter = QSplitter(Qt.Horizontal)
self.opened_dialog_frame = OpenedDialogWidget()
self.dialogs_list_frame = DialogsListRootWidget()
self.init_ui()
def init_ui(self):
layout = QHBoxLayout(self)
self.setStyleSheet(ThemeLoader.loaded_theme.apply_to_stylesheet(styles.main_window_style))
self.dialogs_list_frame.setFrameShape(QFrame.StyledPanel)
self.dialogs_list_frame.setMinimumWidth(200)
self.opened_dialog_frame.setFrameShape(QFrame.StyledPanel)
self.opened_dialog_frame.setMinimumWidth(300)
self.splitter.addWidget(self.dialogs_list_frame)
self.splitter.addWidget(self.opened_dialog_frame)
self.splitter.setCollapsible(0, False)
self.splitter.setCollapsible(1, False)
layout.addWidget(self.splitter)
layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(layout)
# noinspection PyAttributeOutsideInit,PyUnresolvedReferences
class DialogsListRootWidget(QFrame):
def __init__(self):
super().__init__()
self.dialogs_list = QListWidget()
self.incoming_list = QListWidget()
self.head = DialogsListHeadWidget()
self.tabs = QTabWidget()
self.init_ui()
def init_ui(self):
layout = QVBoxLayout()
theme = ThemeLoader.loaded_theme
# shortcuts setup
close_dialog_shortcut = QShortcut(QKeySequence("Esc"), self)
close_dialog_shortcut.activated.connect(lambda: self.close_dialog_event())
close_dialog_shortcut.setEnabled(True)
dialog_up_shortcut = QShortcut(QKeySequence("Alt+Up"), self)
dialog_up_shortcut.activated.connect(lambda: self.open_dialog_above())
dialog_up_shortcut.setEnabled(True)
dialog_down_shortcut = QShortcut(QKeySequence("Alt+Down"), self)
dialog_down_shortcut.activated.connect(lambda: self.open_dialog_below())
dialog_down_shortcut.setEnabled(True)
open_dialogs_shortcut = QShortcut(QKeySequence("Ctrl+Alt+D"), self)
open_dialogs_shortcut.activated.connect(lambda: self.tabs.setCurrentIndex(0))
open_dialogs_shortcut.setEnabled(True)
open_incoming_shortcut = QShortcut(QKeySequence("Ctrl+Alt+I"), self)
open_incoming_shortcut.activated.connect(lambda: self.tabs.setCurrentIndex(1))
open_incoming_shortcut.setEnabled(True)
accept_connection_shortcut = QShortcut(QKeySequence("Ctrl+Shift+A"), self)
accept_connection_shortcut.activated.connect(lambda: self.accept_connection_event(self.incoming_list.currentItem()))
accept_connection_shortcut.setEnabled(True)
decline_connection_shortcut = QShortcut(QKeySequence("Ctrl+Shift+D"), self)
decline_connection_shortcut.activated.connect(lambda: self.decline_connection_event(self.incoming_list.currentItem()))
decline_connection_shortcut.setEnabled(True)
# dialogs list setup
self.dialogs_list.setStyleSheet(theme.apply_to_stylesheet(styles.side_list_style))
self.dialogs_list.setIconSize(QSize(40, 40))
self.dialogs_list.setSelectionMode(QAbstractItemView.SingleSelection)
self.dialogs_list.currentItemChanged.connect(lambda current, previous: dialog_item_changed_callback(current, previous, main_window))
self.dialogs_list.setSpacing(5)
self.dialogs_list.setContextMenuPolicy(Qt.CustomContextMenu)
self.dialogs_list.customContextMenuRequested.connect(self.dialog_context_menu_event)
dialogs = SQLManager.get_instance(DB_MESSAGING).select_all("dialogs")
for item in dialogs:
self.dialogs_list.addItem(DialogItemWidget(item[4], item[0], item[1], item[2], peer_id=item[3]))
# incoming list setup
self.incoming_list.setStyleSheet(theme.apply_to_stylesheet(styles.side_list_style))
self.incoming_list.setContextMenuPolicy(Qt.CustomContextMenu)
self.incoming_list.customContextMenuRequested.connect(self.incoming_context_menu_event)
# tabs setup
self.tabs.setStyleSheet(theme.get_default_for_widget(self.tabs))
self.tabs.addTab(self.dialogs_list, "Dialogs")
self.tabs.addTab(self.incoming_list, "Incoming Connections")
layout.addWidget(self.head)
layout.addWidget(self.tabs)
layout.setContentsMargins(0, 5, 0, 0)
client_base.incoming_connection_callback = lambda address, connection: handle_incoming_connection_callback(self.incoming_list, address)
self.setLayout(layout)
def close_dialog_event(self):
dialog_item_changed_callback(None, self.dialogs_list.currentItem(), main_window)
if self.dialogs_list.currentItem():
self.dialogs_list.currentItem().setSelected(False)
self.dialogs_list.setCurrentRow(-1)
def open_dialog_above(self):
current = self.dialogs_list.currentRow()
if current:
self.dialogs_list.setCurrentRow(current - 1)
def open_dialog_below(self):
current = self.dialogs_list.currentRow()
if current < self.dialogs_list.count() - 1:
self.dialogs_list.setCurrentRow(current + 1)
def dialog_context_menu_event(self, _):
# this is necessary!
# noinspection PyAttributeOutsideInit
self.menu = QMenu(self)
item: DialogItemWidget = self.dialogs_list.currentItem()
if item:
peer_id = item.peer_id
share_info_action = QAction('Share Your Info', self)
share_info_action.triggered.connect(lambda: self.share_info(peer_id))
self.menu.addAction(share_info_action)
if item.chat_type != 2:
request_info_action = QAction('Request Peer Info', self)
request_info_action.triggered.connect(lambda: self.request_info(peer_id))
self.menu.addAction(request_info_action)
clear_history_action = QAction('Clear History', self)
clear_history_action.triggered.connect(lambda: self.clear_history(peer_id))
delete_dialog_action = QAction('Delete Dialog', self)
delete_dialog_action.triggered.connect(lambda: self.delete_dialog(item))
self.menu.addAction(clear_history_action)
self.menu.addAction(delete_dialog_action)
if peer_id in client_base.peers.keys():
disconnect_action = QAction('Disconnect', self)
disconnect_action.triggered.connect(lambda: self.disconnect_from_peer(item))
self.menu.addAction(disconnect_action)
else:
reconnect_action = QAction('Reconnect', self)
reconnect_action.triggered.connect(lambda: self.reconnect_to_peer(item))
self.menu.addAction(reconnect_action)
# add other required actions
self.menu.popup(QCursor.pos())
def incoming_context_menu_event(self, _):
item = self.incoming_list.currentItem()
if item:
# noinspection PyAttributeOutsideInit
self.menu = QMenu(self)
accept_action = QAction("Accept", self)
accept_action.triggered.connect(lambda: self.accept_connection_event(item))
decline_action = QAction("Decline", self)
decline_action.triggered.connect(lambda: self.decline_connection_event(item))
self.menu.addAction(accept_action)
self.menu.addAction(decline_action)
self.menu.popup(QCursor.pos())
def accept_connection_event(self, item):
address = (item.text().split(":")[0], int(item.text().split(":")[1]))
accept_incoming_connection(self, address)
def decline_connection_event(self, item):
address = (item.text().split(":")[0], int(item.text().split(":")[1]))
decline_incoming_connection(self, address)
@staticmethod
def disconnect_from_peer(dialog):
client_base.send_message(
dialog.peer_id,
Packet(
action=DisconnectAction(),
message=Message()
)
)
client_base.disconnect(Peer(dialog.host, dialog.port, dialog.peer_id))
@staticmethod
def reconnect_to_peer(dialog):
if dialog.chat_type == 0:
client_base.p2p_connect(dialog.host, dialog.port, peer_id_override=dialog.peer_id)
client_base.send_message(
dialog.peer_id,
Packet(
action=ConnectAction(),
message=Message(),
data=Data()
)
)
else:
client_base.server_connect(dialog.host, dialog.port, peer_id_override=dialog.peer_id)
def delete_dialog(self, dialog):
result = ConfirmationMessageBox("Delete dialog? This cannot be undone.").exec_()
if result == QMessageBox.Yes:
delete_dialog_callback(dialog.peer_id, dialog.host, dialog.port)
self.dialogs_list.takeItem(self.dialogs_list.row(dialog))
def clear_history(self, peer_id):
result = ConfirmationMessageBox("Clear history? This cannot be undone.").exec_()
if result == QMessageBox.Yes:
self.parentWidget().parentWidget().opened_dialog_frame.messages_list.clear()
delete_messages_table_for_dialog(peer_id)
create_messages_table_for_dialog(peer_id)
@staticmethod
def send_info(peer_id: str, request: bool = False):
client_base.send_message(peer_id, Packet(
message=Message(text=""),
action=PeerInfoAction(),
data=Data(content={
"nickname": client_base.nickname,
"port": client_base.local_port,
"request": request
})
))
def share_info(self, peer_id):
self.send_info(peer_id)
def request_info(self, peer_id):
self.send_info(peer_id, True)
# noinspection PyUnresolvedReferences
class OpenedDialogWidget(QFrame):
def __init__(self):
super().__init__()
self.splitter = QSplitter(Qt.Vertical)
self.message_input = MessageInputWidget()
self.messages_list = QListWidget()
self.init_ui()
def init_ui(self):
layout = QVBoxLayout()
self.messages_list.setStyleSheet(ThemeLoader.loaded_theme.apply_to_stylesheet(styles.messages_list))
self.messages_list.setSpacing(1)
self.messages_list.showMinimized()
self.messages_list.setWordWrap(True)
self.messages_list.setContextMenuPolicy(Qt.CustomContextMenu)
self.messages_list.customContextMenuRequested.connect(self.message_context_menu_event)
self.message_input.setMinimumHeight(50)
self.message_input.setMaximumHeight(100)
self.splitter.addWidget(self.messages_list)
self.splitter.addWidget(self.message_input)
layout.addWidget(self.splitter)
layout.setContentsMargins(0, 0, 0, 0)
self.splitter.setContentsMargins(0, 0, 0, 0)
self.setLayout(layout)
def message_context_menu_event(self, _):
message_item: QListWidgetItem = self.messages_list.currentItem()
if message_item:
message_widget: MessageItemWidget = self.messages_list.itemWidget(message_item)
# same thing
# noinspection PyAttributeOutsideInit
self.menu = QMenu(self)
reply_action = QAction('Reply', self)
forward_action = QAction('Forward', self)
delete_action = QAction('Delete', self)
delete_action.triggered.connect(lambda: delete_message_item_selected_callback(self.messages_list, message_item))
self.menu.addAction(reply_action)
self.menu.addAction(forward_action)
if message_widget.message.mine:
edit_action = QAction('Edit', self)
edit_action.triggered.connect(lambda: edit_message_item_selected_callback(self, message_widget))
self.menu.addAction(edit_action)
self.menu.addAction(delete_action)
# add other required actions
self.menu.popup(QCursor.pos())
def excepthook(exctype, value, tb):
import traceback
Logger.get_channel("FILE").log(str(value))
Logger.get_channel("FILE").log(''.join(traceback.format_tb(tb)))
sys.__excepthook__(exctype, value, traceback)
if __name__ == '__main__':
sys.excepthook = excepthook
if platform.system() == "Windows":
import ctypes
win_app_id = 'arterialist.core_messenger'
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(win_app_id)
ThemeLoader.load_from_file(
AppStorage.get_settings().get(
Category("ui", "User Interface"),
"theme_file_path"
).value)
app = QApplication(sys.argv)
main_window = MainWindow()
settings_window = SettingsWindow()
main_window.show()
NotificationService() # init
# noinspection PyBroadException
try:
sys.exit(app.exec_())
finally:
save_databases(AppStorage.get_settings(), AppStorage.get_storage())
current_item = main_window.centralWidget().dialogs_list_frame.dialogs_list.currentItem()
if current_item:
message_input = main_window.centralWidget().opened_dialog_frame.message_input.message_input
save_draft(current_item.peer_id, full_strip(message_input.toPlainText()))
client_base.finish()