fix(astrbot): fetch chat attachments from the paths this server serves
一些检测仍在等待运行
ci / Portable quality checks (push) Waiting to run
ci / Windows Tauri build (push) Waiting to run

The request trace showed the app talks to 192.168.31.210:26185, not the
host I had been probing, so the endpoint list I read from a dashboard
bundle belonged to a different AstrBot build. This server's own bundle
resolves a chat attachment as:

  /api/chat/get_attachment?attachment_id=...   when an id is known
  /api/chat/get_file?filename=...              otherwise

There is no /api/v1/files at all here. Asking for it returned AstrBot's
"404 Not found" page under HTTP 200, which is why the status check
passed it through as a successful download of an undecodable file.

Try each address in turn — the stream supplies a file name in the media
frame and an id in the frame after, and different builds expose
different paths. Because an unknown path answers 200 with that text
page, a candidate counts as found only when the bytes are recognisably
an image; the status alone proves nothing here. Trying all three also
recovers attachments in existing history, whose markers hold the id
rather than the name.

Refs: N-6.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
这个提交存在于:
YokiiroBW 2026-07-27 03:24:11 +08:00
父节点 d5dfcd465e
当前提交 7a6877d7cc

查看文件

@ -468,6 +468,16 @@ impl AstrBotClient {
})
}
/// Fetches a chat attachment, trying each way AstrBot addresses one.
///
/// The dashboard resolves an attachment by id when it has one and by file
/// name otherwise, and different AstrBot builds expose different paths for
/// it. The marker carries whichever the stream provided, so the candidates
/// are tried in turn.
///
/// Success cannot be judged by status: this server answers an unknown path
/// with its own "404 Not found" text under HTTP 200, so a candidate counts
/// only when the bytes are recognisably an image.
pub async fn download_attachment(
&self,
attachment_id: &str,
@ -480,20 +490,35 @@ impl AstrBotClient {
{
return Err(AstrBotClientError::InvalidConfig("invalid attachment id"));
}
// AstrBot's dashboard fetches a chat image by name via
// `/api/v1/files/content?filename=`. The by-id form
// `/api/v1/files/{id}/content` also exists, but the id carried by
// `attachment_saved` does not address the file.
let request_url = self.url(&format!(
"/api/v1/files/content?filename={}",
urlencoding_username(attachment_id)
));
let encoded = urlencoding_username(attachment_id);
let mut last_note = String::new();
for path in [
format!("/api/chat/get_file?filename={encoded}"),
format!("/api/chat/get_attachment?attachment_id={encoded}"),
format!("/api/v1/files/content?filename={encoded}"),
] {
match self.try_attachment(&path).await? {
Ok(found) => return Ok(found),
Err(note) => last_note = note,
}
}
Err(AstrBotClientError::ApiStatus(format!(
"服务器没有返回图片数据:{last_note}"
)))
}
/// One candidate path. `Ok(Err(note))` means "not here", with what the
/// server said instead.
async fn try_attachment(
&self,
path: &str,
) -> Result<Result<(String, Vec<u8>), String>, AstrBotClientError> {
let request_url = self.url(path);
let response = self.http.get(&request_url).send().await?;
let status = response.status();
// Logged before the status checks: a rejected request is exactly the
// case where the path being asked for is the thing in question. The URL
// holds a file name, not a credential — the bearer token lives in a
// header.
// holds a file name, not a credential; the bearer token is a header.
tracing::debug!(
target: FRAME_TRACE_TARGET,
url = request_url.as_str(),
@ -504,7 +529,7 @@ impl AstrBotClient {
return Err(AstrBotClientError::HttpStatus(status));
}
if !status.is_success() {
return Err(AstrBotClientError::HttpStatus(status));
return Ok(Err(format!("HTTP {}", status.as_u16())));
}
let header_mime = response
.headers()
@ -517,9 +542,7 @@ impl AstrBotClient {
.to_owned();
let bytes = response.bytes().await?.to_vec();
if bytes.is_empty() || bytes.len() > 16 * 1024 * 1024 {
return Err(AstrBotClientError::InvalidConfig(
"attachment size is outside the supported range",
));
return Ok(Err("attachment size is outside the supported range".into()));
}
// A blob URL is decoded according to the blob's type, so handing the
@ -527,13 +550,6 @@ impl AstrBotClient {
// a perfectly good PNG. Prefer a concrete image type from the server,
// fall back to what the bytes themselves say.
let sniffed = sniff_image_mime(&bytes);
let mime_type = if header_mime.starts_with("image/") {
header_mime.clone()
} else if let Some(sniffed) = sniffed {
sniffed.to_owned()
} else {
header_mime.clone()
};
// When the body is not an image it is the server explaining why, which
// is diagnostic text rather than anything the user wrote.
let server_note = if sniffed.is_none() {
@ -546,22 +562,15 @@ impl AstrBotClient {
status = status.as_u16(),
header_mime = header_mime.as_str(),
sniffed = sniffed.unwrap_or("<not an image>"),
resolved_mime = mime_type.as_str(),
bytes = bytes.len(),
server_note = server_note.as_str(),
"astrbot attachment download"
);
// A short HTML body served with 200 is a web page, not a file. AstrBot
// answers an unknown `/api/v1/...` path with its dashboard shell rather
// than a 404, so a wrong endpoint arrives here looking like success.
if mime_type.starts_with("text/html") {
return Err(AstrBotClientError::ApiStatus(
"服务器在附件地址上返回了网页而不是文件,下载端点可能不正确。".into(),
));
match (header_mime.starts_with("image/"), sniffed) {
(true, _) => Ok(Ok((header_mime, bytes))),
(false, Some(sniffed)) => Ok(Ok((sniffed.to_owned(), bytes))),
(false, None) => Ok(Err(server_note)),
}
Ok((mime_type, bytes))
}
pub async fn send_chat_stream(