fix(chat): images attached to chat messages load again
Since chats are read through the Teams chat service, inline images point
at AMS (`https://*.asm.skype.com/v1/objects/{id}/views/imgo`). Those URLs
went to the Graph downloader, which rejects anything outside Graph, so
every pasted image stayed a placeholder. Graph hosted-content ids that
wrap an AMS URL failed the same way.
AMS views now download in the page with the Skype token, like the AMS
upload already does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -0,0 +1,16 @@
1
try {
2
const response = await fetch(args.url, {
3
headers: {Authorization: 'skype_token ' + skypeCache.token, 'x-ms-client-version': '1415/1.0.0.2018090100'},
4
});
5
if (!response.ok) return {status: response.status, body: (await response.text()).slice(0, 300)};
6
const blob = await response.blob();
7
const base64 = await new Promise((resolve, reject) => {
8
const reader = new FileReader();
9
reader.onload = () => resolve(String(reader.result).split(',')[1] || '');
10
reader.onerror = () => reject(reader.error);
11
reader.readAsDataURL(blob);
12
});
13
return {status: response.status, body: {base64, contentType: blob.type}};
14
} catch (error) {
15
return {status: 0, body: String(error)};
16
}
@@ -0,0 +1,16 @@1
try {2
const response = await fetch(args.url, {3
headers: {Authorization: 'skype_token ' + skypeCache.token, 'x-ms-client-version': '1415/1.0.0.2018090100'},4
});5
if (!response.ok) return {status: response.status, body: (await response.text()).slice(0, 300)};6
const blob = await response.blob();7
const base64 = await new Promise((resolve, reject) => {8
const reader = new FileReader();9
reader.onload = () => resolve(String(reader.result).split(',')[1] || '');10
reader.onerror = () => reject(reader.error);11
reader.readAsDataURL(blob);12
});13
return {status: response.status, body: {base64, contentType: blob.type}};14
} catch (error) {15
return {status: 0, body: String(error)};16
}@@ -4,6 +4,7 @@ use serde_json::{Value, json};
4
4
use session::{App, Scope, Session};
5
5
6
6
use crate::error::{Error, Result};
7
use crate::links::{LinkImage, decoded_image};
7
8
use crate::messages::ensure_success;
8
9
use crate::pins::transport::{CSA_RESOURCE, CSA_SCOPE, skype_fetch_answer};
9
10
@@ -12,6 +13,10 @@ const UPLOAD_BODY: &str = concat!(
12
13
include_str!("../assets/skype_token.js"),
13
14
include_str!("../assets/ams_upload.js")
14
15
);
16
const DOWNLOAD_BODY: &str = concat!(
17
include_str!("../assets/skype_token.js"),
18
include_str!("../assets/ams_download.js")
19
);
15
20
const FULL_SIZE_VIEW: &str = "/views/imgpsh_fullsize";
16
21
17
22
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -79,6 +84,23 @@ impl Ams {
79
84
ensure_success(&answer)?;
80
85
uploaded_image(&answer.body)
81
86
}
87
88
/// Reads an AMS image view such as `.../v1/objects/{id}/views/imgo` with the Skype token.
89
pub async fn download_image(&self, url: &str) -> Result<LinkImage> {
90
let answer = self
91
.session
92
.run_with_token(
93
App::Teams,
94
&Scope::new(CSA_RESOURCE, CSA_SCOPE),
95
DOWNLOAD_BODY,
96
&json!({ "url": url }),
97
false,
98
)
99
.await?;
100
let answer = skype_fetch_answer(answer);
101
ensure_success(&answer)?;
102
decoded_image(&answer.body)
103
}
82
104
}
83
105
84
106
#[cfg(test)]
@@ -4,6 +4,7 @@ use serde_json::{Value, json};4
use session::{App, Scope, Session};4
use session::{App, Scope, Session};5
5
6
use crate::error::{Error, Result};6
use crate::error::{Error, Result};7
use crate::links::{LinkImage, decoded_image};7
use crate::messages::ensure_success;8
use crate::messages::ensure_success;8
use crate::pins::transport::{CSA_RESOURCE, CSA_SCOPE, skype_fetch_answer};9
use crate::pins::transport::{CSA_RESOURCE, CSA_SCOPE, skype_fetch_answer};9
10
@@ -12,6 +13,10 @@ const UPLOAD_BODY: &str = concat!(12
include_str!("../assets/skype_token.js"),13
include_str!("../assets/skype_token.js"),13
include_str!("../assets/ams_upload.js")14
include_str!("../assets/ams_upload.js")14
);15
);16
const DOWNLOAD_BODY: &str = concat!(17
include_str!("../assets/skype_token.js"),18
include_str!("../assets/ams_download.js")19
);15
const FULL_SIZE_VIEW: &str = "/views/imgpsh_fullsize";20
const FULL_SIZE_VIEW: &str = "/views/imgpsh_fullsize";16
21
17
#[derive(Debug, Clone, PartialEq, Eq)]22
#[derive(Debug, Clone, PartialEq, Eq)]@@ -79,6 +84,23 @@ impl Ams {79
ensure_success(&answer)?;84
ensure_success(&answer)?;80
uploaded_image(&answer.body)85
uploaded_image(&answer.body)81
}86
}87
88
/// Reads an AMS image view such as `.../v1/objects/{id}/views/imgo` with the Skype token.89
pub async fn download_image(&self, url: &str) -> Result<LinkImage> {90
let answer = self91
.session92
.run_with_token(93
App::Teams,94
&Scope::new(CSA_RESOURCE, CSA_SCOPE),95
DOWNLOAD_BODY,96
&json!({ "url": url }),97
false,98
)99
.await?;100
let answer = skype_fetch_answer(answer);101
ensure_success(&answer)?;102
decoded_image(&answer.body)103
}82
}104
}83
105
84
#[cfg(test)]106
#[cfg(test)]@@ -92,7 +92,10 @@ pub use language_settings::{
92
92
LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,
93
93
parse_language_settings, target_patch,
94
94
};
95
pub use links::{LinkImage, LinkInfo, MessageLinks, hosted_content_image_url, is_link_image_url};
95
pub use links::{
96
LinkImage, LinkInfo, MessageLinks, hosted_content_image_url, is_ams_image_url,
97
is_link_image_url,
98
};
96
99
pub use mask::mask_conversation_id;
97
100
pub use members::{
98
101
HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
@@ -92,7 +92,10 @@ pub use language_settings::{92
LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,92
LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,93
parse_language_settings, target_patch,93
parse_language_settings, target_patch,94
};94
};95
pub use links::{LinkImage, LinkInfo, MessageLinks, hosted_content_image_url, is_link_image_url};95
pub use links::{96
LinkImage, LinkInfo, MessageLinks, hosted_content_image_url, is_ams_image_url,97
is_link_image_url,98
};96
pub use mask::mask_conversation_id;99
pub use mask::mask_conversation_id;97
pub use members::{100
pub use members::{98
HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,101
HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,@@ -11,6 +11,7 @@ pub const LINK_PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";
11
11
const LIST_VIEW: &str = "msnp24Equivalent";
12
12
const HOSTED_CONTENTS_SEGMENT: &str = "/hostedContents/";
13
13
const HOSTED_URL_KEY: &str = ",url=";
14
const AMS_HOST_SUFFIX: &str = ".asm.skype.com";
14
15
15
16
#[derive(Debug, Clone, PartialEq, Eq)]
16
17
pub struct MessageLinks {
@@ -51,7 +52,16 @@ pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {
51
52
.ok()?;
52
53
let decoded = String::from_utf8(bytes).ok()?;
53
54
let (_, url) = decoded.split_once(HOSTED_URL_KEY)?;
54
is_link_image_url(url).then(|| url.to_owned())
55
(is_link_image_url(url) || is_ams_image_url(url)).then(|| url.to_owned())
56
}
57
58
/// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages.
59
pub fn is_ams_image_url(url: &str) -> bool {
60
url.strip_prefix("https://")
61
.and_then(|rest| rest.split_once('/'))
62
.is_some_and(|(host, path)| {
63
host.ends_with(AMS_HOST_SUFFIX) && path.starts_with("v1/objects/")
64
})
55
65
}
56
66
57
67
pub fn parse_message_links(body: &Value) -> Vec<MessageLinks> {
@@ -150,27 +160,30 @@ impl<T: MessageTransport> Messages<T> {
150
160
}
151
161
let answer = self.transport.send(Request::binary_get(url)).await?;
152
162
ensure_success(&answer)?;
153
let encoded = answer
154
.body
155
.get("base64")
156
.and_then(Value::as_str)
157
.unwrap_or_default();
158
let bytes = STANDARD
159
.decode(encoded.as_bytes())
160
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
161
let content_type = answer
162
.body
163
.get("contentType")
164
.and_then(Value::as_str)
165
.unwrap_or_default()
166
.to_owned();
167
Ok(LinkImage {
168
bytes,
169
content_type,
170
})
163
decoded_image(&answer.body)
171
164
}
172
165
}
173
166
167
/// An image answer shaped `{base64, contentType}`.
168
pub(crate) fn decoded_image(body: &Value) -> Result<LinkImage> {
169
let encoded = body
170
.get("base64")
171
.and_then(Value::as_str)
172
.unwrap_or_default();
173
let bytes = STANDARD
174
.decode(encoded.as_bytes())
175
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
176
let content_type = body
177
.get("contentType")
178
.and_then(Value::as_str)
179
.unwrap_or_default()
180
.to_owned();
181
Ok(LinkImage {
182
bytes,
183
content_type,
184
})
185
}
186
174
187
#[cfg(test)]
175
188
mod tests {
176
189
use super::*;
@@ -192,6 +205,26 @@ mod tests {
192
205
);
193
206
}
194
207
208
#[test]
209
fn ams_object_views_are_recognized_inside_hosted_content_ids() {
210
let ams = "https://eu-api.asm.skype.com/v1/objects/0-frca-d14-abc/views/imgo";
211
assert!(is_ams_image_url(ams));
212
let id = STANDARD.encode(format!("id=x_0-frca-d14-abc,type=1,url={ams}"));
213
assert_eq!(
214
hosted_content_image_url(&format!(
215
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{id}/$value"
216
))
217
.as_deref(),
218
Some(ams)
219
);
220
assert!(!is_ams_image_url(
221
"https://evil.example/v1/objects/a/views/imgo"
222
));
223
assert!(!is_ams_image_url(
224
"https://eu-api.asm.skype.com/v1/users/me"
225
));
226
}
227
195
228
#[test]
196
229
fn parses_link_info_with_target_url_and_thumbnail_size() {
197
230
let info = parse_link_info(&json!({
@@ -11,6 +11,7 @@ pub const LINK_PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";11
const LIST_VIEW: &str = "msnp24Equivalent";11
const LIST_VIEW: &str = "msnp24Equivalent";12
const HOSTED_CONTENTS_SEGMENT: &str = "/hostedContents/";12
const HOSTED_CONTENTS_SEGMENT: &str = "/hostedContents/";13
const HOSTED_URL_KEY: &str = ",url=";13
const HOSTED_URL_KEY: &str = ",url=";14
const AMS_HOST_SUFFIX: &str = ".asm.skype.com";14
15
15
#[derive(Debug, Clone, PartialEq, Eq)]16
#[derive(Debug, Clone, PartialEq, Eq)]16
pub struct MessageLinks {17
pub struct MessageLinks {@@ -51,7 +52,16 @@ pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {51
.ok()?;52
.ok()?;52
let decoded = String::from_utf8(bytes).ok()?;53
let decoded = String::from_utf8(bytes).ok()?;53
let (_, url) = decoded.split_once(HOSTED_URL_KEY)?;54
let (_, url) = decoded.split_once(HOSTED_URL_KEY)?;54
is_link_image_url(url).then(|| url.to_owned())55
(is_link_image_url(url) || is_ams_image_url(url)).then(|| url.to_owned())56
}57
58
/// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages.59
pub fn is_ams_image_url(url: &str) -> bool {60
url.strip_prefix("https://")61
.and_then(|rest| rest.split_once('/'))62
.is_some_and(|(host, path)| {63
host.ends_with(AMS_HOST_SUFFIX) && path.starts_with("v1/objects/")64
})55
}65
}56
66
57
pub fn parse_message_links(body: &Value) -> Vec<MessageLinks> {67
pub fn parse_message_links(body: &Value) -> Vec<MessageLinks> {@@ -150,27 +160,30 @@ impl<T: MessageTransport> Messages<T> {150
}160
}151
let answer = self.transport.send(Request::binary_get(url)).await?;161
let answer = self.transport.send(Request::binary_get(url)).await?;152
ensure_success(&answer)?;162
ensure_success(&answer)?;153
let encoded = answer163
decoded_image(&answer.body)154
.body155
.get("base64")156
.and_then(Value::as_str)157
.unwrap_or_default();158
let bytes = STANDARD159
.decode(encoded.as_bytes())160
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;161
let content_type = answer162
.body163
.get("contentType")164
.and_then(Value::as_str)165
.unwrap_or_default()166
.to_owned();167
Ok(LinkImage {168
bytes,169
content_type,170
})171
}164
}172
}165
}173
166
167
/// An image answer shaped `{base64, contentType}`.168
pub(crate) fn decoded_image(body: &Value) -> Result<LinkImage> {169
let encoded = body170
.get("base64")171
.and_then(Value::as_str)172
.unwrap_or_default();173
let bytes = STANDARD174
.decode(encoded.as_bytes())175
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;176
let content_type = body177
.get("contentType")178
.and_then(Value::as_str)179
.unwrap_or_default()180
.to_owned();181
Ok(LinkImage {182
bytes,183
content_type,184
})185
}186
174
#[cfg(test)]187
#[cfg(test)]175
mod tests {188
mod tests {176
use super::*;189
use super::*;@@ -192,6 +205,26 @@ mod tests {192
);205
);193
}206
}194
207
208
#[test]209
fn ams_object_views_are_recognized_inside_hosted_content_ids() {210
let ams = "https://eu-api.asm.skype.com/v1/objects/0-frca-d14-abc/views/imgo";211
assert!(is_ams_image_url(ams));212
let id = STANDARD.encode(format!("id=x_0-frca-d14-abc,type=1,url={ams}"));213
assert_eq!(214
hosted_content_image_url(&format!(215
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{id}/$value"216
))217
.as_deref(),218
Some(ams)219
);220
assert!(!is_ams_image_url(221
"https://evil.example/v1/objects/a/views/imgo"222
));223
assert!(!is_ams_image_url(224
"https://eu-api.asm.skype.com/v1/users/me"225
));226
}227
195
#[test]228
#[test]196
fn parses_link_info_with_target_url_and_thumbnail_size() {229
fn parses_link_info_with_target_url_and_thumbnail_size() {197
let info = parse_link_info(&json!({230
let info = parse_link_info(&json!({@@ -1163,14 +1163,19 @@ impl Remote for Graph {
1163
1163
async fn hosted_content(&self, url: &str) -> Result<Photo> {
1164
1164
let ams_url = chatsvc::hosted_content_image_url(url);
1165
1165
let url = ams_url.as_deref().unwrap_or(url);
1166
if chatsvc::is_link_image_url(url) {
1167
let image = Messages::new(self.session()).link_image(url).await?;
1168
return Ok(Photo {
1169
bytes: image.bytes,
1170
content_type: image.content_type,
1171
});
1172
}
1173
Ok(Graph::download_hosted_content(self, url).await?)
1166
let image = if chatsvc::is_ams_image_url(url) {
1167
chatsvc::ams::Ams::new(self.session())
1168
.download_image(url)
1169
.await?
1170
} else if chatsvc::is_link_image_url(url) {
1171
Messages::new(self.session()).link_image(url).await?
1172
} else {
1173
return Ok(Graph::download_hosted_content(self, url).await?);
1174
};
1175
Ok(Photo {
1176
bytes: image.bytes,
1177
content_type: image.content_type,
1178
})
1174
1179
}
1175
1180
1176
1181
async fn external_image(&self, url: &str) -> Result<Photo> {
@@ -1163,14 +1163,19 @@ impl Remote for Graph {1163
async fn hosted_content(&self, url: &str) -> Result<Photo> {1163
async fn hosted_content(&self, url: &str) -> Result<Photo> {1164
let ams_url = chatsvc::hosted_content_image_url(url);1164
let ams_url = chatsvc::hosted_content_image_url(url);1165
let url = ams_url.as_deref().unwrap_or(url);1165
let url = ams_url.as_deref().unwrap_or(url);1166
if chatsvc::is_link_image_url(url) {1166
let image = if chatsvc::is_ams_image_url(url) {1167
let image = Messages::new(self.session()).link_image(url).await?;1167
chatsvc::ams::Ams::new(self.session())1168
return Ok(Photo {1168
.download_image(url)1169
bytes: image.bytes,1169
.await?1170
content_type: image.content_type,1170
} else if chatsvc::is_link_image_url(url) {1171
});1171
Messages::new(self.session()).link_image(url).await?1172
}1172
} else {1173
Ok(Graph::download_hosted_content(self, url).await?)1173
return Ok(Graph::download_hosted_content(self, url).await?);1174
};1175
Ok(Photo {1176
bytes: image.bytes,1177
content_type: image.content_type,1178
})1174
}1179
}1175
1180
1176
async fn external_image(&self, url: &str) -> Result<Photo> {1181
async fn external_image(&self, url: &str) -> Result<Photo> {