Account.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import enum
  4. from datetime import datetime
  5. from PyQt6.QtCore import QObject, pyqtSignal, pyqtSlot, pyqtProperty, QTimer, pyqtEnum
  6. from typing import Any, Optional, Dict, TYPE_CHECKING, Callable
  7. from UM.Logger import Logger
  8. from UM.Message import Message
  9. from UM.i18n import i18nCatalog
  10. from cura.OAuth2.AuthorizationService import AuthorizationService
  11. from cura.OAuth2.Models import OAuth2Settings, UserProfile
  12. from cura.UltimakerCloud import UltimakerCloudConstants
  13. if TYPE_CHECKING:
  14. from cura.CuraApplication import CuraApplication
  15. i18n_catalog = i18nCatalog("cura")
  16. class SyncState(enum.IntEnum):
  17. """QML: Cura.AccountSyncState"""
  18. SYNCING = 0
  19. SUCCESS = 1
  20. ERROR = 2
  21. IDLE = 3
  22. class Account(QObject):
  23. """The account API provides a version-proof bridge to use Ultimaker Accounts
  24. Usage:
  25. .. code-block:: python
  26. from cura.API import CuraAPI
  27. api = CuraAPI()
  28. api.account.login()
  29. api.account.logout()
  30. api.account.userProfile # Who is logged in
  31. """
  32. # The interval in which sync services are automatically triggered
  33. SYNC_INTERVAL = 60.0 # seconds
  34. pyqtEnum(SyncState)
  35. loginStateChanged = pyqtSignal(bool)
  36. """Signal emitted when user logged in or out"""
  37. userProfileChanged = pyqtSignal()
  38. """Signal emitted when new account information is available."""
  39. additionalRightsChanged = pyqtSignal("QVariantMap")
  40. """Signal emitted when a users additional rights change"""
  41. accessTokenChanged = pyqtSignal()
  42. syncRequested = pyqtSignal()
  43. """Sync services may connect to this signal to receive sync triggers.
  44. Services should be resilient to receiving a signal while they are still syncing,
  45. either by ignoring subsequent signals or restarting a sync.
  46. See setSyncState() for providing user feedback on the state of your service.
  47. """
  48. lastSyncDateTimeChanged = pyqtSignal()
  49. syncStateChanged = pyqtSignal(int) # because SyncState is an int Enum
  50. manualSyncEnabledChanged = pyqtSignal(bool)
  51. updatePackagesEnabledChanged = pyqtSignal(bool)
  52. CLIENT_SCOPES = "account.user.read drive.backup.read drive.backup.write packages.download " \
  53. "packages.rating.read packages.rating.write connect.cluster.read connect.cluster.write connect.material.write " \
  54. "library.project.read library.project.write cura.printjob.read cura.printjob.write " \
  55. "cura.mesh.read cura.mesh.write"
  56. def __init__(self, application: "CuraApplication", parent = None) -> None:
  57. super().__init__(parent)
  58. self._application = application
  59. self._new_cloud_printers_detected = False
  60. self._error_message: Optional[Message] = None
  61. self._logged_in = False
  62. self._user_profile: Optional[UserProfile] = None
  63. self._additional_rights: Dict[str, Any] = {}
  64. self._sync_state = SyncState.IDLE
  65. self._manual_sync_enabled = False
  66. self._update_packages_enabled = False
  67. self._update_packages_action: Optional[Callable] = None
  68. self._last_sync_str = "-"
  69. self._callback_port = 32118
  70. self._oauth_root = UltimakerCloudConstants.CuraCloudAccountAPIRoot
  71. self._oauth_settings = OAuth2Settings(
  72. OAUTH_SERVER_URL= self._oauth_root,
  73. CALLBACK_PORT=self._callback_port,
  74. CALLBACK_URL="http://localhost:{}/callback".format(self._callback_port),
  75. CLIENT_ID="um----------------------------ultimaker_cura",
  76. CLIENT_SCOPES=self.CLIENT_SCOPES,
  77. AUTH_DATA_PREFERENCE_KEY="general/ultimaker_auth_data",
  78. AUTH_SUCCESS_REDIRECT="{}/app/auth-success".format(self._oauth_root),
  79. AUTH_FAILED_REDIRECT="{}/app/auth-error".format(self._oauth_root)
  80. )
  81. self._authorization_service = AuthorizationService(self._oauth_settings)
  82. # Create a timer for automatic account sync
  83. self._update_timer = QTimer()
  84. self._update_timer.setInterval(int(self.SYNC_INTERVAL * 1000))
  85. # The timer is restarted explicitly after an update was processed. This prevents 2 concurrent updates
  86. self._update_timer.setSingleShot(True)
  87. self._update_timer.timeout.connect(self.sync)
  88. self._sync_services: Dict[str, int] = {}
  89. """contains entries "service_name" : SyncState"""
  90. def initialize(self) -> None:
  91. self._authorization_service.initialize(self._application.getPreferences())
  92. self._authorization_service.onAuthStateChanged.connect(self._onLoginStateChanged)
  93. self._authorization_service.onAuthenticationError.connect(self._onLoginStateChanged)
  94. self._authorization_service.accessTokenChanged.connect(self._onAccessTokenChanged)
  95. self._authorization_service.loadAuthDataFromPreferences()
  96. @pyqtProperty(int, notify=syncStateChanged)
  97. def syncState(self):
  98. return self._sync_state
  99. def setSyncState(self, service_name: str, state: int) -> None:
  100. """ Can be used to register sync services and update account sync states
  101. Contract: A sync service is expected exit syncing state in all cases, within reasonable time
  102. Example: `setSyncState("PluginSyncService", SyncState.SYNCING)`
  103. :param service_name: A unique name for your service, such as `plugins` or `backups`
  104. :param state: One of SyncState
  105. """
  106. prev_state = self._sync_state
  107. self._sync_services[service_name] = state
  108. if any(val == SyncState.SYNCING for val in self._sync_services.values()):
  109. self._sync_state = SyncState.SYNCING
  110. self._setManualSyncEnabled(False)
  111. elif any(val == SyncState.ERROR for val in self._sync_services.values()):
  112. self._sync_state = SyncState.ERROR
  113. self._setManualSyncEnabled(True)
  114. else:
  115. self._sync_state = SyncState.SUCCESS
  116. self._setManualSyncEnabled(False)
  117. if self._sync_state != prev_state:
  118. self.syncStateChanged.emit(self._sync_state)
  119. if self._sync_state == SyncState.SUCCESS:
  120. self._last_sync_str = datetime.now().strftime("%d/%m/%Y %H:%M")
  121. self.lastSyncDateTimeChanged.emit()
  122. if self._sync_state != SyncState.SYNCING:
  123. # schedule new auto update after syncing completed (for whatever reason)
  124. if not self._update_timer.isActive():
  125. self._update_timer.start()
  126. def setUpdatePackagesAction(self, action: Callable) -> None:
  127. """ Set the callback which will be invoked when the user clicks the update packages button
  128. Should be invoked after your service sets the sync state to SYNCING and before setting the
  129. sync state to SUCCESS.
  130. Action will be reset to None when the next sync starts
  131. """
  132. self._update_packages_action = action
  133. self._update_packages_enabled = True
  134. self.updatePackagesEnabledChanged.emit(self._update_packages_enabled)
  135. def _onAccessTokenChanged(self):
  136. self.accessTokenChanged.emit()
  137. @property
  138. def is_staging(self) -> bool:
  139. """Indication whether the given authentication is applied against staging or not."""
  140. return "staging" in self._oauth_root
  141. @pyqtProperty(bool, notify=loginStateChanged)
  142. def isLoggedIn(self) -> bool:
  143. return self._logged_in
  144. def _onLoginStateChanged(self, logged_in: bool = False, error_message: Optional[str] = None) -> None:
  145. if error_message:
  146. if self._error_message:
  147. self._error_message.hide()
  148. Logger.log("w", "Failed to login: %s", error_message)
  149. self._error_message = Message(error_message,
  150. title = i18n_catalog.i18nc("@info:title", "Login failed"),
  151. message_type = Message.MessageType.ERROR)
  152. self._error_message.show()
  153. self._logged_in = False
  154. self.loginStateChanged.emit(False)
  155. if self._update_timer.isActive():
  156. self._update_timer.stop()
  157. return
  158. if self._logged_in != logged_in:
  159. self._logged_in = logged_in
  160. self.loginStateChanged.emit(logged_in)
  161. if logged_in:
  162. self._authorization_service.getUserProfile(self._onProfileChanged)
  163. self._setManualSyncEnabled(False)
  164. self._sync()
  165. else:
  166. if self._update_timer.isActive():
  167. self._update_timer.stop()
  168. def _onProfileChanged(self, profile: Optional[UserProfile]) -> None:
  169. self._user_profile = profile
  170. self.userProfileChanged.emit()
  171. def _sync(self) -> None:
  172. """Signals all sync services to start syncing
  173. This can be considered a forced sync: even when a
  174. sync is currently running, a sync will be requested.
  175. """
  176. self._update_packages_action = None
  177. self._update_packages_enabled = False
  178. self.updatePackagesEnabledChanged.emit(self._update_packages_enabled)
  179. if self._update_timer.isActive():
  180. self._update_timer.stop()
  181. elif self._sync_state == SyncState.SYNCING:
  182. Logger.debug("Starting a new sync while previous sync was not completed")
  183. self.syncRequested.emit()
  184. def _setManualSyncEnabled(self, enabled: bool) -> None:
  185. if self._manual_sync_enabled != enabled:
  186. self._manual_sync_enabled = enabled
  187. self.manualSyncEnabledChanged.emit(enabled)
  188. @pyqtSlot()
  189. @pyqtSlot(bool)
  190. def login(self, force_logout_before_login: bool = False) -> None:
  191. """
  192. Initializes the login process. If the user is logged in already and force_logout_before_login is true, Cura will
  193. logout from the account before initiating the authorization flow. If the user is logged in and
  194. force_logout_before_login is false, the function will return, as there is nothing to do.
  195. :param force_logout_before_login: Optional boolean parameter
  196. :return: None
  197. """
  198. if self._logged_in:
  199. if force_logout_before_login:
  200. self.logout()
  201. else:
  202. # Nothing to do, user already logged in.
  203. return
  204. self._authorization_service.startAuthorizationFlow(force_logout_before_login)
  205. @pyqtProperty(str, notify = userProfileChanged)
  206. def userName(self):
  207. if not self._user_profile:
  208. return ""
  209. return self._user_profile.username
  210. @pyqtProperty(str, notify = userProfileChanged)
  211. def profileImageUrl(self):
  212. if not self._user_profile:
  213. return ""
  214. return self._user_profile.profile_image_url
  215. @pyqtProperty(str, notify=accessTokenChanged)
  216. def accessToken(self) -> Optional[str]:
  217. return self._authorization_service.getAccessToken()
  218. @pyqtProperty("QVariantMap", notify = userProfileChanged)
  219. def userProfile(self) -> Dict[str, Optional[str]]:
  220. """None if no user is logged in otherwise the logged in user as a dict containing containing user_id, username and profile_image_url """
  221. if not self._user_profile:
  222. return {}
  223. return self._user_profile.__dict__
  224. @pyqtProperty(str, notify=lastSyncDateTimeChanged)
  225. def lastSyncDateTime(self) -> str:
  226. return self._last_sync_str
  227. @pyqtProperty(bool, notify=manualSyncEnabledChanged)
  228. def manualSyncEnabled(self) -> bool:
  229. return self._manual_sync_enabled
  230. @pyqtProperty(bool, notify=updatePackagesEnabledChanged)
  231. def updatePackagesEnabled(self) -> bool:
  232. return self._update_packages_enabled
  233. @pyqtSlot()
  234. @pyqtSlot(bool)
  235. def sync(self, user_initiated: bool = False) -> None:
  236. if user_initiated:
  237. self._setManualSyncEnabled(False)
  238. self._sync()
  239. @pyqtSlot()
  240. def onUpdatePackagesClicked(self) -> None:
  241. if self._update_packages_action is not None:
  242. self._update_packages_action()
  243. @pyqtSlot()
  244. def popupOpened(self) -> None:
  245. self._setManualSyncEnabled(True)
  246. @pyqtSlot()
  247. def logout(self) -> None:
  248. if not self._logged_in:
  249. return # Nothing to do, user isn't logged in.
  250. self._authorization_service.deleteAuthData()
  251. def updateAdditionalRight(self, **kwargs) -> None:
  252. """Update the additional rights of the account.
  253. The argument(s) are the rights that need to be set"""
  254. self._additional_rights.update(kwargs)
  255. self.additionalRightsChanged.emit(self._additional_rights)
  256. @pyqtProperty("QVariantMap", notify = additionalRightsChanged)
  257. def additionalRights(self) -> Dict[str, Any]:
  258. """A dictionary which can be queried for additional account rights."""
  259. return self._additional_rights