bambu_ftp.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. import asyncio
  2. import logging
  3. import socket
  4. import ssl
  5. from ftplib import FTP, FTP_TLS
  6. from io import BytesIO
  7. from pathlib import Path
  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((self.host, self.port), self.timeout, source_address=self.source_address)
  29. self.sock = self.ssl_context.wrap_socket(self.sock, server_hostname=self.host)
  30. self.af = self.sock.family
  31. self.file = self.sock.makefile("r", encoding=self.encoding)
  32. self.welcome = self.getresp()
  33. return self.welcome
  34. def ntransfercmd(self, cmd, rest=None):
  35. """Override to reuse SSL session for data connection (required by vsFTPd)."""
  36. conn, size = FTP.ntransfercmd(self, cmd, rest)
  37. if self._prot_p:
  38. # Reuse the SSL session from the control connection
  39. conn = self.ssl_context.wrap_socket(
  40. conn,
  41. server_hostname=self.host,
  42. session=self.sock.session, # Reuse session!
  43. )
  44. return conn, size
  45. class BambuFTPClient:
  46. """FTP client for retrieving files from Bambu Lab printers."""
  47. FTP_PORT = 990
  48. def __init__(self, ip_address: str, access_code: str):
  49. self.ip_address = ip_address
  50. self.access_code = access_code
  51. self._ftp: ImplicitFTP_TLS | None = None
  52. def connect(self) -> bool:
  53. """Connect to the printer FTP server (implicit FTPS on port 990)."""
  54. try:
  55. logger.debug(f"FTP connecting to {self.ip_address}:{self.FTP_PORT}")
  56. self._ftp = ImplicitFTP_TLS()
  57. self._ftp.connect(self.ip_address, self.FTP_PORT, timeout=10)
  58. logger.debug("FTP connected, logging in as bblp")
  59. self._ftp.login("bblp", self.access_code)
  60. logger.debug("FTP logged in, setting prot_p and passive mode")
  61. self._ftp.prot_p()
  62. self._ftp.set_pasv(True)
  63. logger.info(f"FTP connected successfully to {self.ip_address}")
  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. logger.debug(f"Listed {len(files)} files in {path}")
  125. except Exception as e:
  126. logger.info(f"FTP list_files failed for {path}: {e}")
  127. return files
  128. def download_file(self, remote_path: str) -> bytes | None:
  129. """Download a file from the printer."""
  130. if not self._ftp:
  131. return None
  132. try:
  133. buffer = BytesIO()
  134. self._ftp.retrbinary(f"RETR {remote_path}", buffer.write)
  135. return buffer.getvalue()
  136. except Exception:
  137. return None
  138. def download_to_file(self, remote_path: str, local_path: Path) -> bool:
  139. """Download a file from the printer to local filesystem."""
  140. if not self._ftp:
  141. logger.warning("download_to_file called but FTP not connected")
  142. return False
  143. try:
  144. local_path.parent.mkdir(parents=True, exist_ok=True)
  145. with open(local_path, "wb") as f:
  146. self._ftp.retrbinary(f"RETR {remote_path}", f.write)
  147. file_size = local_path.stat().st_size if local_path.exists() else 0
  148. logger.info(f"Successfully downloaded {remote_path} to {local_path} ({file_size} bytes)")
  149. return True
  150. except Exception as e:
  151. # Log at INFO level so we can see failures in normal logs
  152. logger.info(f"FTP download failed for {remote_path}: {e}")
  153. # Clean up partial file if it exists
  154. if local_path.exists():
  155. try:
  156. local_path.unlink()
  157. except Exception:
  158. pass
  159. return False
  160. def upload_file(self, local_path: Path, remote_path: str) -> bool:
  161. """Upload a file to the printer."""
  162. if not self._ftp:
  163. logger.warning("upload_file: FTP not connected")
  164. return False
  165. try:
  166. file_size = local_path.stat().st_size if local_path.exists() else 0
  167. logger.info(f"FTP uploading {local_path} ({file_size} bytes) to {remote_path}")
  168. with open(local_path, "rb") as f:
  169. self._ftp.storbinary(f"STOR {remote_path}", f)
  170. logger.info(f"FTP upload complete: {remote_path}")
  171. return True
  172. except Exception as e:
  173. logger.error(f"FTP upload failed for {remote_path}: {e}")
  174. return False
  175. def upload_bytes(self, data: bytes, remote_path: str) -> bool:
  176. """Upload bytes to the printer."""
  177. if not self._ftp:
  178. return False
  179. try:
  180. buffer = BytesIO(data)
  181. self._ftp.storbinary(f"STOR {remote_path}", buffer)
  182. return True
  183. except Exception:
  184. return False
  185. def delete_file(self, remote_path: str) -> bool:
  186. """Delete a file from the printer."""
  187. if not self._ftp:
  188. return False
  189. try:
  190. self._ftp.delete(remote_path)
  191. return True
  192. except Exception as e:
  193. logger.warning(f"Failed to delete {remote_path}: {e}")
  194. return False
  195. def get_file_size(self, remote_path: str) -> int | None:
  196. """Get the size of a file."""
  197. if not self._ftp:
  198. return None
  199. try:
  200. return self._ftp.size(remote_path)
  201. except Exception:
  202. return None
  203. def get_storage_info(self) -> dict | None:
  204. """Get storage information from the printer."""
  205. if not self._ftp:
  206. return None
  207. result = {}
  208. # Try AVBL command (available space) - some FTP servers support this
  209. try:
  210. response = self._ftp.sendcmd("AVBL")
  211. logger.debug(f"AVBL response: {response}")
  212. # Response format: "213 <bytes available>"
  213. if response.startswith("213"):
  214. parts = response.split()
  215. if len(parts) >= 2:
  216. result["free_bytes"] = int(parts[1])
  217. except Exception as e:
  218. logger.debug(f"AVBL command not supported: {e}")
  219. # Try STAT command as fallback
  220. try:
  221. response = self._ftp.sendcmd("STAT")
  222. logger.debug(f"STAT response: {response}")
  223. except Exception:
  224. pass
  225. # Calculate used space by listing root directories
  226. try:
  227. total_used = 0
  228. dirs_to_scan = ["/cache", "/timelapse", "/model"]
  229. for dir_path in dirs_to_scan:
  230. try:
  231. self._ftp.cwd(dir_path)
  232. items = []
  233. self._ftp.retrlines("LIST", items.append)
  234. for item in items:
  235. parts = item.split()
  236. if len(parts) >= 5 and not item.startswith("d"):
  237. try:
  238. total_used += int(parts[4])
  239. except ValueError:
  240. pass
  241. except Exception:
  242. pass
  243. result["used_bytes"] = total_used
  244. except Exception:
  245. pass
  246. return result if result else None
  247. async def download_file_async(
  248. ip_address: str,
  249. access_code: str,
  250. remote_path: str,
  251. local_path: Path,
  252. timeout: float = 60.0,
  253. ) -> bool:
  254. """Async wrapper for downloading a file with timeout."""
  255. loop = asyncio.get_event_loop()
  256. def _download():
  257. client = BambuFTPClient(ip_address, access_code)
  258. if client.connect():
  259. try:
  260. return client.download_to_file(remote_path, local_path)
  261. finally:
  262. client.disconnect()
  263. return False
  264. try:
  265. return await asyncio.wait_for(loop.run_in_executor(None, _download), timeout=timeout)
  266. except TimeoutError:
  267. logger.warning(f"FTP download timed out after {timeout}s for {remote_path}")
  268. return False
  269. async def download_file_try_paths_async(
  270. ip_address: str,
  271. access_code: str,
  272. remote_paths: list[str],
  273. local_path: Path,
  274. ) -> bool:
  275. """Try downloading a file from multiple paths using a single connection."""
  276. loop = asyncio.get_event_loop()
  277. def _download():
  278. client = BambuFTPClient(ip_address, access_code)
  279. if not client.connect():
  280. return False
  281. try:
  282. return any(client.download_to_file(remote_path, local_path) for remote_path in remote_paths)
  283. finally:
  284. client.disconnect()
  285. return await loop.run_in_executor(None, _download)
  286. async def upload_file_async(
  287. ip_address: str,
  288. access_code: str,
  289. local_path: Path,
  290. remote_path: str,
  291. ) -> bool:
  292. """Async wrapper for uploading a file."""
  293. loop = asyncio.get_event_loop()
  294. def _upload():
  295. logger.info(f"FTP connecting to {ip_address} for upload...")
  296. client = BambuFTPClient(ip_address, access_code)
  297. if client.connect():
  298. logger.info(f"FTP connected to {ip_address}")
  299. try:
  300. return client.upload_file(local_path, remote_path)
  301. finally:
  302. client.disconnect()
  303. logger.warning(f"FTP connection failed to {ip_address}")
  304. return False
  305. return await loop.run_in_executor(None, _upload)
  306. async def list_files_async(
  307. ip_address: str,
  308. access_code: str,
  309. path: str = "/",
  310. timeout: float = 30.0,
  311. ) -> list[dict]:
  312. """Async wrapper for listing files with timeout."""
  313. loop = asyncio.get_event_loop()
  314. def _list():
  315. client = BambuFTPClient(ip_address, access_code)
  316. if client.connect():
  317. try:
  318. return client.list_files(path)
  319. finally:
  320. client.disconnect()
  321. return []
  322. try:
  323. return await asyncio.wait_for(loop.run_in_executor(None, _list), timeout=timeout)
  324. except TimeoutError:
  325. logger.warning(f"FTP list_files timed out after {timeout}s for {path}")
  326. return []
  327. async def delete_file_async(
  328. ip_address: str,
  329. access_code: str,
  330. remote_path: str,
  331. ) -> bool:
  332. """Async wrapper for deleting a file."""
  333. loop = asyncio.get_event_loop()
  334. def _delete():
  335. client = BambuFTPClient(ip_address, access_code)
  336. if client.connect():
  337. try:
  338. return client.delete_file(remote_path)
  339. finally:
  340. client.disconnect()
  341. return False
  342. return await loop.run_in_executor(None, _delete)
  343. async def download_file_bytes_async(
  344. ip_address: str,
  345. access_code: str,
  346. remote_path: str,
  347. ) -> bytes | None:
  348. """Async wrapper for downloading file as bytes."""
  349. loop = asyncio.get_event_loop()
  350. def _download():
  351. client = BambuFTPClient(ip_address, access_code)
  352. if client.connect():
  353. try:
  354. return client.download_file(remote_path)
  355. finally:
  356. client.disconnect()
  357. return None
  358. return await loop.run_in_executor(None, _download)
  359. async def get_storage_info_async(
  360. ip_address: str,
  361. access_code: str,
  362. ) -> dict | None:
  363. """Async wrapper for getting storage info."""
  364. loop = asyncio.get_event_loop()
  365. def _get_storage():
  366. client = BambuFTPClient(ip_address, access_code)
  367. if client.connect():
  368. try:
  369. return client.get_storage_info()
  370. finally:
  371. client.disconnect()
  372. return None
  373. return await loop.run_in_executor(None, _get_storage)