Account.py 12 KB

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