This repository was archived by the owner on Mar 1, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathWorkspaceView.py
2941 lines (2480 loc) · 110 KB
/
WorkspaceView.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
# ***********************************************************************
# * *
# * Copyright (c) 2023 Ondsel *
# * *
# ***********************************************************************
import os
from datetime import datetime
import re
import json
import shutil
import requests
import uuid
import base64
import webbrowser
import random
import math
from inspect import cleandoc
import jwt
from jwt.exceptions import ExpiredSignatureError
import handlers
from PySide import QtCore, QtGui, QtWidgets
from PySide.QtGui import QStandardItemModel
import FreeCAD
import FreeCADGui
import AddonManager
import Utils
from DataModels import (
WorkspaceListModel,
CACHE_PATH,
getBookmarkModel,
ROLE_TYPE,
TYPE_ORG,
TYPE_BOOKMARK,
ROLE_SHARE_MODEL_ID,
)
from VersionModel import OndselVersionModel
from LinkModel import ShareLinkModel
from APIClient import (
APIClient,
APIClientException,
APIClientAuthenticationException,
ConnStatus,
APICallResult,
fancy_handle,
)
from Workspace import (
WorkspaceModel,
ServerWorkspaceModel,
FileStatus,
)
from markdown import markdown_to_html
from views.ondsel_promotions_view import OndselPromotionsView
from views.public_shares_view import PublicSharesView
from views.search_results_view import SearchResultsView
from components.choose_download_action_dialog import ChooseDownloadActionDialog
from PySide.QtGui import (
QStyledItemDelegate,
QStyle,
QMessageBox,
QApplication,
QIcon,
QAction,
QActionGroup,
QMenu,
QSizePolicy,
QPixmap,
)
from PySide.QtCore import QByteArray
from PySide.QtWidgets import QTreeView
from WorkspaceListDelegate import WorkspaceListDelegate
from Utils import wait_cursor
logger = Utils.getLogger(__name__)
MAX_LENGTH_BASE_FILENAME = 30
MAX_LENGTH_WORKSPACE_NAME = 33
ELLIPSES = "..."
MAX_INT32 = (1 << 31) - 1
CONFIG_PATH = FreeCAD.getUserConfigDir()
FILENAME_USER_CFG = "user.cfg"
FILENAME_SYS_CFG = "system.cfg"
PREFIX_PARAM_ROOT = "/Root/"
IDX_TAB_WORKSPACES = 0
IDX_TAB_ONDSEL_START = 1
IDX_TAB_BOOKMARKS = 2
IDX_TAB_SEARCH = 3
IDX_TAB_PUBLIC_SHARES = 4
PATH_BOOKMARKS = Utils.joinPath(CACHE_PATH, "bookmarks")
INTERVAL_TIMER_MS = 60000
INTERVAL_TOOLBAR_TIMER_MS = 500
p = Utils.get_param_group()
remote_changelog_url = (
"https://github.com/Ondsel-Development/Ondsel-Lens-Addon/blob/main/changeLog.md"
)
remote_package_url = (
"https://raw.githubusercontent.com/Ondsel-Development/"
"Ondsel-Lens-Addon/main/package.xml"
)
consumed_args_main_app = False
class ParseException(Exception):
def __init__(self, message):
super().__init__(message)
class UpdateManager:
def storePreferences(self):
pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons")
self.autocheck = pref.GetBool("AutoCheck")
self.statusSelection = pref.GetInt("StatusSelection")
self.packageTypeSelection = pref.GetInt("PackageTypeSelection")
self.searchString = pref.GetString("SearchString")
def setCustomPreferences(self):
pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons")
pref.SetBool("AutoCheck", True)
pref.SetInt("StatusSelection", 3)
pref.SetInt("PackageTypeSelection", 1)
pref.SetString("SearchString", "Ondsel Lens")
def restorePreferences(self):
pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons")
pref.SetBool("AutoCheck", self.autocheck)
pref.SetInt("StatusSelection", self.statusSelection)
pref.SetInt("PackageTypeSelection", self.packageTypeSelection)
pref.SetString("SearchString", self.searchString)
def openAddonManager(self, finishFunction):
"""Open the addon manager with custom preferences."""
self.storePreferences()
self.setCustomPreferences()
addonManager = AddonManager.CommandAddonManager()
addonManager.finished.connect(finishFunction)
addonManager.Activated()
# Simple delegate drawing an icon and text
class FileListDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
# Get the data for the current index
if not index.isValid():
return
fileName, status, isFolder = index.data(
WorkspaceModel.NameStatusAndIsFolderRole
)
if option.state & QStyle.State_Selected:
painter.fillRect(option.rect, option.palette.highlight())
icon_rect = QtCore.QRect(option.rect.left(), option.rect.top(), 16, 16)
text_rect = QtCore.QRect(
option.rect.left() + 20,
option.rect.top(),
option.rect.width() - 20,
option.rect.height(),
)
if isFolder:
icon = QtGui.QIcon.fromTheme("back", QtGui.QIcon(":/icons/folder.svg"))
else:
icon = QtGui.QIcon.fromTheme(
"back", QtGui.QIcon(":/icons/document-new.svg")
)
icon.paint(painter, icon_rect)
textToDisplay = renderFileName(fileName)
if status:
textToDisplay += " (" + str(status) + ")"
fontMetrics = painter.fontMetrics()
elidedText = fontMetrics.elidedText(
textToDisplay, QtGui.Qt.ElideRight, option.rect.width()
)
painter.drawText(text_rect, QtCore.Qt.AlignLeft, elidedText)
def renderFileName(fileName):
base, extension = os.path.splitext(fileName)
if len(base) > MAX_LENGTH_BASE_FILENAME:
lengthSuffix = 5
lengthEllipses = len(ELLIPSES)
lengthPrefix = MAX_LENGTH_BASE_FILENAME - lengthSuffix - lengthEllipses
return base[:lengthPrefix] + ELLIPSES + base[-lengthSuffix:] + extension
else:
return fileName
class LinkListDelegate(QStyledItemDelegate):
iconShareClicked = QtCore.Signal(QtCore.QModelIndex)
iconEditClicked = QtCore.Signal(QtCore.QModelIndex)
iconDeleteClicked = QtCore.Signal(QtCore.QModelIndex)
def paint(self, painter, option, index):
if not index.isValid():
return
name = index.data(QtCore.Qt.DisplayRole)
if option.state & QStyle.State_Selected:
painter.fillRect(option.rect, option.palette.highlight())
icon_copy_rect = QtCore.QRect(
option.rect.right() - 60, option.rect.top(), 16, 16
)
icon_edit_rect = QtCore.QRect(
option.rect.right() - 40, option.rect.top(), 16, 16
)
icon_delete_rect = QtCore.QRect(
option.rect.right() - 20, option.rect.top(), 16, 16
)
text_rect = QtCore.QRect(
option.rect.left() + 4,
option.rect.top(),
option.rect.width() - 60,
option.rect.height(),
)
icon_copy = QtGui.QIcon.fromTheme("back", QtGui.QIcon(":/icons/edit-copy.svg"))
icon_edit = QtGui.QIcon.fromTheme(
"back", QtGui.QIcon(":/icons/Std_DlgParameter.svg")
)
icon_delete = QtGui.QIcon.fromTheme(
"back", QtGui.QIcon(":/icons/edit_Cancel.svg")
)
icon_copy.paint(painter, icon_copy_rect)
icon_edit.paint(painter, icon_edit_rect)
icon_delete.paint(painter, icon_delete_rect)
painter.drawText(text_rect, QtCore.Qt.AlignLeft, name)
def editorEvent(self, event, model, option, index):
if not index.isValid():
return False
if (
event.type() == QtCore.QEvent.MouseButtonPress
and event.button() == QtCore.Qt.LeftButton
):
icon_share_rect = QtCore.QRect(
option.rect.right() - 60, option.rect.top(), 16, 16
)
icon_edit_rect = QtCore.QRect(
option.rect.right() - 40, option.rect.top(), 16, 16
)
icon_delete_rect = QtCore.QRect(
option.rect.right() - 20, option.rect.top(), 16, 16
)
if icon_share_rect.contains(event.pos()):
self.iconShareClicked.emit(index)
return True
elif icon_edit_rect.contains(event.pos()):
self.iconEditClicked.emit(index)
return True
elif icon_delete_rect.contains(event.pos()):
self.iconDeleteClicked.emit(index)
return True
# If the click wasn't on any icon, select the item as normal
return super().editorEvent(event, model, option, index)
class BookmarkView(QTreeView):
def drawBranches(self, painter, rect, index):
pass
class BookmarkDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super().__init__(parent)
def createEditor(self, parent, option, index):
return None
def paint(self, painter, option, index):
type = index.data(ROLE_TYPE)
if type == TYPE_ORG:
name = index.data(QtCore.Qt.DisplayRole)
# Mimick the workspaces list for consistency
name_font = painter.font()
name_font.setBold(True)
# Draw the name
name_rect = QtCore.QRect(
option.rect.left() + 20,
option.rect.top() + 10,
option.rect.width() - 20,
option.rect.height() // 2,
)
painter.setFont(name_font)
painter.drawText(
name_rect,
QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter,
name,
)
else:
super().paint(painter, option, index)
def sizeHint(self, option, index):
type = index.data(ROLE_TYPE)
if type == TYPE_ORG:
return QtCore.QSize(100, 40) # Adjust the desired width and height
else:
return super().sizeHint(option, index)
class WorkspaceView(QtWidgets.QScrollArea):
def __init__(self, mw):
super(WorkspaceView, self).__init__(mw)
self.current_workspace = None
self.currentWorkspaceModel = None
self.toolBarItemAction = None
self.fileToolBar = None
self.setObjectName("workspaceView")
self.form = FreeCADGui.PySideUic.loadUi(f"{Utils.mod_path}/WorkspaceView.ui")
self.initialize_tabs()
self.setWidget(self.form)
self.setWindowTitle("Ondsel Lens")
self.createOndselButtonMenus()
self.ondselIcon = QIcon(Utils.icon_path + "OndselWorkbench.svg")
self.ondselIconDisconnected = QIcon(
Utils.icon_path + "OndselWorkbench-disconnected.svg"
)
self.ondselIconLoggedOut = QIcon(
Utils.icon_path + "OndselWorkbench-loggedout.svg"
)
self.form.userBtn.setIconSize(QtCore.QSize(32, 32))
self.form.userBtn.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
self.form.userBtn.clicked.connect(self.form.userBtn.showMenu)
self.form.backToStartBtn.hide()
self.form.buttonBack.clicked.connect(self.backClicked)
self.set_anonymous_client()
self.workspacesModel = WorkspaceListModel(api=self.api)
self.workspacesDelegate = WorkspaceListDelegate(self)
self.form.workspaceListView.setModel(self.workspacesModel)
self.form.workspaceListView.setItemDelegate(self.workspacesDelegate)
self.form.workspaceListView.doubleClicked.connect(self.enterWorkspace)
self.form.workspaceListView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.form.workspaceListView.customContextMenuRequested.connect(
self.showWorkspaceContextMenu
)
self.workspacesModel.rowsInserted.connect(self.switchView)
self.workspacesModel.rowsRemoved.connect(self.switchView)
self.filesDelegate = FileListDelegate(self)
self.form.fileList.setItemDelegate(self.filesDelegate)
self.form.fileList.doubleClicked.connect(self.fileListDoubleClicked)
self.form.fileList.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.form.fileList.customContextMenuRequested.connect(self.showFileContextMenu)
self.form.fileList.clicked.connect(self.fileListClicked)
self.form.versionsComboBox.activated.connect(self.versionClicked)
self.linksDelegate = LinkListDelegate(self)
self.linksDelegate.iconShareClicked.connect(self.shareShareLinkClicked)
self.linksDelegate.iconEditClicked.connect(self.editShareLinkClicked)
self.linksDelegate.iconDeleteClicked.connect(self.deleteShareLinkClicked)
self.form.linksView.setItemDelegate(self.linksDelegate)
self.form.linksView.doubleClicked.connect(self.linksListDoubleClicked)
self.form.linksView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.form.linksView.customContextMenuRequested.connect(
self.showLinksContextMenu
)
self.form.addLinkBtn.clicked.connect(self.addShareLink)
addFileMenu = QtGui.QMenu(self.form.addFileBtn)
addFileAction = QtGui.QAction("Add current file", self.form.addFileBtn)
addFileAction.triggered.connect(self.addCurrentFile)
addFileMenu.addAction(addFileAction)
addFileAction2 = QtGui.QAction("Select files...", self.form.addFileBtn)
addFileAction2.triggered.connect(self.addSelectedFiles)
addFileMenu.addAction(addFileAction2)
addFileAction3 = QtGui.QAction("Add a directory", self.form.addFileBtn)
addFileAction3.triggered.connect(self.addDir)
addFileMenu.addAction(addFileAction3)
self.form.addFileBtn.setMenu(addFileMenu)
self.form.viewOnlineBtn.clicked.connect(self.openModelOnline)
self.form.makeActiveBtn.clicked.connect(self.makeActive)
self.form.fileDetails.setVisible(False)
explainText = cleandoc(
"""
<h1 style="text-align:center; font-weight:bold;">Welcome</h1>
<p>You're not currently logged in to the Ondsel service. Use the button
above to log in or create an account. When you log in, this space will
show your workspaces.
</p>
<p>You can enter the workspaces by double-clicking them.</p>
<p>Each workspace is a collection of files. Think of it like a project.</p>
"""
)
self.form.txtExplain.setHtml(explainText)
self.form.txtExplain.setReadOnly(True)
self.form.txtExplain.hide()
with wait_cursor():
# initialize ondsel-start tab
self.initializeOndselStart()
# initialize bookmarks tab
self.initializeBookmarks()
# initialize search tab
self.form.searchResultScrollArea = SearchResultsView(self)
self.form.searchResultFrame.layout().addWidget(
self.form.searchResultScrollArea
)
# initialize public-shares tab
# We are only loading the public shares if the user clicks on the
# tab. In that case we initialize it only once.
self.initialized_public_shares = False
self.initializeUpdateLens()
self.try_login()
self.switchView()
self.workspacesModel.refreshModel()
# Set a timer to check regularly the server
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.timerTick)
self.timer.setInterval(INTERVAL_TIMER_MS)
self.timer.start()
self.handle_request(self.check_for_update)
def initialize_tabs(self):
tabWidget = self.form.tabWidget
tabBar = tabWidget.tabBar()
# workspaces
wsIcon = QtGui.QIcon(Utils.icon_path + "folder-multiple-outline.svg")
tabBar.setTabIcon(IDX_TAB_WORKSPACES, wsIcon)
tabWidget.setTabToolTip(
IDX_TAB_WORKSPACES,
"Explore and create 3D CAD designs in your Lens workspaces",
)
# Ondsel start
wsIcon = QtGui.QIcon(Utils.icon_path + "play-outline.svg")
tabBar.setTabIcon(IDX_TAB_ONDSEL_START, wsIcon)
tabWidget.setTabToolTip(
IDX_TAB_ONDSEL_START,
"Explore users, workspaces, and share links curated by Ondsel",
)
# Bookmarks
bookmarkIcon = QtGui.QIcon(Utils.icon_path + "bookmark-outline.svg")
tabBar.setTabIcon(IDX_TAB_BOOKMARKS, bookmarkIcon)
tabWidget.setTabToolTip(IDX_TAB_BOOKMARKS, "Explore your Lens bookmarks")
searchIcon = QtGui.QIcon(Utils.icon_path + "search.svg")
tabBar.setTabIcon(IDX_TAB_SEARCH, searchIcon)
tabWidget.setTabToolTip(
IDX_TAB_SEARCH,
"Search for users, workspaces, organizations, and share links",
)
publicIcon = QtGui.QIcon(Utils.icon_path + "dots-square.svg")
tabBar.setTabIcon(IDX_TAB_PUBLIC_SHARES, publicIcon)
tabWidget.setTabToolTip(IDX_TAB_PUBLIC_SHARES, "Explore public share links")
def initializeOndselStart(self):
self.form.ondselStartStatusLabel.setText("loading content...")
self.form.ondselPromotionsScrollArea = OndselPromotionsView(self)
html = "unable to retrieve"
org = self.form.ondselPromotionsScrollArea.ondsel_org
if org is not None:
markdown = org["curation"]["longDescriptionMd"]
html = markdown_to_html(markdown)
self.form.ondselHomePageTextBrowser.setHtml(html)
self.form.ondselPromotionsFrame.layout().addWidget(
self.form.ondselPromotionsScrollArea
)
def initializeBookmarks(self):
tabWidget = self.form.tabWidget
self.form.bookmarkStatusLabel = QtGui.QLabel("No bookmarks")
self.form.tabBookmarks.layout().addWidget(self.form.bookmarkStatusLabel)
self.form.viewBookmarks = BookmarkView(tabWidget)
bookmarkView = self.form.viewBookmarks
self.form.tabBookmarks.layout().addWidget(bookmarkView)
tabWidget.currentChanged.connect(self.onTabChanged)
bookmarkView.setRootIsDecorated(False)
bookmarkView.setToolTip("Bookmarks per organization")
bookmarkView.setExpandsOnDoubleClick(False)
bookmarkView.header().hide()
bookmarkView.setItemDelegate(BookmarkDelegate())
bookmarkView.doubleClicked.connect(self.bookmarkDoubleClicked)
bookmarkView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
def initializePublicShares(self):
if not self.initialized_public_shares:
self.form.publicSharesStatusLabel.setText("loading content...")
self.form.publicSharesScrollArea = PublicSharesView(self)
self.form.publicSharesFrame.layout().addWidget(
self.form.publicSharesScrollArea
)
self.initialized_public_shares = True
def initializeUpdateLens(self):
self.form.frameUpdate.hide()
self.form.updateBtn.clicked.connect(self.openAddonManager)
def openAddonManager(self):
self.updateManager = UpdateManager()
self.updateManager.openAddonManager(self.addonManagerFinished)
def addonManagerFinished(self):
self.updateManager.restorePreferences()
self.UpdateManager = None
# def generate_expired_token(self):
# # generate an expired token for testing
# # Set expiration time to 5 minutes ago
# expiration_time = datetime.now() - timedelta(minutes=5)
# payload = {
# "exp": expiration_time.timestamp(),
# # Add other claims as needed
# }
# secret_key = "your_secret_key" # Replace with your secret key
# token = jwt.encode(payload, secret_key, algorithm="HS256")
# return token
def createOndselButtonMenus(self):
# Ondsel Button's menu when logged in
self.userMenu = QMenu(self.form.userBtn)
userActions = QActionGroup(self.userMenu)
a = QAction("Visit Ondsel Lens", userActions)
a.triggered.connect(self.ondselAccount)
self.userMenu.addAction(a)
# self.synchronizeAction = QAction("Synchronize", userActions)
# self.synchronizeAction.setVisible(False)
# self.userMenu.addAction(self.synchronizeAction)
# Prefer to do this in the dashboard
# self.newWorkspaceAction = QAction("Add new workspace", userActions)
# self.newWorkspaceAction.triggered.connect(self.newWorkspaceBtnClicked)
# self.userMenu.addAction(self.newWorkspaceAction)
# Settings
submenuSettings = QMenu("Settings", self.userMenu)
clearCacheAction = QAction("Clear Cache on logout", submenuSettings)
clearCacheAction.setCheckable(True)
clearCacheAction.setChecked(p.GetBool("clearCache", False))
clearCacheAction.triggered.connect(lambda state: p.SetBool("clearCache", state))
submenuSettings.addAction(clearCacheAction)
self.userMenu.addMenu(submenuSettings)
submenuPrefs = QMenu("Preferences", self.userMenu)
downloadOnselPrefsAction = QAction(
"Download Ondsel ES default preferences", submenuPrefs
)
downloadOnselPrefsAction.setEnabled(FreeCAD.ConfigGet("ExeVendor") == "Ondsel")
downloadOnselPrefsAction.triggered.connect(self.downloadOndselDefaultPrefs)
submenuPrefs.addAction(downloadOnselPrefsAction)
self.userMenu.addMenu(submenuPrefs)
a4 = QAction("Log out", userActions)
a4.triggered.connect(self.logout)
self.userMenu.addAction(a4)
# Ondsel Button's menu when user not logged in
self.guestMenu = QMenu(self.form.userBtn)
guestActions = QActionGroup(self.guestMenu)
a5 = QAction("Login", guestActions)
a5.triggered.connect(self.login_btn_clicked)
self.guestMenu.addAction(a5)
a6 = QAction("Sign up", guestActions)
a6.triggered.connect(self.showOndselSignUpPage)
self.guestMenu.addAction(a6)
# self.guestMenu.addAction(self.newWorkspaceAction)
# ####
# Authentication
# ####
def is_logged_in(self):
"""Whether a user is logged in.
The user may be disconnected.
"""
return self.api is not None and self.api.is_logged_in()
def is_connected(self):
"""Whether a user is connected.
This implies that the user is logged in.
"""
return self.api is not None and self.api.is_connected()
def set_anonymous_client(self):
self.api = APIClient(
self,
"",
"",
Utils.env.api_url,
Utils.env.lens_url,
Utils.get_source_api_request(),
Utils.get_version_source_api_request(),
None,
None,
)
def get_login_data(self):
login_data_str = p.GetString("loginData", "")
if login_data_str != "":
login_data = json.loads(login_data_str)
return login_data
return {}
def try_login(self):
# Check if user is already logged in.
login_data = self.get_login_data()
if login_data:
access_token = login_data["accessToken"]
# access_token = self.generate_expired_token()
if self.is_token_expired(access_token):
self.logout()
else:
user = login_data["user"]
self.api = APIClient(
self,
"",
"",
Utils.env.api_url,
Utils.env.lens_url,
Utils.get_source_api_request(),
Utils.get_version_source_api_request(),
access_token,
user,
)
# do not forget to set the API for the workspacesModel
self.workspacesModel.set_api(self.api)
# Set a timer to logout when token expires.
# we know that the token is not expired
self.set_token_expiration_timer(access_token)
# verify the status
self.api.getStatus()
self.set_ui_connectionStatus()
def login_btn_clicked(self):
while True:
# Show a login dialog to get the user's email and password
dialog = LoginDialog()
if dialog.exec() == QtGui.QDialog.Accepted:
email, password = dialog.get_credentials()
try:
self.api = APIClient(
self,
email,
password,
Utils.env.api_url,
Utils.env.lens_url,
Utils.get_source_api_request(),
Utils.get_version_source_api_request(),
)
self.set_ui_connectionStatus()
# do not forget to set the API for the workspacesModel
self.workspacesModel.set_api(self.api)
self.api.authenticate()
except APIClientAuthenticationException as e:
logger.warn(e)
continue # Present the login dialog again if authentication fails
except APIClientException as e:
logger.error(e)
self.set_anonymous_client()
self.workspacesModel.set_api(None)
break
# Check if the request was successful (201 status code)
if self.api.access_token is not None:
loginData = {
"accessToken": self.api.access_token,
"user": self.api.user,
}
p.SetString("loginData", json.dumps(loginData))
self.set_ui_connectionStatus()
self.leaveWorkspace()
self.workspacesModel.refreshModel()
self.switchView()
# Set a timer to logout when token expires. since we've
# just received the access token, it is very unlikely that
# it is expired.
self.set_token_expiration_timer(self.api.access_token)
else:
logger.warn("Authentication failed")
break
else:
break # Exit the login loop if the dialog is canceled
self.set_ui_connectionStatus()
def disconnect(self):
self.api.disconnect()
self.set_ui_connectionStatus()
if self.currentWorkspaceModel:
self.setWorkspaceModel()
self.hideFileDetails()
def logout(self):
p.SetString("loginData", "")
self.api.logout()
self.set_ui_connectionStatus()
if self.currentWorkspaceModel:
self.setWorkspaceModel()
self.hideFileDetails()
self.hideBookmarks()
if p.GetBool("clearCache", False):
shutil.rmtree(CACHE_PATH)
self.current_workspace = None
self.currentWorkspaceModel = None
self.form.fileList.setModel(None)
self.workspacesModel.removeWorkspaces()
self.switchView()
self.form.workspaceNameLabel.setText("")
self.form.fileDetails.setVisible(False)
def is_token_expired(self, token):
try:
expiration_time = self.get_token_expiration_time(token)
except ExpiredSignatureError:
return True
current_time = datetime.now()
return current_time > expiration_time
def set_token_expiration_timer(self, token):
# Should be called when there is no risk for an expired signature
# However, the code still handles the error gracefully.
try:
expiration_time = self.get_token_expiration_time(token)
current_time = datetime.now()
time_difference = expiration_time - current_time
interval_milliseconds = max(0, time_difference.total_seconds() * 1000)
if interval_milliseconds < MAX_INT32:
# Create a QTimer that triggers only once when the token is expired
self.token_timer = QtCore.QTimer()
self.token_timer.setSingleShot(True)
self.token_timer.timeout.connect(self.token_expired_handler)
self.token_timer.start(interval_milliseconds)
except ExpiredSignatureError as e:
# unexpected
self.logout()
self.set_ui_connectionStatus()
logger.error(e)
def token_expired_handler(self):
QMessageBox.information(
None,
"Token Expired",
"Your authentication token has expired, you have been logged out.",
)
self.logout()
def get_token_expiration_time(self, token):
"""Get a token expiration time.
Should be called only when we assume that the token is not expired.
Otherwise we log out and raise the exception again. In case another
exception happens, we do the same.
"""
try:
decoded_token = jwt.decode(
token,
audience="lens.ondsel.com",
options={"verify_signature": False, "verify_aud": False},
)
except ExpiredSignatureError as e:
raise e
except Exception as e:
self.logout()
self.set_ui_connectionStatus()
logger.error(e)
raise e
return datetime.fromtimestamp(decoded_token["exp"])
def get_status_name_menu_and_icon(self):
status = self.api.status
status_txt = "Starting Up"
name = self.api.getNameUser()
menu = self.guestMenu
icon = self.ondselIconDisconnected
if self.toolBarItemAction is None:
self.find_our_toolbaritem_action()
if status == ConnStatus.CONNECTED or status == ConnStatus.DISCONNECTED:
menu = self.userMenu
login_data = self.get_login_data()
user = login_data.get("user", {})
users_name = user.get("name", "?")
users_username = user.get("username", "?")
if status == ConnStatus.CONNECTED:
icon = self.ondselIcon
status_txt = (
f"Logged in as {users_name} [<code>{users_username}</code>]"
)
elif status == ConnStatus.DISCONNECTED:
status_txt = "No Network Service"
icon = self.ondselIconDisconnected
elif status == ConnStatus.LOGGED_OUT:
icon = self.ondselIconLoggedOut
status_txt = "Logged Out"
return status, status_txt, name, menu, icon
def set_ui_connectionStatus(self):
status, status_txt, name, menu, icon = self.get_status_name_menu_and_icon()
if self.toolBarItemAction is not None:
tool_tip = (
"<p style='white-space:pre; margin-bottom:0.5em;'>"
" <b>Ondsel Lens Addon</b> (Ctrl+L)</p>"
"<p style='white-space:pre; margin:0;'>"
" Show the Ondsel Lens Addon in an MDI view.</p>"
f"<p>{status_txt}</p><p style='white-space:pre; margin-top:0.5em;'>"
" <i>OndselLens_OndselLens</i></p>"
)
self.toolBarItemAction.setToolTip(tool_tip)
self.toolBarItemAction.setIcon(icon)
if status is None:
self.form.userBtn.setText("(starting)")
elif status == ConnStatus.LOGGED_OUT:
self.form.userBtn.setText(name) # api says "Local" when logged out
elif status == ConnStatus.CONNECTED:
self.form.userBtn.setText(name)
else: # DISCONNECTED
self.form.userBtn.setText(name + " (disconnected)")
self.form.userBtn.setIcon(icon)
self.form.userBtn.setMenu(menu)
def enterWorkspace(self, index):
logger.debug("entering workspace")
with wait_cursor():
self.current_workspace = self.workspacesModel.data(index)
self.setWorkspaceModel()
def setWorkspaceModel(self):
self.currentWorkspaceModel = ServerWorkspaceModel(
self.current_workspace, apiClient=self.api
)
self.setWorkspaceNameLabel()
self.form.fileList.setModel(self.currentWorkspaceModel)
self.switchView()
def leaveWorkspace(self):
if self.current_workspace is None:
return
# self.newWorkspaceAction.setVisible(True)
# self.synchronizeAction.setVisible(False)
# self.synchronizeAction.triggered.disconnect()
self.current_workspace = None
self.currentWorkspaceModel = None
self.form.fileList.setModel(None)
self.workspacesModel.refreshModel()
self.switchView()
self.form.workspaceNameLabel.setText("")
self.form.fileDetails.setVisible(False)
def switchView(self):
isFileView = self.current_workspace is not None
if isFileView:
self.form.workspaceListView.setVisible(False)
self.form.WorkspaceDetails.setVisible(True)
self.form.fileList.setVisible(True)
self.form.fileList.setSizePolicy(
QSizePolicy.Preferred, QSizePolicy.Expanding
)
else:
self.form.WorkspaceDetails.setVisible(False)
self.form.fileList.setVisible(False)
if self.is_logged_in() and self.workspacesModel.rowCount() == 0:
# the user may be disconnected
self.form.txtExplain.setVisible(True)
else:
self.form.txtExplain.setVisible(False)
self.form.workspaceListView.setVisible(True)
def backClicked(self):
with wait_cursor():
if self.current_workspace is None:
return
subPath = self.currentWorkspaceModel.subPath
if subPath == "":
self.leaveWorkspace()
else:
self.currentWorkspaceModel.openParentFolder()
self.setWorkspaceNameLabel()
self.hideFileDetails()
def handle_request(self, func):
"""Handle a function that raises an exception from requests."""
try:
func()
except requests.exceptions.RequestException as e:
logger.debug(e)
def handle(self, func):
"""Handle a function that raises an APICLientException.
Issue warning/errors and possibly log out the user, making
it still possible to use the addon.
If the user is disconnected before the call, we simply try the call but
ignore any warning if it doesn't succeed. If the call succeeds but we
were not connected, it means we are connected again, so we set the UI
to be connected.
Returns true if the user is disconnected
"""
func()
self.set_ui_connectionStatus()
# connected_before_call = self.is_connected()
# try:
# func()
# if not connected_before_call:
# # since the call succeeds, it may mean we are connected again
# if self.is_connected():
# # check if we are connected right now
# logger.info("The connection to the Lens service is restored.")
# return False
# except APIClientConnectionError as e:
# if connected_before_call:
# if logger.level <= logging.DEBUG:
# logger.warn(e)
# else:
# logger.warn("Disconnected from the Lens service.")
# except APIClientRequestException as e:
# if connected_before_call:
# if logger.level <= logging.DEBUG:
# logger.warn(e)
# else:
# logger.warn("Error encountered from the Lens service.")
# except APIClientAuthenticationException as e:
# logger.warn(e)
# logger.warn("Logging out")
# self.logout()
# except APIClientTierException as e:
# self.show_tier_dialog(str(e))
# except APIClientException as e:
# logger.error("Uncaught exception:")
# logger.error(e)