Commit 618b603707

618b60370721d6d5d8076d9705f181b1cb1f81ab

parent: f41c0519f9

Unregistered key

Austin Ray <austin@austinray.io> · 2021-04-04 03:52 UTC

fix: convert mxc to http(s) or emxc

Instead of displaying a matrix content URI (mxc), convert it to a
HTTP(S) link or encrypted matrix content URI (emxc.) This form allows
easy accessible to the file via web browser or helper script. If
conversion isn't possible, default to the mxc link.

Fixes #36

Layout: unified · split

src/render.rs +148 −4
@@ -13,6 +13,7 @@ use matrix_sdk::{
1313 RedactedMessageEventContent, ServerNoticeMessageEventContent,
1414 TextMessageEventContent, VideoMessageEventContent,
1515 },
16 EncryptedFile,
1617 },
1718 RedactedSyncMessageEvent, SyncStateEvent,
1819 },
@@ -310,18 +311,112 @@ impl Render for ServerNoticeMessageEventContent {
310311 }
311312}
312313
314/// Create an HTTP download path from a matrix content URI
315fn mxc_to_http_download_path(
316 mxc_url: Url,
317) -> Result<String, Box<dyn std::error::Error>> {
318 Ok(format!(
319 "/_matrix/media/r0/download/{server_name}{media_id}",
320 server_name = mxc_url.host_str().ok_or("Missing host")?,
321 media_id = mxc_url.path(),
322 ))
323}
324
325/// Convert a matrix content URI to HTTP(s), respecting a user's homeserver
326fn mxc_to_http(
327 mxc_url: &str,
328 homeserver: &Url,
329) -> Result<String, Box<dyn std::error::Error>> {
330 let url = url::Url::parse(mxc_url)?;
331
332 if url.scheme() != "mxc" {
333 return Err("URL missing MXC scheme".into());
334 }
335
336 if url.path().is_empty() {
337 return Err("URL missing path".into());
338 }
339
340 Ok(homeserver
341 .join(&mxc_to_http_download_path(url)?)?
342 .to_string())
343}
344
345/// Convert a matrix content URI to an encrypted mxc URI, respecting a user's homeserver.
346///
347/// The return value of this function will have a URI schema of emxc://. The path of the URI will
348/// be converted just like the mxc_to_http() function does, but it will also contain query
349/// parameters that are necessary to decrypt the payload the URI is pointing to.
350///
351/// This function is useful to present a clickable URI that can be passed to a plumber program that
352/// will download and decrypt the content that the matrix content URI is pointing to.
353///
354/// The returned URI should never be converted to http and opened directly, as that would expose
355/// the decryption parameters to any middleman or ISP.
356fn mxc_to_emxc(
357 mxc_url: &str,
358 homeserver: &Url,
359 encrypted: &EncryptedFile,
360) -> Result<String, Box<dyn std::error::Error>> {
361 let url = url::Url::parse(mxc_url)?;
362
363 if url.scheme() != "mxc" {
364 return Err("URL missing MXC scheme".into());
365 }
366
367 if url.path().is_empty() {
368 return Err("URL missing path".into());
369 }
370
371 let host_str = format!(
372 "emxc://{}",
373 homeserver
374 .host_str()
375 .ok_or("Missing homeserver host string")?
376 );
377
378 let mut emxc_url = url::Url::parse(&host_str)?;
379 emxc_url
380 .set_port(homeserver.port_or_known_default())
381 .map_err(|_| "Can't set port")?;
382
383 emxc_url = emxc_url.join(&mxc_to_http_download_path(url)?)?;
384
385 // Add query parameters
386 emxc_url
387 .query_pairs_mut()
388 .append_pair("key", &encrypted.key.k)
389 .append_pair(
390 "hash",
391 encrypted
392 .hashes
393 .get("sha256")
394 .ok_or("Missing sha256 hash")?,
395 )
396 .append_pair("iv", &encrypted.iv);
397
398 Ok(emxc_url.to_string())
399}
400
313401impl<C: HasUrlOrFile> Render for C {
314402 type RenderContext = Url;
315403 const TAGS: &'static [&'static str] = &["matrix_media"];
316404
317 fn render(&self, _homeserver: &Self::RenderContext) -> RenderedContent {
405 fn render(&self, homeserver: &Self::RenderContext) -> RenderedContent {
406 // Convert MXC to HTTP(s) or EMXC, but fallback to MXC if unable to.
407 let mxc_url = match self.encrypted_file() {
408 Some(encrypted_file) => {
409 mxc_to_emxc(self.resolve_url(), homeserver, &encrypted_file)
410 }
411 None => mxc_to_http(self.resolve_url(), homeserver),
412 }
413 .unwrap_or_else(|_| self.resolve_url().to_string());
414
318415 let message = format!(
319416 "{color_delimiter}<{color_reset}{}{color_delimiter}>\
320417 [{color_reset}{}{color_delimiter}]{color_reset}",
321418 self.body(),
322 // FIXME this isn't right, the MXID -> URL transformation depends on
323 // your homeserver URL.
324 self.resolve_url(),
419 mxc_url,
325420 color_delimiter = Weechat::color("color_delimiter"),
326421 color_reset = Weechat::color("reset")
327422 );
@@ -426,6 +521,7 @@ pub trait HasUrlOrFile {
426521 // `file` must exist and unwrapping will never panic
427522 self.url().or_else(|| self.file()).unwrap()
428523 }
524 fn encrypted_file(&self) -> &Option<Box<EncryptedFile>>;
429525}
430526
431527// Same as above: a simple macro to implement the trait for structs with `url`
@@ -446,6 +542,10 @@ macro_rules! has_url_or_file {
446542 fn file(&self) -> Option<&str> {
447543 self.file.as_ref().map(|f| f.url.as_str())
448544 }
545
546 fn encrypted_file(&self) -> &Option<Box<EncryptedFile>> {
547 &self.file
548 }
449549 }
450550 };
451551}
@@ -613,3 +713,47 @@ pub fn render_membership(
613713 ),
614714 }
615715}
716
717#[cfg(test)]
718mod tests {
719 use super::*;
720
721 #[test]
722 fn test_mxc_to_http() {
723 let homeserver = url::Url::parse("https://matrix.org").unwrap();
724 let mxc_url = "mxc://matrix.org/some-media-id";
725 let expected =
726 "https://matrix.org/_matrix/media/r0/download/matrix.org/some-media-id";
727 assert_eq!(expected, mxc_to_http(&mxc_url, &homeserver).unwrap());
728 }
729
730 #[test]
731 fn test_emxc_to_http() {
732 use matrix_sdk::events::room::JsonWebKey;
733 use std::collections::BTreeMap;
734
735 let homeserver = url::Url::parse("https://matrix.org").unwrap();
736 let mxc_url = "mxc://matrix.org/some-media-id";
737 let mut hashes: BTreeMap<String, String> = BTreeMap::new();
738 hashes.insert("sha256".to_string(), "some-sha256".to_string());
739 let encrypt_info = EncryptedFile {
740 key: JsonWebKey {
741 k: "some-secret-key".to_string(),
742 kty: "oct".to_string(),
743 key_ops: vec![],
744 ext: true,
745 alg: "A256CTR".to_string(),
746 },
747 iv: "some-test-iv".to_string(),
748 v: "v2".to_string(),
749 url: "mxc://some-url".to_string(),
750 hashes,
751 };
752 let expected =
753 "emxc://matrix.org:443/_matrix/media/r0/download/matrix.org/some-media-id?key=some-secret-key&hash=some-sha256&iv=some-test-iv";
754 assert_eq!(
755 expected,
756 mxc_to_emxc(&mxc_url, &homeserver, &encrypt_info).unwrap()
757 );
758 }
759}