feat: implement send_document() override in RocketChatAdapter
Adds native file upload support via Rocket.Chat REST API using the
rooms.media → chat.postMessage 2-step flow, replacing the base-class
fallback that showed '⚠️ Couldn't deliver the file attachment'.
Changes:
- RocketChatREST.upload_file(): multipart/form-data upload to
/api/v1/rooms.media/{room_id}, then chat.postMessage with
title_link + type=file attachment
- RocketChatAdapter.send_document(): resolves real room_id from
virtual chat_id (same logic as send()), delegates to
self.rest.upload_file(), falls back to super().send_document()
on any failure (auth, room resolution, upload error, exception)
Fixes: MEDIA:-prefix file delivery attempts that previously hit
the base-class fallback.
This commit is contained in:
@@ -436,6 +436,97 @@ class RocketChatREST:
|
||||
}, data=payload)
|
||||
return bool(r and r.get("success"))
|
||||
|
||||
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.
|
||||
|
||||
Two-step flow:
|
||||
1. POST /api/v1/rooms.media/{room_id} (multipart/form-data)
|
||||
2. POST /api/v1/chat.postMessage with title_link + type=file attachment
|
||||
|
||||
Returns:
|
||||
dict with ``success`` (bool), ``upload`` (rooms.media response),
|
||||
and ``post_message`` (chat.postMessage response) on success.
|
||||
dict with ``success=False`` and ``error`` on failure.
|
||||
"""
|
||||
import mimetypes
|
||||
if not self.auth_token:
|
||||
return {"success": False, "error": "Not authenticated"}
|
||||
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 = []
|
||||
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 = {
|
||||
"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:
|
||||
upload_result = json.loads(resp.read().decode("utf-8"))
|
||||
if not upload_result.get("success"):
|
||||
return upload_result
|
||||
# Step 2: Post message with the uploaded file as attachment
|
||||
file_info = upload_result.get("file") or {}
|
||||
file_id = file_info.get("_id")
|
||||
if file_id:
|
||||
attachment: dict = {
|
||||
"title": filename,
|
||||
"title_link": f"/file-upload/{file_id}/{filename}",
|
||||
"title_link_download": True,
|
||||
"type": "file",
|
||||
}
|
||||
if description:
|
||||
attachment["description"] = description
|
||||
post_result = self.post_message(
|
||||
room_id=room_id,
|
||||
text=message or "",
|
||||
attachments=[attachment],
|
||||
)
|
||||
return {
|
||||
"success": True,
|
||||
"upload": upload_result,
|
||||
"post_message": post_result,
|
||||
}
|
||||
return upload_result
|
||||
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)}
|
||||
|
||||
|
||||
class DDPTimeout(Exception):
|
||||
"""Raised when a DDP method call times out waiting for a result message."""
|
||||
@@ -7320,6 +7411,103 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
async def send_typing(self, chat_id: str, metadata=None) -> None:
|
||||
pass
|
||||
|
||||
async def send_document(
|
||||
self,
|
||||
chat_id: str,
|
||||
file_path: str,
|
||||
caption: Optional[str] = None,
|
||||
file_name: Optional[str] = None,
|
||||
reply_to: Optional[str] = None,
|
||||
metadata: Optional[Dict[str, Any]] = None,
|
||||
**kwargs,
|
||||
) -> SendResult:
|
||||
"""Send a document/file natively via Rocket.Chat REST API.
|
||||
|
||||
Uses the rooms.media → chat.postMessage 2-step flow to upload
|
||||
and attach a file. Falls back to the base-class text notice on
|
||||
any failure.
|
||||
"""
|
||||
if not self.rest.auth_token:
|
||||
logger.warning("[rocketchat] send_document: not authenticated, falling back to base")
|
||||
return await super().send_document(
|
||||
chat_id=chat_id, file_path=file_path, caption=caption,
|
||||
file_name=file_name, reply_to=reply_to, metadata=metadata, **kwargs,
|
||||
)
|
||||
|
||||
# ── Resolve real room_id (same logic as send()) ──────────────
|
||||
real_room_id = chat_id
|
||||
if chat_id.startswith("user:"):
|
||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||
if origin:
|
||||
current_token = _CURRENT_TASK_TOKEN.get()
|
||||
ctx_entry = _room_context.get(chat_id, {})
|
||||
stored_token = ctx_entry.get("task_token", "")
|
||||
if current_token and stored_token and current_token != stored_token:
|
||||
origin = ""
|
||||
if origin:
|
||||
real_room_id = origin
|
||||
else:
|
||||
fallback_origin = _get_room_context_origin(chat_id)
|
||||
if fallback_origin:
|
||||
real_room_id = fallback_origin
|
||||
else:
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target:
|
||||
real_room_id = thematic_target
|
||||
else:
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1]
|
||||
else:
|
||||
logger.warning(
|
||||
"[rocketchat] send_document: no resolved room for %s, "
|
||||
"falling back to base",
|
||||
chat_id,
|
||||
)
|
||||
return await super().send_document(
|
||||
chat_id=chat_id, file_path=file_path, caption=caption,
|
||||
file_name=file_name, reply_to=reply_to,
|
||||
metadata=metadata, **kwargs,
|
||||
)
|
||||
|
||||
# ── Upload via rooms.media → chat.postMessage ────────────────
|
||||
display_name = file_name or os.path.basename(file_path)
|
||||
message_text = caption or ""
|
||||
try:
|
||||
result = self.rest.upload_file(
|
||||
room_id=real_room_id,
|
||||
file_path=file_path,
|
||||
message=message_text,
|
||||
description=display_name,
|
||||
)
|
||||
if result.get("success"):
|
||||
logger.info(
|
||||
"[rocketchat] send_document: uploaded %s to room %s",
|
||||
display_name, real_room_id[:8],
|
||||
)
|
||||
return SendResult(success=True, message_id=result.get("post_message"))
|
||||
else:
|
||||
error = result.get("error", "unknown upload error")
|
||||
logger.warning(
|
||||
"[rocketchat] send_document: upload failed for %s: %s — "
|
||||
"falling back to base",
|
||||
display_name, error,
|
||||
)
|
||||
return await super().send_document(
|
||||
chat_id=chat_id, file_path=file_path, caption=caption,
|
||||
file_name=file_name, reply_to=reply_to, metadata=metadata, **kwargs,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"[rocketchat] send_document: exception uploading %s: %s — "
|
||||
"falling back to base",
|
||||
display_name, exc,
|
||||
)
|
||||
return await super().send_document(
|
||||
chat_id=chat_id, file_path=file_path, caption=caption,
|
||||
file_name=file_name, reply_to=reply_to, metadata=metadata, **kwargs,
|
||||
)
|
||||
|
||||
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
|
||||
info = self._room_info.get(chat_id, {})
|
||||
return {"name": info.get("name", chat_id), "type": "group" if info.get("type") in ("c", "p") else "dm"}
|
||||
|
||||
Reference in New Issue
Block a user