bambu_ftp.py 15 KB

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