bambu_ftp.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. logger.debug(f"AVBL response: {response}")
  209. # Response format: "213 <bytes available>"
  210. if response.startswith("213"):
  211. parts = response.split()
  212. if len(parts) >= 2:
  213. result["free_bytes"] = int(parts[1])
  214. except Exception as e:
  215. logger.debug(f"AVBL command not supported: {e}")
  216. # Try STAT command as fallback
  217. try:
  218. response = self._ftp.sendcmd("STAT")
  219. logger.debug(f"STAT response: {response}")
  220. except Exception:
  221. pass
  222. # Calculate used space by listing root directories
  223. try:
  224. total_used = 0
  225. dirs_to_scan = ["/cache", "/timelapse", "/model"]
  226. for dir_path in dirs_to_scan:
  227. try:
  228. self._ftp.cwd(dir_path)
  229. items = []
  230. self._ftp.retrlines("LIST", items.append)
  231. for item in items:
  232. parts = item.split()
  233. if len(parts) >= 5 and not item.startswith("d"):
  234. try:
  235. total_used += int(parts[4])
  236. except ValueError:
  237. pass
  238. except Exception:
  239. pass
  240. result["used_bytes"] = total_used
  241. except Exception:
  242. pass
  243. return result if result else None
  244. async def download_file_async(
  245. ip_address: str,
  246. access_code: str,
  247. remote_path: str,
  248. local_path: Path,
  249. ) -> bool:
  250. """Async wrapper for downloading a file."""
  251. loop = asyncio.get_event_loop()
  252. def _download():
  253. client = BambuFTPClient(ip_address, access_code)
  254. if client.connect():
  255. try:
  256. return client.download_to_file(remote_path, local_path)
  257. finally:
  258. client.disconnect()
  259. return False
  260. return await loop.run_in_executor(None, _download)
  261. async def download_file_try_paths_async(
  262. ip_address: str,
  263. access_code: str,
  264. remote_paths: list[str],
  265. local_path: Path,
  266. ) -> bool:
  267. """Try downloading a file from multiple paths using a single connection."""
  268. loop = asyncio.get_event_loop()
  269. def _download():
  270. client = BambuFTPClient(ip_address, access_code)
  271. if not client.connect():
  272. return False
  273. try:
  274. for remote_path in remote_paths:
  275. if client.download_to_file(remote_path, local_path):
  276. return True
  277. return False
  278. finally:
  279. client.disconnect()
  280. return await loop.run_in_executor(None, _download)
  281. async def upload_file_async(
  282. ip_address: str,
  283. access_code: str,
  284. local_path: Path,
  285. remote_path: str,
  286. ) -> bool:
  287. """Async wrapper for uploading a file."""
  288. loop = asyncio.get_event_loop()
  289. def _upload():
  290. logger.info(f"FTP connecting to {ip_address} for upload...")
  291. client = BambuFTPClient(ip_address, access_code)
  292. if client.connect():
  293. logger.info(f"FTP connected to {ip_address}")
  294. try:
  295. return client.upload_file(local_path, remote_path)
  296. finally:
  297. client.disconnect()
  298. logger.warning(f"FTP connection failed to {ip_address}")
  299. return False
  300. return await loop.run_in_executor(None, _upload)
  301. async def list_files_async(
  302. ip_address: str,
  303. access_code: str,
  304. path: str = "/",
  305. ) -> list[dict]:
  306. """Async wrapper for listing files."""
  307. loop = asyncio.get_event_loop()
  308. def _list():
  309. client = BambuFTPClient(ip_address, access_code)
  310. if client.connect():
  311. try:
  312. return client.list_files(path)
  313. finally:
  314. client.disconnect()
  315. return []
  316. return await loop.run_in_executor(None, _list)
  317. async def delete_file_async(
  318. ip_address: str,
  319. access_code: str,
  320. remote_path: str,
  321. ) -> bool:
  322. """Async wrapper for deleting a file."""
  323. loop = asyncio.get_event_loop()
  324. def _delete():
  325. client = BambuFTPClient(ip_address, access_code)
  326. if client.connect():
  327. try:
  328. return client.delete_file(remote_path)
  329. finally:
  330. client.disconnect()
  331. return False
  332. return await loop.run_in_executor(None, _delete)
  333. async def download_file_bytes_async(
  334. ip_address: str,
  335. access_code: str,
  336. remote_path: str,
  337. ) -> bytes | None:
  338. """Async wrapper for downloading file as bytes."""
  339. loop = asyncio.get_event_loop()
  340. def _download():
  341. client = BambuFTPClient(ip_address, access_code)
  342. if client.connect():
  343. try:
  344. return client.download_file(remote_path)
  345. finally:
  346. client.disconnect()
  347. return None
  348. return await loop.run_in_executor(None, _download)
  349. async def get_storage_info_async(
  350. ip_address: str,
  351. access_code: str,
  352. ) -> dict | None:
  353. """Async wrapper for getting storage info."""
  354. loop = asyncio.get_event_loop()
  355. def _get_storage():
  356. client = BambuFTPClient(ip_address, access_code)
  357. if client.connect():
  358. try:
  359. return client.get_storage_info()
  360. finally:
  361. client.disconnect()
  362. return None
  363. return await loop.run_in_executor(None, _get_storage)