bambu_ftp.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. # Parse modification time from FTP listing
  93. # Format: "Nov 30 10:15" or "Nov 30 2024"
  94. mtime = None
  95. try:
  96. from datetime import datetime
  97. month = parts[5]
  98. day = parts[6]
  99. time_or_year = parts[7]
  100. # Determine if it's time (HH:MM) or year
  101. if ":" in time_or_year:
  102. # Recent file: "Nov 30 10:15" - assume current year
  103. year = datetime.now().year
  104. time_str = f"{month} {day} {year} {time_or_year}"
  105. mtime = datetime.strptime(time_str, "%b %d %Y %H:%M")
  106. # If parsed date is in the future, use last year
  107. if mtime > datetime.now():
  108. mtime = mtime.replace(year=year - 1)
  109. else:
  110. # Older file: "Nov 30 2024" - no time, just date
  111. time_str = f"{month} {day} {time_or_year}"
  112. mtime = datetime.strptime(time_str, "%b %d %Y")
  113. except (ValueError, IndexError):
  114. pass
  115. file_entry = {
  116. "name": name,
  117. "is_directory": is_dir,
  118. "size": size,
  119. "path": f"{path.rstrip('/')}/{name}",
  120. }
  121. if mtime:
  122. file_entry["mtime"] = mtime
  123. files.append(file_entry)
  124. except Exception:
  125. pass
  126. return files
  127. def download_file(self, remote_path: str) -> bytes | None:
  128. """Download a file from the printer."""
  129. if not self._ftp:
  130. return None
  131. try:
  132. buffer = BytesIO()
  133. self._ftp.retrbinary(f"RETR {remote_path}", buffer.write)
  134. return buffer.getvalue()
  135. except Exception:
  136. return None
  137. def download_to_file(self, remote_path: str, local_path: Path) -> bool:
  138. """Download a file from the printer to local filesystem."""
  139. if not self._ftp:
  140. logger.warning("download_to_file called but FTP not connected")
  141. return False
  142. try:
  143. local_path.parent.mkdir(parents=True, exist_ok=True)
  144. with open(local_path, "wb") as f:
  145. self._ftp.retrbinary(f"RETR {remote_path}", f.write)
  146. logger.info(f"Successfully downloaded {remote_path} to {local_path}")
  147. return True
  148. except Exception as e:
  149. logger.debug(f"Failed to download {remote_path}: {e}")
  150. # Clean up partial file if it exists
  151. if local_path.exists():
  152. try:
  153. local_path.unlink()
  154. except Exception:
  155. pass
  156. return False
  157. def upload_file(self, local_path: Path, remote_path: str) -> bool:
  158. """Upload a file to the printer."""
  159. if not self._ftp:
  160. logger.warning(f"upload_file: FTP not connected")
  161. return False
  162. try:
  163. file_size = local_path.stat().st_size if local_path.exists() else 0
  164. logger.info(f"FTP uploading {local_path} ({file_size} bytes) to {remote_path}")
  165. with open(local_path, "rb") as f:
  166. self._ftp.storbinary(f"STOR {remote_path}", f)
  167. logger.info(f"FTP upload complete: {remote_path}")
  168. return True
  169. except Exception as e:
  170. logger.error(f"FTP upload failed for {remote_path}: {e}")
  171. return False
  172. def upload_bytes(self, data: bytes, remote_path: str) -> bool:
  173. """Upload bytes to the printer."""
  174. if not self._ftp:
  175. return False
  176. try:
  177. buffer = BytesIO(data)
  178. self._ftp.storbinary(f"STOR {remote_path}", buffer)
  179. return True
  180. except Exception:
  181. return False
  182. def delete_file(self, remote_path: str) -> bool:
  183. """Delete a file from the printer."""
  184. if not self._ftp:
  185. return False
  186. try:
  187. self._ftp.delete(remote_path)
  188. return True
  189. except Exception as e:
  190. logger.warning(f"Failed to delete {remote_path}: {e}")
  191. return False
  192. def get_file_size(self, remote_path: str) -> int | None:
  193. """Get the size of a file."""
  194. if not self._ftp:
  195. return None
  196. try:
  197. return self._ftp.size(remote_path)
  198. except Exception:
  199. return None
  200. def get_storage_info(self) -> dict | None:
  201. """Get storage information from the printer."""
  202. if not self._ftp:
  203. return None
  204. result = {}
  205. # Try AVBL command (available space) - some FTP servers support this
  206. try:
  207. response = self._ftp.sendcmd("AVBL")
  208. # Response format: "213 <bytes available>"
  209. if response.startswith("213"):
  210. parts = response.split()
  211. if len(parts) >= 2:
  212. result["free_bytes"] = int(parts[1])
  213. except Exception:
  214. pass
  215. # Calculate used space by listing root directories
  216. try:
  217. total_used = 0
  218. dirs_to_scan = ["/cache", "/timelapse", "/model"]
  219. for dir_path in dirs_to_scan:
  220. try:
  221. self._ftp.cwd(dir_path)
  222. items = []
  223. self._ftp.retrlines("LIST", items.append)
  224. for item in items:
  225. parts = item.split()
  226. if len(parts) >= 5 and not item.startswith("d"):
  227. try:
  228. total_used += int(parts[4])
  229. except ValueError:
  230. pass
  231. except Exception:
  232. pass
  233. result["used_bytes"] = total_used
  234. except Exception:
  235. pass
  236. return result if result else None
  237. async def download_file_async(
  238. ip_address: str,
  239. access_code: str,
  240. remote_path: str,
  241. local_path: Path,
  242. ) -> bool:
  243. """Async wrapper for downloading a file."""
  244. loop = asyncio.get_event_loop()
  245. def _download():
  246. client = BambuFTPClient(ip_address, access_code)
  247. if client.connect():
  248. try:
  249. return client.download_to_file(remote_path, local_path)
  250. finally:
  251. client.disconnect()
  252. return False
  253. return await loop.run_in_executor(None, _download)
  254. async def download_file_try_paths_async(
  255. ip_address: str,
  256. access_code: str,
  257. remote_paths: list[str],
  258. local_path: Path,
  259. ) -> bool:
  260. """Try downloading a file from multiple paths using a single connection."""
  261. loop = asyncio.get_event_loop()
  262. def _download():
  263. client = BambuFTPClient(ip_address, access_code)
  264. if not client.connect():
  265. return False
  266. try:
  267. for remote_path in remote_paths:
  268. if client.download_to_file(remote_path, local_path):
  269. return True
  270. return False
  271. finally:
  272. client.disconnect()
  273. return await loop.run_in_executor(None, _download)
  274. async def upload_file_async(
  275. ip_address: str,
  276. access_code: str,
  277. local_path: Path,
  278. remote_path: str,
  279. ) -> bool:
  280. """Async wrapper for uploading a file."""
  281. loop = asyncio.get_event_loop()
  282. def _upload():
  283. logger.info(f"FTP connecting to {ip_address} for upload...")
  284. client = BambuFTPClient(ip_address, access_code)
  285. if client.connect():
  286. logger.info(f"FTP connected to {ip_address}")
  287. try:
  288. return client.upload_file(local_path, remote_path)
  289. finally:
  290. client.disconnect()
  291. logger.warning(f"FTP connection failed to {ip_address}")
  292. return False
  293. return await loop.run_in_executor(None, _upload)
  294. async def list_files_async(
  295. ip_address: str,
  296. access_code: str,
  297. path: str = "/",
  298. ) -> list[dict]:
  299. """Async wrapper for listing files."""
  300. loop = asyncio.get_event_loop()
  301. def _list():
  302. client = BambuFTPClient(ip_address, access_code)
  303. if client.connect():
  304. try:
  305. return client.list_files(path)
  306. finally:
  307. client.disconnect()
  308. return []
  309. return await loop.run_in_executor(None, _list)
  310. async def delete_file_async(
  311. ip_address: str,
  312. access_code: str,
  313. remote_path: str,
  314. ) -> bool:
  315. """Async wrapper for deleting a file."""
  316. loop = asyncio.get_event_loop()
  317. def _delete():
  318. client = BambuFTPClient(ip_address, access_code)
  319. if client.connect():
  320. try:
  321. return client.delete_file(remote_path)
  322. finally:
  323. client.disconnect()
  324. return False
  325. return await loop.run_in_executor(None, _delete)
  326. async def download_file_bytes_async(
  327. ip_address: str,
  328. access_code: str,
  329. remote_path: str,
  330. ) -> bytes | None:
  331. """Async wrapper for downloading file as bytes."""
  332. loop = asyncio.get_event_loop()
  333. def _download():
  334. client = BambuFTPClient(ip_address, access_code)
  335. if client.connect():
  336. try:
  337. return client.download_file(remote_path)
  338. finally:
  339. client.disconnect()
  340. return None
  341. return await loop.run_in_executor(None, _download)
  342. async def get_storage_info_async(
  343. ip_address: str,
  344. access_code: str,
  345. ) -> dict | None:
  346. """Async wrapper for getting storage info."""
  347. loop = asyncio.get_event_loop()
  348. def _get_storage():
  349. client = BambuFTPClient(ip_address, access_code)
  350. if client.connect():
  351. try:
  352. return client.get_storage_info()
  353. finally:
  354. client.disconnect()
  355. return None
  356. return await loop.run_in_executor(None, _get_storage)