bambu_ftp.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. import ssl
  2. import socket
  3. import asyncio
  4. import logging
  5. from ftplib import FTP_TLS, FTP
  6. from pathlib import Path
  7. from io import BytesIO
  8. logger = logging.getLogger(__name__)
  9. class ImplicitFTP_TLS(FTP_TLS):
  10. """FTP_TLS subclass for implicit FTPS (port 990) with session reuse."""
  11. def __init__(self, *args, **kwargs):
  12. super().__init__(*args, **kwargs)
  13. self._sock = None
  14. self.ssl_context = ssl.create_default_context()
  15. self.ssl_context.check_hostname = False
  16. self.ssl_context.verify_mode = ssl.CERT_NONE
  17. def connect(self, host='', port=990, timeout=-999, source_address=None):
  18. """Connect to host, wrapping socket in TLS immediately (implicit FTPS)."""
  19. if host:
  20. self.host = host
  21. if port > 0:
  22. self.port = port
  23. if timeout != -999:
  24. self.timeout = timeout
  25. if source_address:
  26. self.source_address = source_address
  27. # Create and wrap socket immediately (implicit TLS)
  28. self.sock = socket.create_connection(
  29. (self.host, self.port),
  30. self.timeout,
  31. source_address=self.source_address
  32. )
  33. self.sock = self.ssl_context.wrap_socket(self.sock, server_hostname=self.host)
  34. self.af = self.sock.family
  35. self.file = self.sock.makefile('r', encoding=self.encoding)
  36. self.welcome = self.getresp()
  37. return self.welcome
  38. def ntransfercmd(self, cmd, rest=None):
  39. """Override to reuse SSL session for data connection (required by vsFTPd)."""
  40. conn, size = FTP.ntransfercmd(self, cmd, rest)
  41. if self._prot_p:
  42. # Reuse the SSL session from the control connection
  43. conn = self.ssl_context.wrap_socket(
  44. conn,
  45. server_hostname=self.host,
  46. session=self.sock.session # Reuse session!
  47. )
  48. return conn, size
  49. class BambuFTPClient:
  50. """FTP client for retrieving files from Bambu Lab printers."""
  51. FTP_PORT = 990
  52. def __init__(self, ip_address: str, access_code: str):
  53. self.ip_address = ip_address
  54. self.access_code = access_code
  55. self._ftp: ImplicitFTP_TLS | None = None
  56. def connect(self) -> bool:
  57. """Connect to the printer FTP server (implicit FTPS on port 990)."""
  58. try:
  59. self._ftp = ImplicitFTP_TLS()
  60. self._ftp.connect(self.ip_address, self.FTP_PORT, timeout=10)
  61. self._ftp.login("bblp", self.access_code)
  62. self._ftp.prot_p()
  63. self._ftp.set_pasv(True)
  64. return True
  65. except Exception as e:
  66. logger.warning(f"FTP connection failed to {self.ip_address}: {e}")
  67. self._ftp = None
  68. return False
  69. def disconnect(self):
  70. """Disconnect from the FTP server."""
  71. if self._ftp:
  72. try:
  73. self._ftp.quit()
  74. except Exception:
  75. pass
  76. self._ftp = None
  77. def list_files(self, path: str = "/") -> list[dict]:
  78. """List files in a directory."""
  79. if not self._ftp:
  80. return []
  81. files = []
  82. try:
  83. self._ftp.cwd(path)
  84. items = []
  85. self._ftp.retrlines("LIST", items.append)
  86. for item in items:
  87. parts = item.split()
  88. if len(parts) >= 9:
  89. name = " ".join(parts[8:])
  90. is_dir = item.startswith("d")
  91. size = int(parts[4]) if not is_dir else 0
  92. files.append({
  93. "name": name,
  94. "is_directory": is_dir,
  95. "size": size,
  96. })
  97. except Exception:
  98. pass
  99. return files
  100. def download_file(self, remote_path: str) -> bytes | None:
  101. """Download a file from the printer."""
  102. if not self._ftp:
  103. return None
  104. try:
  105. buffer = BytesIO()
  106. self._ftp.retrbinary(f"RETR {remote_path}", buffer.write)
  107. return buffer.getvalue()
  108. except Exception:
  109. return None
  110. def download_to_file(self, remote_path: str, local_path: Path) -> bool:
  111. """Download a file from the printer to local filesystem."""
  112. if not self._ftp:
  113. logger.warning("download_to_file called but FTP not connected")
  114. return False
  115. try:
  116. local_path.parent.mkdir(parents=True, exist_ok=True)
  117. with open(local_path, "wb") as f:
  118. self._ftp.retrbinary(f"RETR {remote_path}", f.write)
  119. logger.info(f"Successfully downloaded {remote_path} to {local_path}")
  120. return True
  121. except Exception as e:
  122. logger.debug(f"Failed to download {remote_path}: {e}")
  123. # Clean up partial file if it exists
  124. if local_path.exists():
  125. try:
  126. local_path.unlink()
  127. except Exception:
  128. pass
  129. return False
  130. def upload_file(self, local_path: Path, remote_path: str) -> bool:
  131. """Upload a file to the printer."""
  132. if not self._ftp:
  133. return False
  134. try:
  135. with open(local_path, "rb") as f:
  136. self._ftp.storbinary(f"STOR {remote_path}", f)
  137. return True
  138. except Exception:
  139. return False
  140. def upload_bytes(self, data: bytes, remote_path: str) -> bool:
  141. """Upload bytes to the printer."""
  142. if not self._ftp:
  143. return False
  144. try:
  145. buffer = BytesIO(data)
  146. self._ftp.storbinary(f"STOR {remote_path}", buffer)
  147. return True
  148. except Exception:
  149. return False
  150. def delete_file(self, remote_path: str) -> bool:
  151. """Delete a file from the printer."""
  152. if not self._ftp:
  153. return False
  154. try:
  155. self._ftp.delete(remote_path)
  156. return True
  157. except Exception as e:
  158. logger.warning(f"Failed to delete {remote_path}: {e}")
  159. return False
  160. def get_file_size(self, remote_path: str) -> int | None:
  161. """Get the size of a file."""
  162. if not self._ftp:
  163. return None
  164. try:
  165. return self._ftp.size(remote_path)
  166. except Exception:
  167. return None
  168. def get_storage_info(self) -> dict | None:
  169. """Get storage information from the printer."""
  170. if not self._ftp:
  171. return None
  172. result = {}
  173. # Try AVBL command (available space) - some FTP servers support this
  174. try:
  175. response = self._ftp.sendcmd("AVBL")
  176. # Response format: "213 <bytes available>"
  177. if response.startswith("213"):
  178. parts = response.split()
  179. if len(parts) >= 2:
  180. result["free_bytes"] = int(parts[1])
  181. except Exception:
  182. pass
  183. # Calculate used space by listing root directories
  184. try:
  185. total_used = 0
  186. dirs_to_scan = ["/cache", "/timelapse", "/model"]
  187. for dir_path in dirs_to_scan:
  188. try:
  189. self._ftp.cwd(dir_path)
  190. items = []
  191. self._ftp.retrlines("LIST", items.append)
  192. for item in items:
  193. parts = item.split()
  194. if len(parts) >= 5 and not item.startswith("d"):
  195. try:
  196. total_used += int(parts[4])
  197. except ValueError:
  198. pass
  199. except Exception:
  200. pass
  201. result["used_bytes"] = total_used
  202. except Exception:
  203. pass
  204. return result if result else None
  205. async def download_file_async(
  206. ip_address: str,
  207. access_code: str,
  208. remote_path: str,
  209. local_path: Path,
  210. ) -> bool:
  211. """Async wrapper for downloading a file."""
  212. loop = asyncio.get_event_loop()
  213. def _download():
  214. client = BambuFTPClient(ip_address, access_code)
  215. if client.connect():
  216. try:
  217. return client.download_to_file(remote_path, local_path)
  218. finally:
  219. client.disconnect()
  220. return False
  221. return await loop.run_in_executor(None, _download)
  222. async def download_file_try_paths_async(
  223. ip_address: str,
  224. access_code: str,
  225. remote_paths: list[str],
  226. local_path: Path,
  227. ) -> bool:
  228. """Try downloading a file from multiple paths using a single connection."""
  229. loop = asyncio.get_event_loop()
  230. def _download():
  231. client = BambuFTPClient(ip_address, access_code)
  232. if not client.connect():
  233. return False
  234. try:
  235. for remote_path in remote_paths:
  236. if client.download_to_file(remote_path, local_path):
  237. return True
  238. return False
  239. finally:
  240. client.disconnect()
  241. return await loop.run_in_executor(None, _download)
  242. async def upload_file_async(
  243. ip_address: str,
  244. access_code: str,
  245. local_path: Path,
  246. remote_path: str,
  247. ) -> bool:
  248. """Async wrapper for uploading a file."""
  249. loop = asyncio.get_event_loop()
  250. def _upload():
  251. client = BambuFTPClient(ip_address, access_code)
  252. if client.connect():
  253. try:
  254. return client.upload_file(local_path, remote_path)
  255. finally:
  256. client.disconnect()
  257. return False
  258. return await loop.run_in_executor(None, _upload)
  259. async def list_files_async(
  260. ip_address: str,
  261. access_code: str,
  262. path: str = "/",
  263. ) -> list[dict]:
  264. """Async wrapper for listing files."""
  265. loop = asyncio.get_event_loop()
  266. def _list():
  267. client = BambuFTPClient(ip_address, access_code)
  268. if client.connect():
  269. try:
  270. return client.list_files(path)
  271. finally:
  272. client.disconnect()
  273. return []
  274. return await loop.run_in_executor(None, _list)
  275. async def delete_file_async(
  276. ip_address: str,
  277. access_code: str,
  278. remote_path: str,
  279. ) -> bool:
  280. """Async wrapper for deleting a file."""
  281. loop = asyncio.get_event_loop()
  282. def _delete():
  283. client = BambuFTPClient(ip_address, access_code)
  284. if client.connect():
  285. try:
  286. return client.delete_file(remote_path)
  287. finally:
  288. client.disconnect()
  289. return False
  290. return await loop.run_in_executor(None, _delete)
  291. async def download_file_bytes_async(
  292. ip_address: str,
  293. access_code: str,
  294. remote_path: str,
  295. ) -> bytes | None:
  296. """Async wrapper for downloading file as bytes."""
  297. loop = asyncio.get_event_loop()
  298. def _download():
  299. client = BambuFTPClient(ip_address, access_code)
  300. if client.connect():
  301. try:
  302. return client.download_file(remote_path)
  303. finally:
  304. client.disconnect()
  305. return None
  306. return await loop.run_in_executor(None, _download)
  307. async def get_storage_info_async(
  308. ip_address: str,
  309. access_code: str,
  310. ) -> dict | None:
  311. """Async wrapper for getting storage info."""
  312. loop = asyncio.get_event_loop()
  313. def _get_storage():
  314. client = BambuFTPClient(ip_address, access_code)
  315. if client.connect():
  316. try:
  317. return client.get_storage_info()
  318. finally:
  319. client.disconnect()
  320. return None
  321. return await loop.run_in_executor(None, _get_storage)