Account.py 12 KB

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