Account.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from datetime import datetime
  4. from typing import Optional, Dict, TYPE_CHECKING, Union
  5. from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, pyqtProperty, QTimer, Q_ENUMS
  6. from UM.Logger import Logger
  7. from UM.Message import Message
  8. from UM.i18n import i18nCatalog
  9. from cura.OAuth2.AuthorizationService import AuthorizationService
  10. from cura.OAuth2.Models import OAuth2Settings
  11. from cura.UltimakerCloud import UltimakerCloudAuthentication
  12. if TYPE_CHECKING:
  13. from cura.CuraApplication import CuraApplication
  14. i18n_catalog = i18nCatalog("cura")
  15. class SyncState:
  16. """QML: Cura.AccountSyncState"""
  17. SYNCING = 0
  18. SUCCESS = 1
  19. ERROR = 2
  20. ## The account API provides a version-proof bridge to use Ultimaker Accounts
  21. #
  22. # Usage:
  23. # ``from cura.API import CuraAPI
  24. # api = CuraAPI()
  25. # api.account.login()
  26. # api.account.logout()
  27. # api.account.userProfile # Who is logged in``
  28. #
  29. class Account(QObject):
  30. # The interval in which sync services are automatically triggered
  31. SYNC_INTERVAL = 30.0 # seconds
  32. Q_ENUMS(SyncState)
  33. # Signal emitted when user logged in or out.
  34. loginStateChanged = pyqtSignal(bool)
  35. accessTokenChanged = pyqtSignal()
  36. syncRequested = pyqtSignal()
  37. """Sync services may connect to this signal to receive sync triggers.
  38. Services should be resilient to receiving a signal while they are still syncing,
  39. either by ignoring subsequent signals or restarting a sync.
  40. See setSyncState() for providing user feedback on the state of your service.
  41. """
  42. lastSyncDateTimeChanged = pyqtSignal()
  43. syncStateChanged = pyqtSignal(int) # because SyncState is an int Enum
  44. def __init__(self, application: "CuraApplication", parent = None) -> None:
  45. super().__init__(parent)
  46. self._application = application
  47. self._new_cloud_printers_detected = False
  48. self._error_message = None # type: Optional[Message]
  49. self._logged_in = False
  50. self._sync_state = SyncState.SUCCESS
  51. self._last_sync_str = "-"
  52. self._callback_port = 32118
  53. self._oauth_root = UltimakerCloudAuthentication.CuraCloudAccountAPIRoot
  54. self._oauth_settings = OAuth2Settings(
  55. OAUTH_SERVER_URL= self._oauth_root,
  56. CALLBACK_PORT=self._callback_port,
  57. CALLBACK_URL="http://localhost:{}/callback".format(self._callback_port),
  58. CLIENT_ID="um----------------------------ultimaker_cura",
  59. CLIENT_SCOPES="account.user.read drive.backup.read drive.backup.write packages.download "
  60. "packages.rating.read packages.rating.write connect.cluster.read connect.cluster.write "
  61. "cura.printjob.read cura.printjob.write cura.mesh.read cura.mesh.write",
  62. AUTH_DATA_PREFERENCE_KEY="general/ultimaker_auth_data",
  63. AUTH_SUCCESS_REDIRECT="{}/app/auth-success".format(self._oauth_root),
  64. AUTH_FAILED_REDIRECT="{}/app/auth-error".format(self._oauth_root)
  65. )
  66. self._authorization_service = AuthorizationService(self._oauth_settings)
  67. # Create a timer for automatic account sync
  68. self._update_timer = QTimer()
  69. self._update_timer.setInterval(int(self.SYNC_INTERVAL * 1000))
  70. # The timer is restarted explicitly after an update was processed. This prevents 2 concurrent updates
  71. self._update_timer.setSingleShot(True)
  72. self._update_timer.timeout.connect(self.syncRequested)
  73. self._sync_services = {} # type: Dict[str, int]
  74. """contains entries "service_name" : SyncState"""
  75. def initialize(self) -> None:
  76. self._authorization_service.initialize(self._application.getPreferences())
  77. self._authorization_service.onAuthStateChanged.connect(self._onLoginStateChanged)
  78. self._authorization_service.onAuthenticationError.connect(self._onLoginStateChanged)
  79. self._authorization_service.accessTokenChanged.connect(self._onAccessTokenChanged)
  80. self._authorization_service.loadAuthDataFromPreferences()
  81. def setSyncState(self, service_name: str, state: int) -> None:
  82. """ Can be used to register sync services and update account sync states
  83. Contract: A sync service is expected exit syncing state in all cases, within reasonable time
  84. Example: `setSyncState("PluginSyncService", SyncState.SYNCING)`
  85. :param service_name: A unique name for your service, such as `plugins` or `backups`
  86. :param state: One of SyncState
  87. """
  88. prev_state = self._sync_state
  89. self._sync_services[service_name] = state
  90. if any(val == SyncState.SYNCING for val in self._sync_services.values()):
  91. self._sync_state = SyncState.SYNCING
  92. elif any(val == SyncState.ERROR for val in self._sync_services.values()):
  93. self._sync_state = SyncState.ERROR
  94. else:
  95. self._sync_state = SyncState.SUCCESS
  96. if self._sync_state != prev_state:
  97. self.syncStateChanged.emit(self._sync_state)
  98. if self._sync_state == SyncState.SUCCESS:
  99. self._last_sync_str = datetime.now().strftime("%d/%m/%Y %H:%M")
  100. self.lastSyncDateTimeChanged.emit()
  101. if self._sync_state != SyncState.SYNCING:
  102. # schedule new auto update after syncing completed (for whatever reason)
  103. if not self._update_timer.isActive():
  104. self._update_timer.start()
  105. def _onAccessTokenChanged(self):
  106. self.accessTokenChanged.emit()
  107. ## Returns a boolean indicating whether the given authentication is applied against staging or not.
  108. @property
  109. def is_staging(self) -> bool:
  110. return "staging" in self._oauth_root
  111. @pyqtProperty(bool, notify=loginStateChanged)
  112. def isLoggedIn(self) -> bool:
  113. return self._logged_in
  114. def _onLoginStateChanged(self, logged_in: bool = False, error_message: Optional[str] = None) -> None:
  115. if error_message:
  116. if self._error_message:
  117. self._error_message.hide()
  118. self._error_message = Message(error_message, title = i18n_catalog.i18nc("@info:title", "Login failed"))
  119. self._error_message.show()
  120. self._logged_in = False
  121. self.loginStateChanged.emit(False)
  122. if self._update_timer.isActive():
  123. self._update_timer.stop()
  124. return
  125. if self._logged_in != logged_in:
  126. self._logged_in = logged_in
  127. self.loginStateChanged.emit(logged_in)
  128. if logged_in:
  129. self.sync()
  130. else:
  131. if self._update_timer.isActive():
  132. self._update_timer.stop()
  133. @pyqtSlot()
  134. def login(self) -> None:
  135. if self._logged_in:
  136. # Nothing to do, user already logged in.
  137. return
  138. self._authorization_service.startAuthorizationFlow()
  139. @pyqtProperty(str, notify=loginStateChanged)
  140. def userName(self):
  141. user_profile = self._authorization_service.getUserProfile()
  142. if not user_profile:
  143. return None
  144. return user_profile.username
  145. @pyqtProperty(str, notify = loginStateChanged)
  146. def profileImageUrl(self):
  147. user_profile = self._authorization_service.getUserProfile()
  148. if not user_profile:
  149. return None
  150. return user_profile.profile_image_url
  151. @pyqtProperty(str, notify=accessTokenChanged)
  152. def accessToken(self) -> Optional[str]:
  153. return self._authorization_service.getAccessToken()
  154. # Get the profile of the logged in user
  155. # @returns None if no user is logged in, a dict containing user_id, username and profile_image_url
  156. @pyqtProperty("QVariantMap", notify = loginStateChanged)
  157. def userProfile(self) -> Optional[Dict[str, Optional[str]]]:
  158. user_profile = self._authorization_service.getUserProfile()
  159. if not user_profile:
  160. return None
  161. return user_profile.__dict__
  162. @pyqtProperty(str, notify=lastSyncDateTimeChanged)
  163. def lastSyncDateTime(self) -> str:
  164. return self._last_sync_str
  165. @pyqtSlot()
  166. def sync(self) -> None:
  167. """Signals all sync services to start syncing
  168. This can be considered a forced sync: even when a
  169. sync is currently running, a sync will be requested.
  170. """
  171. if self._update_timer.isActive():
  172. self._update_timer.stop()
  173. elif self._sync_state == SyncState.SYNCING:
  174. Logger.warning("Starting a new sync while previous sync was not completed\n{}", str(self._sync_services))
  175. self.syncRequested.emit()
  176. @pyqtSlot()
  177. def logout(self) -> None:
  178. if not self._logged_in:
  179. return # Nothing to do, user isn't logged in.
  180. self._authorization_service.deleteAuthData()