Account.py 15 KB

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