-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathmscolab.py
2176 lines (1954 loc) · 97.6 KB
/
mscolab.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
# -*- coding: utf-8 -*-
"""
mslib.msui.mscolab
~~~~~~~~~~~~~~~~~~~~~~~~~
Window to display authentication and operation details for mscolab
To better understand of the code, look at the 'ships' example from
chapter 14/16 of 'Rapid GUI Programming with Python and Qt: The
Definitive Guide to PyQt Programming' (Mark Summerfield).
This file is part of MSS.
:copyright: Copyright 2019- Shivashis Padhi
:copyright: Copyright 2019-2024 by the MSS team, see AUTHORS.
:license: APACHE-2.0, see LICENSE for details.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import sys
import json
import hashlib
import logging
import types
import fs
import requests
import re
import webbrowser
import urllib.request
from urllib.parse import urljoin
from fs import open_fs
from PIL import Image
from keyring.errors import NoKeyringError, PasswordSetError, InitError
from mslib.msui import flighttrack as ft
from mslib.msui import mscolab_chat as mc
from mslib.msui import mscolab_admin_window as maw
from mslib.msui import mscolab_version_history as mvh
from mslib.msui import socket_control as sc
import PyQt5
from PyQt5 import QtCore, QtGui, QtWidgets
from mslib.utils.auth import get_password_from_keyring, save_password_to_keyring
from mslib.utils.verify_user_token import verify_user_token
from mslib.utils.verify_waypoint_data import verify_waypoint_data
from mslib.utils.qt import get_open_filename, get_save_filename, dropEvent, dragEnterEvent, show_popup
from mslib.msui.qt5 import ui_mscolab_help_dialog as msc_help_dialog
from mslib.msui.qt5 import ui_add_operation_dialog as add_operation_ui
from mslib.msui.qt5 import ui_mscolab_merge_waypoints_dialog as merge_wp_ui
from mslib.msui.qt5 import ui_mscolab_connect_dialog as ui_conn
from mslib.msui.qt5 import ui_mscolab_profile_dialog as ui_profile
from mslib.msui.qt5 import ui_operation_archive as ui_opar
from mslib.msui import constants
from mslib.utils.config import config_loader, modify_config_file
class MSColab_OperationArchiveBrowser(QtWidgets.QDialog, ui_opar.Ui_OperationArchiveBrowser):
def __init__(self, parent=None, mscolab=None):
super().__init__(parent)
self.setupUi(self)
self.parent = parent
self.mscolab = mscolab
self.pbClose.clicked.connect(self.hide)
self.pbUnarchiveOperation.setEnabled(False)
self.pbUnarchiveOperation.clicked.connect(self.unarchive_operation)
self.listArchivedOperations.itemClicked.connect(self.select_archived_operation)
self.setModal(True)
def select_archived_operation(self, item):
logging.debug('select_inactive_operation')
if item.access_level == "creator":
self.archived_op_id = item.op_id
self.pbUnarchiveOperation.setEnabled(True)
else:
self.archived_op_id = None
self.pbUnarchiveOperation.setEnabled(False)
def unarchive_operation(self):
logging.debug('unarchive_operation')
if verify_user_token(self.mscolab.mscolab_server_url, self.mscolab.token):
# set last used date for operation
data = {
"token": self.mscolab.token,
"op_id": self.archived_op_id,
}
url = urljoin(self.mscolab.mscolab_server_url, 'set_last_used')
try:
res = requests.post(url, data=data, timeout=tuple(config_loader(dataset="MSCOLAB_timeout")))
except requests.exceptions.RequestException as e:
logging.debug(e)
show_popup(self.parent, "Error", "Some error occurred! Could not unarchive operation.")
else:
if res.text != "False":
res = res.json()
if res["success"]:
self.mscolab.reload_operations()
else:
show_popup(self.parent, "Error", "Some error occurred! Could not activate operation")
else:
show_popup(self.parent, "Error", "Session expired, new login required")
self.mscolab.logout()
else:
show_popup(self.ui, "Error", "Your Connection is expired. New Login required!")
self.mscolab.logout()
class MSColab_ConnectDialog(QtWidgets.QDialog, ui_conn.Ui_MSColabConnectDialog):
"""MSColab connect window class. Provides user interface elements to connect/disconnect,
login, add new user to an MSColab Server. Also implements HTTP Server Authentication prompt.
"""
def __init__(self, parent=None, mscolab=None):
"""
Arguments:
parent -- Qt widget that is parent to this widget.
"""
super().__init__(parent)
self.setupUi(self)
self.parent = parent
self.mscolab = mscolab
# initialize server url as none
self.mscolab_server_url = None
self.auth = None
self.setFixedSize(self.size())
self.stackedWidget.setCurrentWidget(self.httpAuthPage)
# disable widgets in login frame
self.loginEmailLe.setEnabled(False)
self.loginPasswordLe.setEnabled(False)
self.loginBtn.setEnabled(False)
self.addUserBtn.setEnabled(False)
# add urls from settings to the combobox
self.add_mscolab_urls()
self.mscolab_url_changed(self.urlCb.currentText())
# connect login, adduser, connect, login with idp, auth token submit buttons
self.connectBtn.clicked.connect(self.connect_handler)
self.connectBtn.setFocus()
self.disconnectBtn.clicked.connect(self.disconnect_handler)
self.disconnectBtn.hide()
self.loginBtn.clicked.connect(self.login_handler)
self.loginWithIDPBtn.clicked.connect(self.idp_login_handler)
self.idpAuthTokenSubmitBtn.clicked.connect(self.idp_auth_token_submit_handler)
self.addUserBtn.clicked.connect(lambda: self.stackedWidget.setCurrentWidget(self.newuserPage))
# enable login button only if email and password are entered
self.loginEmailLe.textChanged[str].connect(self.mscolab_login_changed)
self.loginPasswordLe.textChanged[str].connect(self.enable_login_btn)
self.urlCb.editTextChanged.connect(self.mscolab_url_changed)
# connect new user dialogbutton
self.newUserBb.accepted.connect(self.new_user_handler)
self.newUserBb.rejected.connect(lambda: self.stackedWidget.setCurrentWidget(self.loginPage))
# connecting slot to clear all input widgets while switching tabs
self.stackedWidget.currentChanged.connect(self.page_switched)
def mscolab_url_changed(self, text):
self.httpPasswordLe.setText(
get_password_from_keyring("MSCOLAB_AUTH_" + text, config_loader(dataset="MSCOLAB_auth_user_name")))
def mscolab_login_changed(self, text):
self.loginPasswordLe.setText(
get_password_from_keyring(self.mscolab_server_url, text))
def page_switched(self, index):
# clear all text in add user widget
self.newUsernameLe.setText("")
self.newEmailLe.setText("")
self.newPasswordLe.setText("")
self.newConfirmPasswordLe.setText("")
def set_status(self, _type="Error", msg=""):
if _type == "Error":
msg = "⚠ " + msg
self.statusLabel.setOpenExternalLinks(True)
self.statusLabel.setStyleSheet("color: red;")
elif _type == "Success":
self.statusLabel.setStyleSheet("color: green;")
msg = "✓ " + msg
else:
self.statusLabel.setStyleSheet("")
msg = "ⓘ " + msg
self.statusLabel.setText(msg)
logging.debug("set_status: %s", msg)
QtWidgets.QApplication.processEvents()
def add_mscolab_urls(self):
url_list = config_loader(dataset="default_MSCOLAB")
combo_box_urls = [self.urlCb.itemText(_i) for _i in range(self.urlCb.count())]
for url in (_url for _url in url_list if _url not in combo_box_urls):
self.urlCb.addItem(url)
def enable_login_btn(self):
self.loginBtn.setEnabled(self.loginEmailLe.text() != "" and self.loginPasswordLe.text() != "")
def connect_handler(self):
try:
url = str(self.urlCb.currentText())
auth = config_loader(dataset="MSCOLAB_auth_user_name"), self.httpPasswordLe.text()
s = requests.Session()
s.auth = auth
s.headers.update({'x-test': 'true'})
r = s.get(urljoin(url, 'status'), timeout=tuple(tuple(config_loader(dataset="MSCOLAB_timeout"))))
if r.status_code == 401:
self.set_status("Error", 'Server authentication data were incorrect.')
elif r.status_code == 200:
self.stackedWidget.setCurrentWidget(self.loginPage)
self.set_status("Success", "Successfully connected to MSColab server.")
# disable url input
self.urlCb.setEnabled(False)
# enable/disable appropriate widgets in login frame
self.loginBtn.setEnabled(False)
self.addUserBtn.setEnabled(True)
self.loginEmailLe.setEnabled(True)
self.loginPasswordLe.setEnabled(True)
try:
idp_enabled = json.loads(r.text)["use_saml2"]
except (json.decoder.JSONDecodeError, KeyError):
idp_enabled = False
try:
direct_login = json.loads(r.text)["direct_login"]
except (json.decoder.JSONDecodeError, KeyError):
direct_login = True
if not direct_login:
# Hide user creation when this is disabled on the server
self.addUserBtn.setHidden(True)
self.clickNewUserLabel.setHidden(True)
if not idp_enabled:
# Hide login by identity provider if IDP login disabled
self.loginWithIDPBtn.setHidden(True)
self.mscolab_server_url = url
self.auth = auth
save_password_to_keyring("MSCOLAB_AUTH_" + url, auth[0], auth[1])
url_list = config_loader(dataset="default_MSCOLAB")
if self.mscolab_server_url not in url_list:
ret = PyQt5.QtWidgets.QMessageBox.question(
self, self.tr("Update Server List"),
self.tr("You are using a new MSColab server. "
"Should your settings file be updated by adding the new server?"),
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)
if ret == QtWidgets.QMessageBox.Yes:
url_list = [self.mscolab_server_url] + url_list
modify_config_file({"default_MSCOLAB": url_list})
# Fill Email and Password fields from config
self.loginEmailLe.setText(
config_loader(dataset="MSS_auth").get(self.mscolab_server_url))
self.mscolab_login_changed(self.loginEmailLe.text())
self.enable_login_btn()
self.loginBtn.setFocus()
# Change connect button text and connect disconnect handler
self.connectBtn.hide()
self.disconnectBtn.show()
else:
logging.error("Error %s", r)
self.set_status("Error", "Some unexpected error occurred. Please try again.")
except requests.exceptions.SSLError:
logging.debug("Certificate Verification Failed")
self.set_status("Error", "Certificate Verification Failed.")
except requests.exceptions.InvalidSchema:
logging.debug("invalid schema of url")
self.set_status("Error", "Invalid Url Scheme.")
except requests.exceptions.InvalidURL:
logging.debug("invalid url")
self.set_status("Error", "Invalid URL.")
except requests.exceptions.ConnectionError:
logging.debug("MSColab server isn't active")
self.set_status("Error", "MSColab server isn't active.")
except Exception as e:
logging.error("Error %s %s", type(e), str(e))
self.set_status("Error", "Some unexpected error occurred. Please try again.")
def disconnect_handler(self):
self.urlCb.setEnabled(True)
# enable/disable appropriate widgets in login frame
self.loginBtn.setEnabled(False)
self.addUserBtn.setEnabled(False)
self.loginEmailLe.setEnabled(False)
self.loginPasswordLe.setEnabled(False)
# clear text
self.stackedWidget.setCurrentWidget(self.httpAuthPage)
self.mscolab_server_url = None
self.auth = None
self.connectBtn.show()
self.connectBtn.setFocus()
self.disconnectBtn.hide()
self.set_status("Info", 'Disconnected from server.')
def login_handler(self):
data = {
"email": self.loginEmailLe.text(),
"password": self.loginPasswordLe.text()
}
s = requests.Session()
s.auth = self.auth
s.headers.update({'x-test': 'true'})
url = urljoin(self.mscolab_server_url, "token")
url_recover_password = urljoin(self.mscolab_server_url, "reset_request")
try:
r = s.post(url, data=data, timeout=tuple(config_loader(dataset="MSCOLAB_timeout")))
if r.status_code == 401:
raise requests.exceptions.ConnectionError
except requests.exceptions.RequestException as ex:
logging.error("unexpected error: %s %s %s", type(ex), url, ex)
self.set_status(
"Error",
f'Failed to establish a new connection to "{self.mscolab_server_url}". Try again in a moment.',
)
self.disconnect_handler()
return
if r.text == "False":
# show status indicating about wrong credentials
self.set_status("Error", 'Invalid credentials. Fix them, create a new user, or '
f'<a href="{url_recover_password}">recover your password</a>.')
else:
self.save_user_credentials_to_config_file(data["email"], data["password"])
self.mscolab.after_login(data["email"], self.mscolab_server_url, r)
def idp_login_handler(self):
"""Handle IDP login Button"""
url_idp_login = urljoin(self.mscolab_server_url, "available_idps")
webbrowser.open(url_idp_login, new=2)
self.stackedWidget.setCurrentWidget(self.idpAuthPage)
def idp_auth_token_submit_handler(self):
"""Handle IDP authentication token submission"""
url_idp_login_auth = urljoin(self.mscolab_server_url, "idp_login_auth")
user_token = self.idpAuthPasswordLe.text()
try:
data = {'token': user_token}
response = requests.post(url_idp_login_auth, json=data, timeout=(2, 10))
if response.status_code == 401:
self.set_status("Error", 'Invalid token or token expired. Please try again')
self.stackedWidget.setCurrentWidget(self.loginPage)
elif response.status_code == 200:
_json = json.loads(response.text)
token = _json["token"]
user = _json["user"]
data = {
"email": user["emailid"],
"password": token,
}
s = requests.Session()
s.auth = self.auth
s.headers.update({'x-test': 'true'})
url = urljoin(self.mscolab_server_url, "token")
r = s.post(url, data=data, timeout=(2, 10))
if r.status_code == 401:
raise requests.exceptions.ConnectionError
if r.text == "False":
# show status indicating about wrong credentials
self.set_status("Error", 'Invalid token. Please enter correct token')
else:
self.mscolab.after_login(data["email"], self.mscolab_server_url, r)
self.set_status("Success", 'Succesfully logged into mscolab server')
except requests.exceptions.RequestException as error:
logging.error("unexpected error: %s %s %s", type(error), url, error)
def save_user_credentials_to_config_file(self, emailid, password):
try:
save_password_to_keyring(service_name=self.mscolab_server_url, username=emailid, password=password)
except (NoKeyringError, PasswordSetError, InitError) as ex:
logging.warning("Can't use Keyring on your system: %s" % ex)
mss_auth = config_loader(dataset="MSS_auth")
if mss_auth.get(self.mscolab_server_url) != emailid:
ret = QtWidgets.QMessageBox.question(
self, self.tr("Update Credentials"),
self.tr("You are using new credentials. "
"Should your settings file be updated with the new credentials?"),
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)
if ret == QtWidgets.QMessageBox.Yes:
mss_auth[self.mscolab_server_url] = emailid
modify_config_file({"MSS_auth": mss_auth})
def new_user_handler(self):
# get mscolab /token http auth credentials from cache
emailid = self.newEmailLe.text()
password = self.newPasswordLe.text()
re_password = self.newConfirmPasswordLe.text()
username = self.newUsernameLe.text()
if password != re_password:
self.set_status("Error", 'Your passwords don\'t match.')
return
data = {
"email": emailid,
"password": password,
"username": username
}
s = requests.Session()
s.auth = self.auth
s.headers.update({'x-test': 'true'})
url = urljoin(self.mscolab_server_url, "register")
try:
r = s.post(url, data=data, timeout=tuple(config_loader(dataset="MSCOLAB_timeout")))
except requests.exceptions.RequestException as ex:
logging.error("unexpected error: %s %s %s", type(ex), url, ex)
self.set_status(
"Error",
f'Failed to establish a new connection to "{self.mscolab_server_url}". Try again in a moment.',
)
self.disconnect_handler()
return
if r.status_code == 204:
self.set_status("Success", 'You are registered, confirm your email before logging in.')
self.save_user_credentials_to_config_file(emailid, password)
self.stackedWidget.setCurrentWidget(self.loginPage)
self.loginEmailLe.setText(emailid)
self.loginPasswordLe.setText(password)
elif r.status_code == 201:
self.set_status("Success", 'You are registered.')
self.save_user_credentials_to_config_file(emailid, password)
self.loginEmailLe.setText(emailid)
self.loginPasswordLe.setText(password)
self.login_handler()
else:
try:
error_msg = json.loads(r.text)["message"]
except Exception as e:
logging.debug("Unexpected error occurred %s", e)
error_msg = "Unexpected error occurred. Please try again."
self.set_status("Error", error_msg)
class MSUIMscolab(QtCore.QObject):
"""
Class for implementing MSColab functionalities
"""
name = "Mscolab"
signal_unarchive_operation = QtCore.pyqtSignal(int, name="signal_unarchive_operation")
signal_operation_added = QtCore.pyqtSignal(int, str, name="signal_operation_added")
signal_operation_removed = QtCore.pyqtSignal(int, name="signal_operation_removed")
signal_login_mscolab = QtCore.pyqtSignal(str, str, name="signal_login_mscolab")
signal_logout_mscolab = QtCore.pyqtSignal(name="signal_logout_mscolab")
signal_listFlighttrack_doubleClicked = QtCore.pyqtSignal()
signal_permission_revoked = QtCore.pyqtSignal(int)
signal_render_new_permission = QtCore.pyqtSignal(int, str)
def __init__(self, parent=None, data_dir=None):
super().__init__(parent)
self.ui = parent
self.operation_archive_browser = MSColab_OperationArchiveBrowser(self.ui, self)
self.operation_archive_browser.hide()
self.ui.listInactiveOperationsMSC = self.operation_archive_browser.listArchivedOperations
# connect mscolab help action from help menu
self.ui.actionMSColabHelp.triggered.connect(self.open_help_dialog)
self.ui.pbOpenOperationArchive.clicked.connect(self.open_operation_archive)
# hide mscolab related widgets
self.ui.usernameLabel.hide()
self.ui.userOptionsTb.hide()
self.ui.actionAddOperation.setEnabled(False)
self.ui.activeOperationDesc.setHidden(True)
self.hide_operation_options()
# reset operation description label for flight tracks and open views
self.ui.listFlightTracks.itemDoubleClicked.connect(self.listFlighttrack_itemDoubleClicked)
self.ui.listViews.itemDoubleClicked.connect(
lambda: self.ui.activeOperationDesc.setText("Select Operation to View Description."))
# connect operation options menu actions
self.ui.actionAddOperation.triggered.connect(self.add_operation_handler)
self.ui.actionChat.triggered.connect(self.operation_options_handler)
self.ui.actionVersionHistory.triggered.connect(self.operation_options_handler)
self.ui.actionManageUsers.triggered.connect(self.operation_options_handler)
self.ui.actionDeleteOperation.triggered.connect(self.operation_options_handler)
self.ui.actionLeaveOperation.triggered.connect(self.operation_options_handler)
self.ui.actionChangeCategory.triggered.connect(self.change_category_handler)
self.ui.actionChangeDescription.triggered.connect(self.change_description_handler)
self.ui.actionRenameOperation.triggered.connect(self.rename_operation_handler)
self.ui.actionArchiveOperation.triggered.connect(self.archive_operation)
self.ui.actionViewDescription.triggered.connect(self.view_description)
self.ui.filterCategoryCb.currentIndexChanged.connect(self.operation_category_handler)
# connect slot for handling operation options combobox
self.ui.workLocallyCheckbox.stateChanged.connect(self.handle_work_locally_toggle)
self.ui.serverOptionsCb.currentIndexChanged.connect(self.server_options_handler)
# set up user menu and add to toolbutton
self.user_menu = QtWidgets.QMenu()
self.profile_action = self.user_menu.addAction("Profile", self.open_profile_window)
self.user_menu.addSeparator()
self.logout_action = self.user_menu.addAction("Logout", self.logout)
self.ui.userOptionsTb.setPopupMode(QtWidgets.QToolButton.InstantPopup)
self.ui.userOptionsTb.setMenu(self.user_menu)
# self.ui.userOptionsTb.setAutoRaise(True)
# self.ui.userOptionsTb.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
# if token is None, not authorized, else authorized
self.token = None
# int to store new pid
self.new_op_id = None
# int to store active pid
self.active_op_id = None
# storing access_level to save network call
self.access_level = None
# storing operation_name to save network call
self.active_operation_name = None
# storing operation category to save network call
self.active_operation_category = None
# Storing operation list to pass to admin window
self.operations = None
# store active_flight_path here as object
self.waypoints_model = None
# Store active operation's file path
self.local_ftml_file = None
# Store active_operation_description
self.active_operation_description = None
# connection object to interact with sockets
self.conn = None
# operation window
self.chat_window = None
# Admin Window
self.admin_window = None
# Version History Window
self.version_window = None
# Merge waypoints dialog
self.merge_dialog = None
# Mscolab help dialog
self.help_dialog = None
# Profile dialog
self.prof_diag = None
# Mscolab Server URL
self.mscolab_server_url = None
# User email
self.email = None
# Display all categories by default
self.selected_category = "*ANY*"
# Gravatar image path
self.gravatar = None
# set data dir, uri
if data_dir is None:
self.data_dir = config_loader(dataset="mss_dir")
else:
self.data_dir = data_dir
self.create_dir()
def view_description(self):
data = {
"token": self.token,
"op_id": self.active_op_id
}
url = urljoin(self.mscolab_server_url, "creator_of_operation")
r = requests.get(url, data=data, timeout=tuple(config_loader(dataset="MSCOLAB_timeout")))
creator_name = "unknown"
if r.text != "False":
_json = json.loads(r.text)
creator_name = _json["username"]
QtWidgets.QMessageBox.information(
self.ui, "Operation Description",
f"<html>Creator: <b>{creator_name}</b><p>"
f"Category: <b>{self.active_operation_category}</b><p>"
"<p>"
f"{self.active_operation_description}</html>")
def open_operation_archive(self):
self.operation_archive_browser.show()
def create_dir(self):
# ToDo this needs to be done earlier
if '://' in self.data_dir:
try:
_ = fs.open_fs(self.data_dir)
except fs.errors.CreateFailed:
logging.error('Make sure that the FS url "%s" exists', self.data_dir)
show_popup(self.ui, "Error", f'FS Url: "{self.data_dir}" does not exist!')
sys.exit()
except fs.opener.errors.UnsupportedProtocol:
logging.error('FS url "%s" not supported', self.data_dir)
show_popup(self.ui, "Error", f'FS Url: "{self.data_dir}" not supported!')
sys.exit()
else:
_dir = os.path.expanduser(self.data_dir)
if not os.path.exists(_dir):
os.makedirs(_dir)
def close_help_dialog(self):
self.help_dialog = None
def open_help_dialog(self):
if self.help_dialog is not None:
self.help_dialog.raise_()
self.help_dialog.activateWindow()
else:
self.help_dialog = MscolabHelpDialog(self.ui)
self.help_dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.help_dialog.destroyed.connect(self.close_help_dialog)
self.help_dialog.show()
def open_connect_window(self):
self.connect_window = MSColab_ConnectDialog(parent=self.ui, mscolab=self)
self.connect_window.setModal(True)
self.connect_window.exec_()
def after_login(self, emailid, url, r):
logging.debug("after login %s %s", emailid, url)
# emailid by direct call
self.email = emailid
self.connect_window.close()
self.connect_window = None
QtWidgets.QApplication.processEvents()
# fill value of mscolab url if found in QSettings storage
_json = json.loads(r.text)
self.token = _json["token"]
self.user = _json["user"]
self.mscolab_server_url = url
# create socket connection here
try:
self.conn = sc.ConnectionManager(self.token, user=self.user, mscolab_server_url=self.mscolab_server_url)
except Exception as ex:
logging.debug("Couldn't create a socket connection: %s", ex)
show_popup(self.ui, "Error", "Couldn't create a socket connection. Maybe the MSColab server is too old. "
"New Login required!")
self.logout()
else:
self.conn.signal_operation_list_updated.connect(self.reload_operation_list)
self.conn.signal_reload.connect(self.reload_window)
self.conn.signal_new_permission.connect(self.render_new_permission)
self.conn.signal_update_permission.connect(self.handle_update_permission)
self.conn.signal_revoke_permission.connect(self.handle_revoke_permission)
self.conn.signal_operation_deleted.connect(self.handle_operation_deleted)
self.ui.connectBtn.hide()
self.ui.openOperationsGb.show()
# display connection status
transport_layer = self.conn.sio.transport()
self.ui.mscStatusLabel.setText(self.ui.tr(
f"Status: connected to '{self.mscolab_server_url}' by transport layer '{transport_layer}'"))
# display username beside useroptions toolbutton
self.ui.usernameLabel.setText(f"{self.user['username']}")
self.ui.usernameLabel.show()
self.ui.userOptionsTb.show()
self.fetch_gravatar()
# enable add operation menu action
self.ui.actionAddOperation.setEnabled(True)
# Populate open operations list
ops = self.add_operations_to_ui()
# Show category list
self.show_categories_to_ui(ops)
self.ui.activeOperationDesc.setHidden(False)
self.ui.actionChangeCategory.setEnabled(False)
self.ui.actionChangeDescription.setEnabled(False)
self.ui.actionDeleteOperation.setEnabled(False)
self.ui.filterCategoryCb.setEnabled(True)
self.ui.actionViewDescription.setEnabled(False)
self.signal_login_mscolab.emit(self.mscolab_server_url, self.token)
def fetch_gravatar(self, refresh=False):
email_hash = hashlib.md5(bytes(self.email.encode('utf-8')).lower()).hexdigest()
email_in_config = self.email in config_loader(dataset="gravatar_ids")
gravatar_img_path = fs.path.join(constants.GRAVATAR_DIR_PATH, f"{email_hash}.png")
config_fs = fs.open_fs(constants.MSUI_CONFIG_PATH)
# refresh is used to fetch new gravatar associated with the email
if refresh or email_in_config:
# create directory to store cached gravatar images
if not config_fs.exists("gravatars"):
try:
config_fs.makedirs("gravatars")
except fs.errors.CreateFailed:
logging.error('Creation of gravatar directory failed')
return
except fs.opener.errors.UnsupportedProtocol:
logging.error('FS url not supported')
return
# use cached image if refresh not requested
if not refresh and email_in_config and \
config_fs.exists(fs.path.join("gravatars", f"{email_hash}.png")):
self.set_gravatar(gravatar_img_path)
return
# fetch gravatar image
gravatar_url = f"https://www.gravatar.com/avatar/{email_hash}.png?s=80&d=404"
try:
urllib.request.urlretrieve(gravatar_url, gravatar_img_path)
img = Image.open(gravatar_img_path)
img.save(gravatar_img_path)
except urllib.error.HTTPError:
if refresh:
show_popup(self.prof_diag, "Error", "Gravatar not found")
return
except urllib.error.URLError:
if refresh:
show_popup(self.prof_diag, "Error", "Could not fetch Gravatar")
return
if refresh and not email_in_config:
show_popup(
self.prof_diag,
"Information",
"Please add your email to the gravatar_ids section in your "
"msui_settings.json to automatically fetch your gravatar",
icon=1, )
self.set_gravatar(gravatar_img_path)
def set_gravatar(self, gravatar=None):
self.gravatar = gravatar
pixmap = QtGui.QPixmap(self.gravatar)
# check if pixmap has correct image
if pixmap.isNull():
user_name = self.user["username"]
try:
# find the first alphabet in the user name to set appropriate gravatar
first_alphabet = user_name[user_name.find(next(filter(str.isalpha, user_name)))].lower()
except StopIteration:
# fallback to default gravatar logo if no alphabets found in the user name
first_alphabet = "default"
pixmap = QtGui.QPixmap(f":/gravatars/default-gravatars/{first_alphabet}.png")
self.gravatar = None
icon = QtGui.QIcon()
icon.addPixmap(pixmap, QtGui.QIcon.Normal, QtGui.QIcon.Off)
# set icon for user options toolbutton
self.ui.userOptionsTb.setIcon(icon)
# set icon for profile window
if self.prof_diag is not None:
self.profile_dialog.gravatarLabel.setPixmap(pixmap)
def remove_gravatar(self):
if self.gravatar is None:
return
# remove cached gravatar image if not found in config
config_fs = fs.open_fs(constants.MSUI_CONFIG_PATH)
if config_fs.exists("gravatars"):
if fs.open_fs(constants.GRAVATAR_DIR_PATH).exists(fs.path.basename(self.gravatar)):
fs.open_fs(constants.GRAVATAR_DIR_PATH).remove(fs.path.basename(self.gravatar))
if self.email in config_loader(dataset="gravatar_ids"):
show_popup(
self.prof_diag,
"Information",
"Please remove your email from gravatar_ids section in your "
"msui_settings.json to not fetch gravatar automatically",
icon=1, )
self.set_gravatar()
def open_profile_window(self):
def on_context_menu(point):
self.gravatar_menu.exec_(self.profile_dialog.gravatarLabel.mapToGlobal(point))
self.prof_diag = QtWidgets.QDialog()
self.profile_dialog = ui_profile.Ui_ProfileWindow()
self.profile_dialog.setupUi(self.prof_diag)
self.profile_dialog.buttonBox.accepted.connect(lambda: self.prof_diag.close())
self.profile_dialog.usernameLabel_2.setText(self.user['username'])
self.profile_dialog.mscolabURLLabel_2.setText(self.mscolab_server_url)
self.profile_dialog.emailLabel_2.setText(self.email)
self.profile_dialog.deleteAccountBtn.clicked.connect(self.delete_account)
# add context menu for right click on image
self.gravatar_menu = QtWidgets.QMenu()
self.gravatar_menu.addAction('Fetch Gravatar', lambda: self.fetch_gravatar(refresh=True))
self.gravatar_menu.addAction('Remove Gravatar', lambda: self.remove_gravatar())
self.profile_dialog.gravatarLabel.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.profile_dialog.gravatarLabel.customContextMenuRequested.connect(on_context_menu)
self.prof_diag.show()
self.fetch_gravatar()
def delete_account(self):
# ToDo rename to delete_own_account
if verify_user_token(self.mscolab_server_url, self.token):
w = QtWidgets.QWidget()
qm = QtWidgets.QMessageBox
reply = qm.question(w, self.tr('Continue?'),
self.tr("You're about to delete your account. You cannot undo this operation!"),
qm.Yes, qm.No)
if reply == QtWidgets.QMessageBox.No:
return
data = {
"token": self.token
}
try:
url = urljoin(self.mscolab_server_url, "delete_own_account")
r = requests.post(url, data=data,
timeout=tuple(config_loader(dataset="MSCOLAB_timeout")))
except requests.exceptions.RequestException as e:
logging.error(e)
show_popup(self.ui, "Error", "Some error occurred! Please reconnect.")
self.logout()
else:
if r.status_code == 200 and json.loads(r.text)["success"] is True:
self.logout()
else:
show_popup(self, "Error", "Your Connection is expired. New Login required!")
self.logout()
def add_operation_handler(self):
if verify_user_token(self.mscolab_server_url, self.token):
def check_and_enable_operation_accept():
if (self.add_proj_dialog.path.text() != "" and
self.add_proj_dialog.description.toPlainText() != "" and
self.add_proj_dialog.category.text() != ""):
self.add_proj_dialog.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True)
else:
self.add_proj_dialog.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
def browse():
import_type = self.add_proj_dialog.cb_ImportType.currentText()
file_type = ["Flight track (*.ftml)"]
if import_type != 'FTML':
file_type = [f"Flight track (*.{self.ui.import_plugins[import_type][1]})"]
file_path = get_open_filename(
self.ui, "Open Flighttrack file", "", ';;'.join(file_type))
if file_path is not None:
file_name = fs.path.basename(file_path)
if file_path.endswith('ftml'):
with open_fs(fs.path.dirname(file_path)) as file_dir:
file_content = file_dir.readtext(file_name)
else:
function = self.ui.import_plugins[import_type][0]
ft_name, waypoints = function(file_path)
model = ft.WaypointsTableModel(waypoints=waypoints)
xml_doc = model.get_xml_doc()
file_content = xml_doc.toprettyxml(indent=" ", newl="\n")
self.add_proj_dialog.f_content = file_content
self.add_proj_dialog.selectedFile.setText(file_name)
self.proj_diag = QtWidgets.QDialog()
self.add_proj_dialog = add_operation_ui.Ui_addOperationDialog()
self.add_proj_dialog.setupUi(self.proj_diag)
self.add_proj_dialog.f_content = None
self.add_proj_dialog.buttonBox.accepted.connect(self.add_operation)
self.add_proj_dialog.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
self.add_proj_dialog.path.textChanged.connect(check_and_enable_operation_accept)
self.add_proj_dialog.description.textChanged.connect(check_and_enable_operation_accept)
self.add_proj_dialog.category.textChanged.connect(check_and_enable_operation_accept)
self.add_proj_dialog.browse.clicked.connect(browse)
self.add_proj_dialog.category.setText(config_loader(dataset="MSCOLAB_category"))
# sets types from defined import menu
import_menu = self.ui.menuImportFlightTrack
for im_action in import_menu.actions():
self.add_proj_dialog.cb_ImportType.addItem(im_action.text())
self.proj_diag.show()
else:
show_popup(self.ui, "Error", "Your Connection is expired. New Login required!")
self.logout()
def add_operation(self):
logging.debug("add_operation")
path = self.add_proj_dialog.path.text()
description = self.add_proj_dialog.description.toPlainText()
category = self.add_proj_dialog.category.text()
if not path:
self.error_dialog = QtWidgets.QErrorMessage()
self.error_dialog.showMessage('Path can\'t be empty')
return
elif not description:
self.error_dialog = QtWidgets.QErrorMessage()
self.error_dialog.showMessage('Description can\'t be empty')
return
# same regex as for path validation
elif not re.match("^[a-zA-Z0-9_-]*$", category):
self.error_dialog = QtWidgets.QErrorMessage()
self.error_dialog.showMessage('Category can\'t contain spaces or special characters')
return
# regex checks if the whole path from beginning to end only contains alphanumerical characters or _ and -
elif not re.match("^[a-zA-Z0-9_-]*$", path):
self.error_dialog = QtWidgets.QErrorMessage()
self.error_dialog.showMessage('Path can\'t contain spaces or special characters')
return
data = {
"token": self.token,
"path": path,
"description": description,
"category": category
}
if self.add_proj_dialog.f_content is not None:
data["content"] = self.add_proj_dialog.f_content
try:
url = urljoin(self.mscolab_server_url, "create_operation")
r = requests.post(url, data=data,
timeout=tuple(config_loader(dataset="MSCOLAB_timeout")))
except requests.exceptions.RequestException as e:
logging.error(e)
show_popup(self.ui, "Error", "Some error occurred! Please reconnect.")
self.logout()
else:
if r.text == "True":
QtWidgets.QMessageBox.information(
self.ui,
"Creation successful",
"Your operation was created successfully.",
)
op_id = self.get_recent_op_id()
self.new_op_id = op_id
self.conn.handle_new_operation(op_id)
self.signal_operation_added.emit(op_id, path)
else:
self.error_dialog = QtWidgets.QErrorMessage()
self.error_dialog.showMessage('The path already exists')
def get_recent_op_id(self):
logging.debug('get_recent_op_id')
if verify_user_token(self.mscolab_server_url, self.token):
"""
get most recent operation's op_id
"""
skip_archived = config_loader(dataset="MSCOLAB_skip_archived_operations")
data = {
"token": self.token,
"skip_archived": skip_archived
}
url = urljoin(self.mscolab_server_url, "operations")
r = requests.get(url, data=data)
if r.text != "False":
_json = json.loads(r.text)
operations = _json["operations"]
op_id = None
if operations:
op_id = operations[-1]["op_id"]
logging.debug("recent op_id %s", op_id)
return op_id
else:
show_popup(self.ui, "Error", "Session expired, new login required")
self.signal_logout_mscolab()
else:
show_popup(self.ui, "Error", "Your Connection is expired. New Login required!")
self.logout()
def operation_options_handler(self):
if self.sender() == self.ui.actionChat:
self.open_chat_window()
elif self.sender() == self.ui.actionVersionHistory:
self.open_version_history_window()
elif self.sender() == self.ui.actionManageUsers:
self.open_admin_window()
elif self.sender() == self.ui.actionDeleteOperation:
self.handle_delete_operation()
elif self.sender() == self.ui.actionLeaveOperation:
self.handle_leave_operation()
def open_chat_window(self):
if verify_user_token(self.mscolab_server_url, self.token):
if self.active_op_id is None:
return
if self.chat_window is not None:
self.chat_window.activateWindow()
return
self.chat_window = mc.MSColabChatWindow(
self.token,