NetworkedPrinterOutputDevice.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from UM.FileHandler.FileHandler import FileHandler #For typing.
  4. from UM.Logger import Logger
  5. from UM.Scene.SceneNode import SceneNode #For typing.
  6. from cura.API import Account
  7. from cura.CuraApplication import CuraApplication
  8. from cura.PrinterOutput.PrinterOutputDevice import PrinterOutputDevice, ConnectionState, ConnectionType
  9. from PyQt5.QtNetwork import QHttpMultiPart, QHttpPart, QNetworkRequest, QNetworkAccessManager, QNetworkReply, QAuthenticator
  10. from PyQt5.QtCore import pyqtProperty, pyqtSignal, pyqtSlot, QObject, QUrl, QCoreApplication
  11. from time import time
  12. from typing import Callable, Dict, List, Optional, Union
  13. from enum import IntEnum
  14. import os # To get the username
  15. import gzip
  16. from cura.Settings.CuraContainerRegistry import CuraContainerRegistry
  17. class AuthState(IntEnum):
  18. NotAuthenticated = 1
  19. AuthenticationRequested = 2
  20. Authenticated = 3
  21. AuthenticationDenied = 4
  22. AuthenticationReceived = 5
  23. class NetworkedPrinterOutputDevice(PrinterOutputDevice):
  24. authenticationStateChanged = pyqtSignal()
  25. def __init__(self, device_id, address: str, properties: Dict[bytes, bytes], connection_type: ConnectionType = ConnectionType.NetworkConnection, parent: QObject = None) -> None:
  26. super().__init__(device_id = device_id, connection_type = connection_type, parent = parent)
  27. self._manager = None # type: Optional[QNetworkAccessManager]
  28. self._timeout_time = 10 # After how many seconds of no response should a timeout occur?
  29. self._last_response_time = None # type: Optional[float]
  30. self._last_request_time = None # type: Optional[float]
  31. self._api_prefix = ""
  32. self._address = address
  33. self._properties = properties
  34. self._user_agent = "%s/%s " % (CuraApplication.getInstance().getApplicationName(),
  35. CuraApplication.getInstance().getVersion())
  36. self._onFinishedCallbacks = {} # type: Dict[str, Callable[[QNetworkReply], None]]
  37. self._authentication_state = AuthState.NotAuthenticated
  38. # QHttpMultiPart objects need to be kept alive and not garbage collected during the
  39. # HTTP which uses them. We hold references to these QHttpMultiPart objects here.
  40. self._kept_alive_multiparts = {} # type: Dict[QNetworkReply, QHttpMultiPart]
  41. self._sending_gcode = False
  42. self._compressing_gcode = False
  43. self._gcode = [] # type: List[str]
  44. self._connection_state_before_timeout = None # type: Optional[ConnectionState]
  45. def requestWrite(self, nodes: List["SceneNode"], file_name: Optional[str] = None, limit_mimetypes: bool = False,
  46. file_handler: Optional["FileHandler"] = None, filter_by_machine: bool = False, **kwargs) -> None:
  47. raise NotImplementedError("requestWrite needs to be implemented")
  48. def setAuthenticationState(self, authentication_state: AuthState) -> None:
  49. if self._authentication_state != authentication_state:
  50. self._authentication_state = authentication_state
  51. self.authenticationStateChanged.emit()
  52. @pyqtProperty(int, notify = authenticationStateChanged)
  53. def authenticationState(self) -> AuthState:
  54. return self._authentication_state
  55. def _compressDataAndNotifyQt(self, data_to_append: str) -> bytes:
  56. compressed_data = gzip.compress(data_to_append.encode("utf-8"))
  57. self._progress_message.setProgress(-1) # Tickle the message so that it's clear that it's still being used.
  58. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  59. # Pretend that this is a response, as zipping might take a bit of time.
  60. # If we don't do this, the device might trigger a timeout.
  61. self._last_response_time = time()
  62. return compressed_data
  63. def _compressGCode(self) -> Optional[bytes]:
  64. self._compressing_gcode = True
  65. ## Mash the data into single string
  66. max_chars_per_line = int(1024 * 1024 / 4) # 1/4 MB per line.
  67. file_data_bytes_list = []
  68. batched_lines = []
  69. batched_lines_count = 0
  70. for line in self._gcode:
  71. if not self._compressing_gcode:
  72. self._progress_message.hide()
  73. # Stop trying to zip / send as abort was called.
  74. return None
  75. # if the gcode was read from a gcode file, self._gcode will be a list of all lines in that file.
  76. # Compressing line by line in this case is extremely slow, so we need to batch them.
  77. batched_lines.append(line)
  78. batched_lines_count += len(line)
  79. if batched_lines_count >= max_chars_per_line:
  80. file_data_bytes_list.append(self._compressDataAndNotifyQt("".join(batched_lines)))
  81. batched_lines = []
  82. batched_lines_count = 0
  83. # Don't miss the last batch (If any)
  84. if len(batched_lines) != 0:
  85. file_data_bytes_list.append(self._compressDataAndNotifyQt("".join(batched_lines)))
  86. self._compressing_gcode = False
  87. return b"".join(file_data_bytes_list)
  88. def _update(self) -> None:
  89. if self._last_response_time:
  90. time_since_last_response = time() - self._last_response_time
  91. else:
  92. time_since_last_response = 0
  93. if self._last_request_time:
  94. time_since_last_request = time() - self._last_request_time
  95. else:
  96. time_since_last_request = float("inf") # An irrelevantly large number of seconds
  97. if time_since_last_response > self._timeout_time >= time_since_last_request:
  98. # Go (or stay) into timeout.
  99. if self._connection_state_before_timeout is None:
  100. self._connection_state_before_timeout = self._connection_state
  101. self.setConnectionState(ConnectionState.Closed)
  102. elif self._connection_state == ConnectionState.Closed:
  103. # Go out of timeout.
  104. if self._connection_state_before_timeout is not None: # sanity check, but it should never be None here
  105. self.setConnectionState(self._connection_state_before_timeout)
  106. self._connection_state_before_timeout = None
  107. def _createEmptyRequest(self, target: str, content_type: Optional[str] = "application/json") -> QNetworkRequest:
  108. url = QUrl("http://" + self._address + self._api_prefix + target)
  109. request = QNetworkRequest(url)
  110. if content_type is not None:
  111. request.setHeader(QNetworkRequest.ContentTypeHeader, content_type)
  112. request.setHeader(QNetworkRequest.UserAgentHeader, self._user_agent)
  113. return request
  114. ## This method was only available privately before, but it was actually called from SendMaterialJob.py.
  115. # We now have a public equivalent as well. We did not remove the private one as plugins might be using that.
  116. def createFormPart(self, content_header: str, data: bytes, content_type: Optional[str] = None) -> QHttpPart:
  117. return self._createFormPart(content_header, data, content_type)
  118. def _createFormPart(self, content_header: str, data: bytes, content_type: Optional[str] = None) -> QHttpPart:
  119. part = QHttpPart()
  120. if not content_header.startswith("form-data;"):
  121. content_header = "form_data; " + content_header
  122. part.setHeader(QNetworkRequest.ContentDispositionHeader, content_header)
  123. if content_type is not None:
  124. part.setHeader(QNetworkRequest.ContentTypeHeader, content_type)
  125. part.setBody(data)
  126. return part
  127. ## Convenience function to get the username, either from the cloud or from the OS.
  128. def _getUserName(self) -> str:
  129. # check first if we are logged in with the Ultimaker Account
  130. account = CuraApplication.getInstance().getCuraAPI().account # type: Account
  131. if account and account.isLoggedIn:
  132. return account.userName
  133. # Otherwise get the username from the US
  134. # The code below was copied from the getpass module, as we try to use as little dependencies as possible.
  135. for name in ("LOGNAME", "USER", "LNAME", "USERNAME"):
  136. user = os.environ.get(name)
  137. if user:
  138. return user
  139. return "Unknown User" # Couldn't find out username.
  140. def _clearCachedMultiPart(self, reply: QNetworkReply) -> None:
  141. if reply in self._kept_alive_multiparts:
  142. del self._kept_alive_multiparts[reply]
  143. def _validateManager(self) -> None:
  144. if self._manager is None:
  145. self._createNetworkManager()
  146. assert (self._manager is not None)
  147. ## Sends a put request to the given path.
  148. # \param url: The path after the API prefix.
  149. # \param data: The data to be sent in the body
  150. # \param content_type: The content type of the body data.
  151. # \param on_finished: The function to call when the response is received.
  152. # \param on_progress: The function to call when the progress changes. Parameters are bytes_sent / bytes_total.
  153. def put(self, url: str, data: Union[str, bytes], content_type: Optional[str] = "application/json",
  154. on_finished: Optional[Callable[[QNetworkReply], None]] = None,
  155. on_progress: Optional[Callable[[int, int], None]] = None) -> None:
  156. self._validateManager()
  157. request = self._createEmptyRequest(url, content_type = content_type)
  158. self._last_request_time = time()
  159. if not self._manager:
  160. Logger.log("e", "No network manager was created to execute the PUT call with.")
  161. return
  162. body = data if isinstance(data, bytes) else data.encode() # type: bytes
  163. reply = self._manager.put(request, body)
  164. self._registerOnFinishedCallback(reply, on_finished)
  165. if on_progress is not None:
  166. reply.uploadProgress.connect(on_progress)
  167. ## Sends a delete request to the given path.
  168. # \param url: The path after the API prefix.
  169. # \param on_finished: The function to be call when the response is received.
  170. def delete(self, url: str, on_finished: Optional[Callable[[QNetworkReply], None]]) -> None:
  171. self._validateManager()
  172. request = self._createEmptyRequest(url)
  173. self._last_request_time = time()
  174. if not self._manager:
  175. Logger.log("e", "No network manager was created to execute the DELETE call with.")
  176. return
  177. reply = self._manager.deleteResource(request)
  178. self._registerOnFinishedCallback(reply, on_finished)
  179. ## Sends a get request to the given path.
  180. # \param url: The path after the API prefix.
  181. # \param on_finished: The function to be call when the response is received.
  182. def get(self, url: str, on_finished: Optional[Callable[[QNetworkReply], None]]) -> None:
  183. self._validateManager()
  184. request = self._createEmptyRequest(url)
  185. self._last_request_time = time()
  186. if not self._manager:
  187. Logger.log("e", "No network manager was created to execute the GET call with.")
  188. return
  189. reply = self._manager.get(request)
  190. self._registerOnFinishedCallback(reply, on_finished)
  191. ## Sends a post request to the given path.
  192. # \param url: The path after the API prefix.
  193. # \param data: The data to be sent in the body
  194. # \param on_finished: The function to call when the response is received.
  195. # \param on_progress: The function to call when the progress changes. Parameters are bytes_sent / bytes_total.
  196. def post(self, url: str, data: Union[str, bytes],
  197. on_finished: Optional[Callable[[QNetworkReply], None]],
  198. on_progress: Optional[Callable[[int, int], None]] = None) -> None:
  199. self._validateManager()
  200. request = self._createEmptyRequest(url)
  201. self._last_request_time = time()
  202. if not self._manager:
  203. Logger.log("e", "Could not find manager.")
  204. return
  205. body = data if isinstance(data, bytes) else data.encode() # type: bytes
  206. reply = self._manager.post(request, body)
  207. if on_progress is not None:
  208. reply.uploadProgress.connect(on_progress)
  209. self._registerOnFinishedCallback(reply, on_finished)
  210. def postFormWithParts(self, target: str, parts: List[QHttpPart],
  211. on_finished: Optional[Callable[[QNetworkReply], None]],
  212. on_progress: Optional[Callable[[int, int], None]] = None) -> QNetworkReply:
  213. self._validateManager()
  214. request = self._createEmptyRequest(target, content_type=None)
  215. multi_post_part = QHttpMultiPart(QHttpMultiPart.FormDataType)
  216. for part in parts:
  217. multi_post_part.append(part)
  218. self._last_request_time = time()
  219. if self._manager is not None:
  220. reply = self._manager.post(request, multi_post_part)
  221. self._kept_alive_multiparts[reply] = multi_post_part
  222. if on_progress is not None:
  223. reply.uploadProgress.connect(on_progress)
  224. self._registerOnFinishedCallback(reply, on_finished)
  225. return reply
  226. else:
  227. Logger.log("e", "Could not find manager.")
  228. def postForm(self, target: str, header_data: str, body_data: bytes, on_finished: Optional[Callable[[QNetworkReply], None]], on_progress: Callable = None) -> None:
  229. post_part = QHttpPart()
  230. post_part.setHeader(QNetworkRequest.ContentDispositionHeader, header_data)
  231. post_part.setBody(body_data)
  232. self.postFormWithParts(target, [post_part], on_finished, on_progress)
  233. def _onAuthenticationRequired(self, reply: QNetworkReply, authenticator: QAuthenticator) -> None:
  234. Logger.log("w", "Request to {url} required authentication, which was not implemented".format(url = reply.url().toString()))
  235. def _createNetworkManager(self) -> None:
  236. Logger.log("d", "Creating network manager")
  237. if self._manager:
  238. self._manager.finished.disconnect(self._handleOnFinished)
  239. self._manager.authenticationRequired.disconnect(self._onAuthenticationRequired)
  240. self._manager = QNetworkAccessManager()
  241. self._manager.finished.connect(self._handleOnFinished)
  242. self._manager.authenticationRequired.connect(self._onAuthenticationRequired)
  243. if self._properties.get(b"temporary", b"false") != b"true":
  244. self._checkCorrectGroupName(self.getId(), self.name)
  245. def _registerOnFinishedCallback(self, reply: QNetworkReply, on_finished: Optional[Callable[[QNetworkReply], None]]) -> None:
  246. if on_finished is not None:
  247. self._onFinishedCallbacks[reply.url().toString() + str(reply.operation())] = on_finished
  248. ## This method checks if the name of the group stored in the definition container is correct.
  249. # After updating from 3.2 to 3.3 some group names may be temporary. If there is a mismatch in the name of the group
  250. # then all the container stacks are updated, both the current and the hidden ones.
  251. def _checkCorrectGroupName(self, device_id: str, group_name: str) -> None:
  252. global_container_stack = CuraApplication.getInstance().getGlobalContainerStack()
  253. active_machine_network_name = CuraApplication.getInstance().getMachineManager().activeMachineNetworkKey()
  254. if global_container_stack and device_id == active_machine_network_name:
  255. # Check if the group_name is correct. If not, update all the containers connected to the same printer
  256. if CuraApplication.getInstance().getMachineManager().activeMachineNetworkGroupName != group_name:
  257. metadata_filter = {"um_network_key": active_machine_network_name}
  258. containers = CuraContainerRegistry.getInstance().findContainerStacks(type="machine",
  259. **metadata_filter)
  260. for container in containers:
  261. container.setMetaDataEntry("group_name", group_name)
  262. def _handleOnFinished(self, reply: QNetworkReply) -> None:
  263. # Due to garbage collection, we need to cache certain bits of post operations.
  264. # As we don't want to keep them around forever, delete them if we get a reply.
  265. if reply.operation() == QNetworkAccessManager.PostOperation:
  266. self._clearCachedMultiPart(reply)
  267. if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) is None:
  268. # No status code means it never even reached remote.
  269. return
  270. self._last_response_time = time()
  271. if self._connection_state == ConnectionState.Connecting:
  272. self.setConnectionState(ConnectionState.Connected)
  273. callback_key = reply.url().toString() + str(reply.operation())
  274. try:
  275. if callback_key in self._onFinishedCallbacks:
  276. self._onFinishedCallbacks[callback_key](reply)
  277. except Exception:
  278. Logger.logException("w", "something went wrong with callback")
  279. @pyqtSlot(str, result=str)
  280. def getProperty(self, key: str) -> str:
  281. bytes_key = key.encode("utf-8")
  282. if bytes_key in self._properties:
  283. return self._properties.get(bytes_key, b"").decode("utf-8")
  284. else:
  285. return ""
  286. def getProperties(self):
  287. return self._properties
  288. ## Get the unique key of this machine
  289. # \return key String containing the key of the machine.
  290. @pyqtProperty(str, constant = True)
  291. def key(self) -> str:
  292. return self._id
  293. ## The IP address of the printer.
  294. @pyqtProperty(str, constant = True)
  295. def address(self) -> str:
  296. return self._properties.get(b"address", b"").decode("utf-8")
  297. ## Name of the printer (as returned from the ZeroConf properties)
  298. @pyqtProperty(str, constant = True)
  299. def name(self) -> str:
  300. return self._properties.get(b"name", b"").decode("utf-8")
  301. ## Firmware version (as returned from the ZeroConf properties)
  302. @pyqtProperty(str, constant = True)
  303. def firmwareVersion(self) -> str:
  304. return self._properties.get(b"firmware_version", b"").decode("utf-8")
  305. @pyqtProperty(str, constant = True)
  306. def printerType(self) -> str:
  307. return self._properties.get(b"printer_type", b"Unknown").decode("utf-8")
  308. ## IP adress of this printer
  309. @pyqtProperty(str, constant = True)
  310. def ipAddress(self) -> str:
  311. return self._address