diff --git a/plugin/adapter.py b/plugin/adapter.py index 1b021ec..6ab6ee1 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -478,6 +478,41 @@ class RocketChatAdapter(BasePlatformAdapter): user_info = msg_obj.get("u", {}) username = (user_info.get("username", "") or "").lower() # normalize case + # NEW: Check for file attachments in the message and enrich the text + file_info = msg_obj.get("file") + attachments = msg_obj.get("attachments", []) + if file_info or attachments: + file_details = [] + base_url = self.base_url.rstrip("/") + # Process file object if present + if file_info and isinstance(file_info, dict): + filename = file_info.get("name", "unknown") + filetype = file_info.get("type", "unknown") + file_id = file_info.get("_id") + if file_id and filename: + download_url = f"{base_url}/file-upload/{file_id}/{filename}" + file_details.append(f"[FILE] {filename} ({filetype})\nDownload: {download_url}") + # Process attachments if present + if attachments and isinstance(attachments, list): + for attachment in attachments: + if isinstance(attachment, dict) and attachment.get("type") == "file": + title = attachment.get("title", "unknown") + title_link = attachment.get("title_link", "") + if title_link: + if title_link.startswith("/"): + download_url = f"{base_url}{title_link}" + else: + download_url = f"{base_url}/{title_link}" + file_details.append(f"[FILE] {title} (file)\nDownload: {download_url}") + # Add file information to message text + if file_details: + file_info_text = "\n".join(file_details) + if text: + text = f"{text}\n\n{file_info_text}" + else: + text = file_info_text + msg_obj["msg"] = text + # Skip own messages (case-insensitive comparison) if username == (self.user or "").lower() or not text or not room_id: return diff --git a/plugin/tools.py b/plugin/tools.py index 4397bd9..465bd0b 100644 --- a/plugin/tools.py +++ b/plugin/tools.py @@ -16,6 +16,7 @@ import os import time import urllib.request from typing import Any, Dict, List, Optional +import urllib.parse from tools.registry import tool_error, tool_result @@ -167,6 +168,74 @@ class RocketChatAPI: payload["attachments"] = attachments return self._request("POST", "/api/v1/chat.postMessage", payload) or {} + def download_file(self, file_id: str, filename: str) -> bytes: + """Download a file from Rocket.Chat.""" + url = f"{self.base_url}/file-upload/{file_id}/{filename}" + headers: Dict[str, str] = { + "X-Auth-Token": self.auth_token, + "X-User-Id": self.user_id, + } + req = urllib.request.Request(url, headers=headers, method="GET") + with urllib.request.urlopen(req, timeout=30) as resp: + return resp.read() + + def get_room_files(self, room_id: str, count: int = 50, offset: int = 0) -> dict: + """Get list of files in a room with pagination.""" + endpoint = f"/api/v1/channels.files?roomId={room_id}&count={count}&offset={offset}" + return self._request("GET", endpoint) or {} + + def upload_file(self, room_id: str, file_path: str, message: str = "", description: str = "") -> dict: + """Upload a file to a Rocket.Chat room using multipart/form-data.""" + import mimetypes + if not os.path.exists(file_path): + return {"success": False, "error": f"File not found: {file_path}"} + content_type, _ = mimetypes.guess_type(file_path) + if content_type is None: + content_type = "application/octet-stream" + boundary = "----HermesAgentUploadBoundary" + body_parts: List[bytes] = [] + with open(file_path, "rb") as f: + file_data = f.read() + filename = os.path.basename(file_path) + # Add file field + body_parts.append(f"--{boundary}\r\n".encode()) + body_parts.append(f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'.encode()) + body_parts.append(f"Content-Type: {content_type}\r\n\r\n".encode()) + body_parts.append(file_data) + body_parts.append(b"\r\n") + if message: + body_parts.append(f"--{boundary}\r\n".encode()) + body_parts.append(b'Content-Disposition: form-data; name="msg"\r\n\r\n') + body_parts.append(message.encode()) + body_parts.append(b"\r\n") + if description: + body_parts.append(f"--{boundary}\r\n".encode()) + body_parts.append(b'Content-Disposition: form-data; name="description"\r\n\r\n') + body_parts.append(description.encode()) + body_parts.append(b"\r\n") + body_parts.append(f"--{boundary}--\r\n".encode()) + body = b"".join(body_parts) + url = f"{self.base_url}/api/v1/rooms.media/{room_id}" + headers: Dict[str, str] = { + "X-Auth-Token": self.auth_token, + "X-User-Id": self.user_id, + "Content-Type": f"multipart/form-data; boundary={boundary}", + } + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=60) as resp: + return json.loads(resp.read().decode("utf-8")) + except urllib.error.HTTPError as exc: + msg = f"Upload HTTP {exc.code}" + try: + detail = json.loads(exc.read().decode("utf-8")) + msg += f": {detail}" + except Exception: + pass + return {"success": False, "error": msg} + except Exception as exc: + return {"success": False, "error": str(exc)} + @classmethod def login(cls, base_url: str, user: str, password: str) -> Optional["RocketChatAPI"]: """Authenticate and return an API client, or None if login fails.""" @@ -591,6 +660,124 @@ def _handle_rocketchat_send(args: dict, **kw) -> str: return tool_error(f"rocketchat_send failed: {type(exc).__name__}: {exc}") +def _handle_rocketchat_upload(args: dict, **kw) -> str: + """Upload a file to a Rocket.Chat room.""" + client = _rc_client() + if not client: + return _rc_error() + + room_id = str(args.get("room_id") or "").strip() + file_path = str(args.get("file_path") or "").strip() + message = str(args.get("message") or "").strip() + description = str(args.get("description") or "").strip() + + if not room_id or not file_path: + return tool_error("room_id and file_path are required for rocketchat_upload") + + try: + result = client.upload_file(room_id, file_path, message, description) + if result.get("success"): + return tool_result({ + "success": True, + "file_id": result.get("file_id"), + "filename": result.get("filename"), + "file_type": result.get("file_type"), + "message": result.get("message"), + "result": result, + }) + else: + return tool_result({"success": False, "error": result.get("error", "Upload failed")}) + except Exception as exc: + return tool_error(f"rocketchat_upload failed: {type(exc).__name__}: {exc}") + + +def _handle_rocketchat_download(args: dict, **kw) -> str: + """Download a file from Rocket.Chat and save it locally.""" + client = _rc_client() + if not client: + return _rc_error() + + file_id = str(args.get("file_id") or "").strip() + filename = str(args.get("filename") or "").strip() + + if not file_id or not filename: + return tool_error("file_id and filename are required for rocketchat_download") + + try: + # Download the file + file_content = client.download_file(file_id, filename) + + # Create download directory if it doesn't exist + download_dir = os.path.expanduser("~/.hermes/cache/downloads") + os.makedirs(download_dir, exist_ok=True) + + # Save file locally + file_path = os.path.join(download_dir, filename) + with open(file_path, "wb") as f: + f.write(file_content) + + return tool_result({ + "success": True, + "file_id": file_id, + "filename": filename, + "saved_path": file_path, + "size": len(file_content) + }) + except Exception as exc: + return tool_error(f"rocketchat_download failed: {type(exc).__name__}: {exc}") + + +def _handle_rocketchat_files(args: dict, **kw) -> str: + """List files in a Rocket.Chat room with pagination.""" + client = _rc_client() + if not client: + return _rc_error() + + room_id = str(args.get("room_id") or "").strip() + if not room_id: + return tool_error("room_id is required for rocketchat_files") + + try: + count = int(args.get("count", 50)) + offset = int(args.get("offset", 0)) + + # Get files from the room + result = client.get_room_files(room_id, count=count, offset=offset) + + if not result.get("success"): + return tool_error(f"Failed to retrieve files: {result.get('error', 'Unknown error')}") + + files = result.get("files", []) + + # Normalize file information + normalized_files = [] + for file_info in files: + normalized_files.append({ + "_id": file_info.get("_id"), + "name": file_info.get("name"), + "type": file_info.get("type"), + "size": file_info.get("size"), + "uploadedAt": file_info.get("uploadedAt"), + "url": file_info.get("url"), + "user": { + "_id": file_info.get("user", {}).get("_id"), + "username": file_info.get("user", {}).get("username"), + "name": file_info.get("user", {}).get("name") + } if file_info.get("user") else None + }) + + return tool_result({ + "success": True, + "room_id": room_id, + "count": len(normalized_files), + "files": normalized_files, + "offset": offset, + "total": result.get("total", 0) + }) + except Exception as exc: + return tool_error(f"rocketchat_files failed: {type(exc).__name__}: {exc}") + + # --------------------------------------------------------------------------- # Tool schemas (OpenAI function-calling format) # --------------------------------------------------------------------------- @@ -705,6 +892,60 @@ ROCKETCHAT_SEND_SCHEMA = { } +ROCKETCHAT_DOWNLOAD_SCHEMA = { + "name": "rocketchat_download", + "description": ( + "Download a file from Rocket.Chat by file ID and filename. " + "The file will be saved to ~/.hermes/cache/downloads/ and the local path will be returned." + ), + "parameters": { + "type": "object", + "properties": { + "file_id": {"type": "string", "description": "Rocket.Chat file ID"}, + "filename": {"type": "string", "description": "Filename to save as"}, + }, + "required": ["file_id", "filename"], + }, +} + + +ROCKETCHAT_UPLOAD_SCHEMA = { + "name": "rocketchat_upload", + "description": ( + "Upload a file to a Rocket.Chat room with optional message and description. " + "Uses multipart/form-data to upload files directly to the Rocket.Chat server." + ), + "parameters": { + "type": "object", + "properties": { + "room_id": {"type": "string", "description": "Target room ID"}, + "file_path": {"type": "string", "description": "Local path to the file to upload"}, + "message": {"type": "string", "description": "Optional message to send with the file"}, + "description": {"type": "string", "description": "Optional file description"}, + }, + "required": ["room_id", "file_path"], + }, +} + + +ROCKETCHAT_FILES_SCHEMA = { + "name": "rocketchat_files", + "description": ( + "List files in a Rocket.Chat room with pagination support. " + "Returns structured information about files including ID, name, type, size, and upload date." + ), + "parameters": { + "type": "object", + "properties": { + "room_id": {"type": "string", "description": "Room ID to list files from"}, + "count": {"type": "integer", "description": "Number of files to retrieve (default: 50)"}, + "offset": {"type": "integer", "description": "Offset for pagination (default: 0)"}, + }, + "required": ["room_id"], + }, +} + + # --------------------------------------------------------------------------- # Registration helpers for the plugin register() function # --------------------------------------------------------------------------- @@ -714,6 +955,9 @@ _TOOLS = ( ("rocketchat_users", ROCKETCHAT_USERS_SCHEMA, _handle_rocketchat_users, "👤"), ("rocketchat_dm", ROCKETCHAT_DM_SCHEMA, _handle_rocketchat_dm, "💬"), ("rocketchat_send", ROCKETCHAT_SEND_SCHEMA, _handle_rocketchat_send, "✉️"), + ("rocketchat_upload", ROCKETCHAT_UPLOAD_SCHEMA, _handle_rocketchat_upload, "📎"), + ("rocketchat_download", ROCKETCHAT_DOWNLOAD_SCHEMA, _handle_rocketchat_download, "📥"), + ("rocketchat_files", ROCKETCHAT_FILES_SCHEMA, _handle_rocketchat_files, "📁"), )