NetworkedPrinterOutputDevice.py 17 KB

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