Account.py 16 KB

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