Account.py 10 KB

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