bambu_ftp.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. import asyncio
  2. import logging
  3. import socket
  4. import ssl
  5. from collections.abc import Callable
  6. from ftplib import FTP, FTP_TLS
  7. from io import BytesIO
  8. from pathlib import Path
  9. logger = logging.getLogger(__name__)
  10. class ImplicitFTP_TLS(FTP_TLS):
  11. """FTP_TLS subclass for implicit FTPS (port 990) with session reuse."""
  12. def __init__(self, *args, **kwargs):
  13. super().__init__(*args, **kwargs)
  14. self._sock = None
  15. self.ssl_context = ssl.create_default_context()
  16. self.ssl_context.check_hostname = False
  17. self.ssl_context.verify_mode = ssl.CERT_NONE
  18. def connect(self, host="", port=990, timeout=-999, source_address=None):
  19. """Connect to host, wrapping socket in TLS immediately (implicit FTPS)."""
  20. if host:
  21. self.host = host
  22. if port > 0:
  23. self.port = port
  24. if timeout != -999:
  25. self.timeout = timeout
  26. if source_address:
  27. self.source_address = source_address
  28. # Create and wrap socket immediately (implicit TLS)
  29. self.sock = socket.create_connection((self.host, self.port), self.timeout, source_address=self.source_address)
  30. self.sock = self.ssl_context.wrap_socket(self.sock, server_hostname=self.host)
  31. self.af = self.sock.family
  32. self.file = self.sock.makefile("r", encoding=self.encoding)
  33. self.welcome = self.getresp()
  34. return self.welcome
  35. def ntransfercmd(self, cmd, rest=None):
  36. """Override to reuse SSL session for data connection (required by vsFTPd)."""
  37. conn, size = FTP.ntransfercmd(self, cmd, rest)
  38. if self._prot_p:
  39. # Reuse the SSL session from the control connection
  40. conn = self.ssl_context.wrap_socket(
  41. conn,
  42. server_hostname=self.host,
  43. session=self.sock.session, # Reuse session!
  44. )
  45. return conn, size
  46. class BambuFTPClient:
  47. """FTP client for retrieving files from Bambu Lab printers."""
  48. FTP_PORT = 990
  49. def __init__(self, ip_address: str, access_code: str):
  50. self.ip_address = ip_address
  51. self.access_code = access_code
  52. self._ftp: ImplicitFTP_TLS | None = None
  53. def connect(self) -> bool:
  54. """Connect to the printer FTP server (implicit FTPS on port 990)."""
  55. try:
  56. logger.debug(f"FTP connecting to {self.ip_address}:{self.FTP_PORT}")
  57. self._ftp = ImplicitFTP_TLS()
  58. self._ftp.connect(self.ip_address, self.FTP_PORT, timeout=10)
  59. logger.debug("FTP connected, logging in as bblp")
  60. self._ftp.login("bblp", self.access_code)
  61. logger.debug("FTP logged in, setting prot_p and passive mode")
  62. self._ftp.prot_p()
  63. self._ftp.set_pasv(True)
  64. logger.info(f"FTP connected successfully to {self.ip_address}")
  65. return True
  66. except Exception as e:
  67. logger.warning(f"FTP connection failed to {self.ip_address}: {e}")
  68. self._ftp = None
  69. return False
  70. def disconnect(self):
  71. """Disconnect from the FTP server."""
  72. if self._ftp:
  73. try:
  74. self._ftp.quit()
  75. except Exception:
  76. pass
  77. self._ftp = None
  78. def list_files(self, path: str = "/") -> list[dict]:
  79. """List files in a directory."""
  80. if not self._ftp:
  81. return []
  82. files = []
  83. try:
  84. self._ftp.cwd(path)
  85. items = []
  86. self._ftp.retrlines("LIST", items.append)
  87. for item in items:
  88. parts = item.split()
  89. if len(parts) >= 9:
  90. name = " ".join(parts[8:])
  91. is_dir = item.startswith("d")
  92. size = int(parts[4]) if not is_dir else 0
  93. # Parse modification time from FTP listing
  94. # Format: "Nov 30 10:15" or "Nov 30 2024"
  95. mtime = None
  96. try:
  97. from datetime import datetime
  98. month = parts[5]
  99. day = parts[6]
  100. time_or_year = parts[7]
  101. # Determine if it's time (HH:MM) or year
  102. if ":" in time_or_year:
  103. # Recent file: "Nov 30 10:15" - assume current year
  104. year = datetime.now().year
  105. time_str = f"{month} {day} {year} {time_or_year}"
  106. mtime = datetime.strptime(time_str, "%b %d %Y %H:%M")
  107. # If parsed date is in the future, use last year
  108. if mtime > datetime.now():
  109. mtime = mtime.replace(year=year - 1)
  110. else:
  111. # Older file: "Nov 30 2024" - no time, just date
  112. time_str = f"{month} {day} {time_or_year}"
  113. mtime = datetime.strptime(time_str, "%b %d %Y")
  114. except (ValueError, IndexError):
  115. pass
  116. file_entry = {
  117. "name": name,
  118. "is_directory": is_dir,
  119. "size": size,
  120. "path": f"{path.rstrip('/')}/{name}",
  121. }
  122. if mtime:
  123. file_entry["mtime"] = mtime
  124. files.append(file_entry)
  125. logger.debug(f"Listed {len(files)} files in {path}")
  126. except Exception as e:
  127. logger.info(f"FTP list_files failed for {path}: {e}")
  128. return files
  129. def download_file(self, remote_path: str) -> bytes | None:
  130. """Download a file from the printer."""
  131. if not self._ftp:
  132. return None
  133. try:
  134. buffer = BytesIO()
  135. self._ftp.retrbinary(f"RETR {remote_path}", buffer.write)
  136. return buffer.getvalue()
  137. except Exception:
  138. return None
  139. def download_to_file(self, remote_path: str, local_path: Path) -> bool:
  140. """Download a file from the printer to local filesystem."""
  141. if not self._ftp:
  142. logger.warning("download_to_file called but FTP not connected")
  143. return False
  144. try:
  145. local_path.parent.mkdir(parents=True, exist_ok=True)
  146. with open(local_path, "wb") as f:
  147. self._ftp.retrbinary(f"RETR {remote_path}", f.write)
  148. file_size = local_path.stat().st_size if local_path.exists() else 0
  149. logger.info(f"Successfully downloaded {remote_path} to {local_path} ({file_size} bytes)")
  150. return True
  151. except Exception as e:
  152. # Log at INFO level so we can see failures in normal logs
  153. logger.info(f"FTP download failed for {remote_path}: {e}")
  154. # Clean up partial file if it exists
  155. if local_path.exists():
  156. try:
  157. local_path.unlink()
  158. except Exception:
  159. pass
  160. return False
  161. def upload_file(
  162. self,
  163. local_path: Path,
  164. remote_path: str,
  165. progress_callback: Callable[[int, int], None] | None = None,
  166. ) -> bool:
  167. """Upload a file to the printer with optional progress callback."""
  168. if not self._ftp:
  169. logger.warning("upload_file: FTP not connected")
  170. return False
  171. try:
  172. file_size = local_path.stat().st_size if local_path.exists() else 0
  173. logger.info(f"FTP uploading {local_path} ({file_size} bytes) to {remote_path}")
  174. uploaded = 0
  175. def on_block(block: bytes):
  176. nonlocal uploaded
  177. uploaded += len(block)
  178. if progress_callback:
  179. progress_callback(uploaded, file_size)
  180. with open(local_path, "rb") as f:
  181. self._ftp.storbinary(f"STOR {remote_path}", f, callback=on_block)
  182. logger.info(f"FTP upload complete: {remote_path}")
  183. return True
  184. except Exception as e:
  185. logger.error(f"FTP upload failed for {remote_path}: {e}")
  186. return False
  187. def upload_bytes(self, data: bytes, remote_path: str) -> bool:
  188. """Upload bytes to the printer."""
  189. if not self._ftp:
  190. return False
  191. try:
  192. buffer = BytesIO(data)
  193. self._ftp.storbinary(f"STOR {remote_path}", buffer)
  194. return True
  195. except Exception:
  196. return False
  197. def delete_file(self, remote_path: str) -> bool:
  198. """Delete a file from the printer."""
  199. if not self._ftp:
  200. return False
  201. try:
  202. self._ftp.delete(remote_path)
  203. return True
  204. except Exception as e:
  205. logger.warning(f"Failed to delete {remote_path}: {e}")
  206. return False
  207. def get_file_size(self, remote_path: str) -> int | None:
  208. """Get the size of a file."""
  209. if not self._ftp:
  210. return None
  211. try:
  212. return self._ftp.size(remote_path)
  213. except Exception:
  214. return None
  215. def get_storage_info(self) -> dict | None:
  216. """Get storage information from the printer."""
  217. if not self._ftp:
  218. return None
  219. result = {}
  220. # Try AVBL command (available space) - some FTP servers support this
  221. try:
  222. response = self._ftp.sendcmd("AVBL")
  223. logger.debug(f"AVBL response: {response}")
  224. # Response format: "213 <bytes available>"
  225. if response.startswith("213"):
  226. parts = response.split()
  227. if len(parts) >= 2:
  228. result["free_bytes"] = int(parts[1])
  229. except Exception as e:
  230. logger.debug(f"AVBL command not supported: {e}")
  231. # Try STAT command as fallback
  232. try:
  233. response = self._ftp.sendcmd("STAT")
  234. logger.debug(f"STAT response: {response}")
  235. except Exception:
  236. pass
  237. # Calculate used space by listing root directories
  238. try:
  239. total_used = 0
  240. dirs_to_scan = ["/cache", "/timelapse", "/model"]
  241. for dir_path in dirs_to_scan:
  242. try:
  243. self._ftp.cwd(dir_path)
  244. items = []
  245. self._ftp.retrlines("LIST", items.append)
  246. for item in items:
  247. parts = item.split()
  248. if len(parts) >= 5 and not item.startswith("d"):
  249. try:
  250. total_used += int(parts[4])
  251. except ValueError:
  252. pass
  253. except Exception:
  254. pass
  255. result["used_bytes"] = total_used
  256. except Exception:
  257. pass
  258. return result if result else None
  259. async def download_file_async(
  260. ip_address: str,
  261. access_code: str,
  262. remote_path: str,
  263. local_path: Path,
  264. timeout: float = 60.0,
  265. ) -> bool:
  266. """Async wrapper for downloading a file with timeout."""
  267. loop = asyncio.get_event_loop()
  268. def _download():
  269. client = BambuFTPClient(ip_address, access_code)
  270. if client.connect():
  271. try:
  272. return client.download_to_file(remote_path, local_path)
  273. finally:
  274. client.disconnect()
  275. return False
  276. try:
  277. return await asyncio.wait_for(loop.run_in_executor(None, _download), timeout=timeout)
  278. except TimeoutError:
  279. logger.warning(f"FTP download timed out after {timeout}s for {remote_path}")
  280. return False
  281. async def download_file_try_paths_async(
  282. ip_address: str,
  283. access_code: str,
  284. remote_paths: list[str],
  285. local_path: Path,
  286. ) -> bool:
  287. """Try downloading a file from multiple paths using a single connection."""
  288. loop = asyncio.get_event_loop()
  289. def _download():
  290. client = BambuFTPClient(ip_address, access_code)
  291. if not client.connect():
  292. return False
  293. try:
  294. return any(client.download_to_file(remote_path, local_path) for remote_path in remote_paths)
  295. finally:
  296. client.disconnect()
  297. return await loop.run_in_executor(None, _download)
  298. async def upload_file_async(
  299. ip_address: str,
  300. access_code: str,
  301. local_path: Path,
  302. remote_path: str,
  303. timeout: float = 600.0,
  304. progress_callback: Callable[[int, int], None] | None = None,
  305. ) -> bool:
  306. """Async wrapper for uploading a file with timeout and progress callback."""
  307. loop = asyncio.get_event_loop()
  308. def _upload():
  309. logger.info(f"FTP connecting to {ip_address} for upload...")
  310. client = BambuFTPClient(ip_address, access_code)
  311. if client.connect():
  312. logger.info(f"FTP connected to {ip_address}")
  313. try:
  314. return client.upload_file(local_path, remote_path, progress_callback)
  315. finally:
  316. client.disconnect()
  317. logger.warning(f"FTP connection failed to {ip_address}")
  318. return False
  319. try:
  320. return await asyncio.wait_for(loop.run_in_executor(None, _upload), timeout=timeout)
  321. except TimeoutError:
  322. logger.warning(f"FTP upload timed out after {timeout}s for {remote_path}")
  323. return False
  324. async def list_files_async(
  325. ip_address: str,
  326. access_code: str,
  327. path: str = "/",
  328. timeout: float = 30.0,
  329. ) -> list[dict]:
  330. """Async wrapper for listing files with timeout."""
  331. loop = asyncio.get_event_loop()
  332. def _list():
  333. client = BambuFTPClient(ip_address, access_code)
  334. if client.connect():
  335. try:
  336. return client.list_files(path)
  337. finally:
  338. client.disconnect()
  339. return []
  340. try:
  341. return await asyncio.wait_for(loop.run_in_executor(None, _list), timeout=timeout)
  342. except TimeoutError:
  343. logger.warning(f"FTP list_files timed out after {timeout}s for {path}")
  344. return []
  345. async def delete_file_async(
  346. ip_address: str,
  347. access_code: str,
  348. remote_path: str,
  349. ) -> bool:
  350. """Async wrapper for deleting a file."""
  351. loop = asyncio.get_event_loop()
  352. def _delete():
  353. client = BambuFTPClient(ip_address, access_code)
  354. if client.connect():
  355. try:
  356. return client.delete_file(remote_path)
  357. finally:
  358. client.disconnect()
  359. return False
  360. return await loop.run_in_executor(None, _delete)
  361. async def download_file_bytes_async(
  362. ip_address: str,
  363. access_code: str,
  364. remote_path: str,
  365. ) -> bytes | None:
  366. """Async wrapper for downloading file as bytes."""
  367. loop = asyncio.get_event_loop()
  368. def _download():
  369. client = BambuFTPClient(ip_address, access_code)
  370. if client.connect():
  371. try:
  372. return client.download_file(remote_path)
  373. finally:
  374. client.disconnect()
  375. return None
  376. return await loop.run_in_executor(None, _download)
  377. async def get_storage_info_async(
  378. ip_address: str,
  379. access_code: str,
  380. ) -> dict | None:
  381. """Async wrapper for getting storage info."""
  382. loop = asyncio.get_event_loop()
  383. def _get_storage():
  384. client = BambuFTPClient(ip_address, access_code)
  385. if client.connect():
  386. try:
  387. return client.get_storage_info()
  388. finally:
  389. client.disconnect()
  390. return None
  391. return await loop.run_in_executor(None, _get_storage)