Account.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. self._sync_services: Dict[str, int] = {}
  97. """contains entries "service_name" : SyncState"""
  98. self.syncRequested.connect(self._updatePermissions)
  99. def initialize(self) -> None:
  100. self._authorization_service.initialize(self._application.getPreferences())
  101. self._authorization_service.onAuthStateChanged.connect(self._onLoginStateChanged)
  102. self._authorization_service.onAuthenticationError.connect(self._onLoginStateChanged)
  103. self._authorization_service.accessTokenChanged.connect(self._onAccessTokenChanged)
  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. def _onLoginStateChanged(self, logged_in: bool = False, error_message: Optional[str] = None) -> None:
  154. if error_message:
  155. if self._error_message:
  156. self._error_message.hide()
  157. Logger.log("w", "Failed to login: %s", error_message)
  158. self._error_message = Message(error_message,
  159. title = i18n_catalog.i18nc("@info:title", "Login failed"),
  160. message_type = Message.MessageType.ERROR)
  161. self._error_message.show()
  162. self._logged_in = False
  163. self.loginStateChanged.emit(False)
  164. if self._update_timer.isActive():
  165. self._update_timer.stop()
  166. return
  167. if self._logged_in != logged_in:
  168. self._logged_in = logged_in
  169. self.loginStateChanged.emit(logged_in)
  170. if logged_in:
  171. self._authorization_service.getUserProfile(self._onProfileChanged)
  172. self._setManualSyncEnabled(False)
  173. self._sync()
  174. else:
  175. if self._update_timer.isActive():
  176. self._update_timer.stop()
  177. def _onProfileChanged(self, profile: Optional[UserProfile]) -> None:
  178. self._user_profile = profile
  179. self.userProfileChanged.emit()
  180. def _sync(self) -> None:
  181. """Signals all sync services to start syncing
  182. This can be considered a forced sync: even when a
  183. sync is currently running, a sync will be requested.
  184. """
  185. self._update_packages_action = None
  186. self._update_packages_enabled = False
  187. self.updatePackagesEnabledChanged.emit(self._update_packages_enabled)
  188. if self._update_timer.isActive():
  189. self._update_timer.stop()
  190. elif self._sync_state == SyncState.SYNCING:
  191. Logger.debug("Starting a new sync while previous sync was not completed")
  192. self.syncRequested.emit()
  193. def _setManualSyncEnabled(self, enabled: bool) -> None:
  194. if self._manual_sync_enabled != enabled:
  195. self._manual_sync_enabled = enabled
  196. self.manualSyncEnabledChanged.emit(enabled)
  197. @pyqtSlot()
  198. @pyqtSlot(bool)
  199. def login(self, force_logout_before_login: bool = False) -> None:
  200. """
  201. Initializes the login process. If the user is logged in already and force_logout_before_login is true, Cura will
  202. logout from the account before initiating the authorization flow. If the user is logged in and
  203. force_logout_before_login is false, the function will return, as there is nothing to do.
  204. :param force_logout_before_login: Optional boolean parameter
  205. :return: None
  206. """
  207. if self._logged_in:
  208. if force_logout_before_login:
  209. self.logout()
  210. else:
  211. # Nothing to do, user already logged in.
  212. return
  213. self._authorization_service.startAuthorizationFlow(force_logout_before_login)
  214. @pyqtProperty(str, notify = userProfileChanged)
  215. def userName(self):
  216. if not self._user_profile:
  217. return ""
  218. return self._user_profile.username
  219. @pyqtProperty(str, notify = userProfileChanged)
  220. def profileImageUrl(self):
  221. if not self._user_profile:
  222. return ""
  223. return self._user_profile.profile_image_url
  224. @pyqtProperty(str, notify=accessTokenChanged)
  225. def accessToken(self) -> Optional[str]:
  226. return self._authorization_service.getAccessToken()
  227. @pyqtProperty("QVariantMap", notify = userProfileChanged)
  228. def userProfile(self) -> Dict[str, Optional[str]]:
  229. """None if no user is logged in otherwise the logged in user as a dict containing containing user_id, username and profile_image_url """
  230. if not self._user_profile:
  231. return {}
  232. return self._user_profile.__dict__
  233. @pyqtProperty(str, notify=lastSyncDateTimeChanged)
  234. def lastSyncDateTime(self) -> str:
  235. return self._last_sync_str
  236. @pyqtProperty(bool, notify=manualSyncEnabledChanged)
  237. def manualSyncEnabled(self) -> bool:
  238. return self._manual_sync_enabled
  239. @pyqtProperty(bool, notify=updatePackagesEnabledChanged)
  240. def updatePackagesEnabled(self) -> bool:
  241. return self._update_packages_enabled
  242. @pyqtSlot()
  243. @pyqtSlot(bool)
  244. def sync(self, user_initiated: bool = False) -> None:
  245. if user_initiated:
  246. self._setManualSyncEnabled(False)
  247. self._sync()
  248. @pyqtSlot()
  249. def onUpdatePackagesClicked(self) -> None:
  250. if self._update_packages_action is not None:
  251. self._update_packages_action()
  252. @pyqtSlot()
  253. def popupOpened(self) -> None:
  254. self._setManualSyncEnabled(True)
  255. @pyqtSlot()
  256. def logout(self) -> None:
  257. if not self._logged_in:
  258. return # Nothing to do, user isn't logged in.
  259. self._authorization_service.deleteAuthData()
  260. @deprecated("Get permissions from the 'permissions' property", since = "5.2.0")
  261. def updateAdditionalRight(self, **kwargs) -> None:
  262. """Update the additional rights of the account.
  263. The argument(s) are the rights that need to be set"""
  264. self._additional_rights.update(kwargs)
  265. self.additionalRightsChanged.emit(self._additional_rights)
  266. @deprecated("Get permissions from the 'permissions' property", since = "5.2.0")
  267. @pyqtProperty("QVariantMap", notify = additionalRightsChanged)
  268. def additionalRights(self) -> Dict[str, Any]:
  269. """A dictionary which can be queried for additional account rights."""
  270. return self._additional_rights
  271. permissionsChanged = pyqtSignal()
  272. @pyqtProperty("QVariantList", notify = permissionsChanged)
  273. def permissions(self) -> List[str]:
  274. """
  275. The permission keys that the user has in his account.
  276. """
  277. return self._permissions
  278. def _updatePermissions(self) -> None:
  279. """
  280. Update the list of permissions that the user has.
  281. """
  282. def callback(reply: "QNetworkReply"):
  283. status_code = reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute)
  284. if status_code is None:
  285. Logger.error("Server did not respond to request to get list of permissions.")
  286. return
  287. if status_code >= 300:
  288. Logger.error(f"Request to get list of permission resulted in HTTP error {status_code}")
  289. return
  290. try:
  291. reply_data = json.loads(bytes(reply.readAll()).decode("UTF-8"))
  292. except (UnicodeDecodeError, json.JSONDecodeError, ValueError) as e:
  293. Logger.logException("e", f"Could not parse response to permission list request: {e}")
  294. return
  295. if "errors" in reply_data:
  296. Logger.error(f"Request to get list of permission resulted in error response: {reply_data['errors']}")
  297. return
  298. if "data" in reply_data and "permissions" in reply_data["data"]:
  299. permissions = sorted(reply_data["data"]["permissions"])
  300. if permissions != self._permissions:
  301. self._permissions = permissions
  302. self.permissionsChanged.emit()
  303. def error_callback(reply: "QNetworkReply", error: "QNetworkReply.NetworkError"):
  304. Logger.error(f"Request for user permissions list failed. Network error: {error}")
  305. HttpRequestManager.getInstance().get(
  306. url = f"{self._oauth_root}/users/permissions",
  307. scope = JsonDecoratorScope(UltimakerCloudScope(self._application)),
  308. callback = callback,
  309. error_callback = error_callback,
  310. timeout = 10
  311. )