Run 'cargo fmt' to format code (#489)
This commit is contained in:
committed by
Baptiste Gelez
parent
732f514da7
commit
b945d1f602
@@ -18,7 +18,8 @@ pub mod sign;
|
||||
pub const CONTEXT_URL: &str = "https://www.w3.org/ns/activitystreams";
|
||||
pub const PUBLIC_VISIBILTY: &str = "https://www.w3.org/ns/activitystreams#Public";
|
||||
|
||||
pub const AP_CONTENT_TYPE: &str = r#"application/ld+json; profile="https://www.w3.org/ns/activitystreams""#;
|
||||
pub const AP_CONTENT_TYPE: &str =
|
||||
r#"application/ld+json; profile="https://www.w3.org/ns/activitystreams""#;
|
||||
|
||||
pub fn ap_accept_header() -> Vec<&'static str> {
|
||||
vec![
|
||||
@@ -114,13 +115,18 @@ pub fn broadcast<S: sign::Signer, A: Activity, T: inbox::WithInbox>(
|
||||
let boxes = to
|
||||
.into_iter()
|
||||
.filter(|u| !u.is_local())
|
||||
.map(|u| u.get_shared_inbox_url().unwrap_or_else(|| u.get_inbox_url()))
|
||||
.map(|u| {
|
||||
u.get_shared_inbox_url()
|
||||
.unwrap_or_else(|| u.get_inbox_url())
|
||||
})
|
||||
.collect::<Vec<String>>()
|
||||
.unique();
|
||||
|
||||
let mut act = serde_json::to_value(act).expect("activity_pub::broadcast: serialization error");
|
||||
act["@context"] = context();
|
||||
let signed = act.sign(sender).expect("activity_pub::broadcast: signature error");
|
||||
let signed = act
|
||||
.sign(sender)
|
||||
.expect("activity_pub::broadcast: signature error");
|
||||
|
||||
for inbox in boxes {
|
||||
// TODO: run it in Sidekiq or something like that
|
||||
@@ -130,7 +136,11 @@ pub fn broadcast<S: sign::Signer, A: Activity, T: inbox::WithInbox>(
|
||||
let res = Client::new()
|
||||
.post(&inbox)
|
||||
.headers(headers.clone())
|
||||
.header("Signature", request::signature(sender, &headers).expect("activity_pub::broadcast: request signature error"))
|
||||
.header(
|
||||
"Signature",
|
||||
request::signature(sender, &headers)
|
||||
.expect("activity_pub::broadcast: request signature error"),
|
||||
)
|
||||
.body(body)
|
||||
.send();
|
||||
match res {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
use base64;
|
||||
use chrono::{offset::Utc, DateTime};
|
||||
use openssl::hash::{Hasher, MessageDigest};
|
||||
use reqwest::header::{ACCEPT, CONTENT_TYPE, DATE, HeaderMap, HeaderValue, USER_AGENT};
|
||||
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, CONTENT_TYPE, DATE, USER_AGENT};
|
||||
use std::ops::Deref;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use activity_pub::{AP_CONTENT_TYPE, ap_accept_header};
|
||||
use activity_pub::sign::Signer;
|
||||
use activity_pub::{ap_accept_header, AP_CONTENT_TYPE};
|
||||
|
||||
const PLUME_USER_AGENT: &str = concat!("Plume/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
@@ -42,7 +42,7 @@ impl Digest {
|
||||
}
|
||||
|
||||
pub fn verify_header(&self, other: &Digest) -> bool {
|
||||
self.value()==other.value()
|
||||
self.value() == other.value()
|
||||
}
|
||||
|
||||
pub fn algorithm(&self) -> &str {
|
||||
@@ -57,7 +57,8 @@ impl Digest {
|
||||
let pos = self
|
||||
.0
|
||||
.find('=')
|
||||
.expect("Digest::value: invalid header error") + 1;
|
||||
.expect("Digest::value: invalid header error")
|
||||
+ 1;
|
||||
base64::decode(&self.0[pos..]).expect("Digest::value: invalid encoding error")
|
||||
}
|
||||
|
||||
@@ -75,8 +76,11 @@ impl Digest {
|
||||
}
|
||||
|
||||
pub fn from_body(body: &str) -> Self {
|
||||
let mut hasher = Hasher::new(MessageDigest::sha256()).expect("Digest::digest: initialization error");
|
||||
hasher.update(body.as_bytes()).expect("Digest::digest: content insertion error");
|
||||
let mut hasher =
|
||||
Hasher::new(MessageDigest::sha256()).expect("Digest::digest: initialization error");
|
||||
hasher
|
||||
.update(body.as_bytes())
|
||||
.expect("Digest::digest: content insertion error");
|
||||
let res = base64::encode(&hasher.finish().expect("Digest::digest: finalizing error"));
|
||||
Digest(format!("SHA-256={}", res))
|
||||
}
|
||||
@@ -99,7 +103,8 @@ pub fn headers() -> HeaderMap {
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
).expect("request::headers: accept error"),
|
||||
)
|
||||
.expect("request::headers: accept error"),
|
||||
);
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static(AP_CONTENT_TYPE));
|
||||
headers
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use super::request;
|
||||
use base64;
|
||||
use chrono::{DateTime, Duration,
|
||||
naive::NaiveDateTime, Utc};
|
||||
use chrono::{naive::NaiveDateTime, DateTime, Duration, Utc};
|
||||
use hex;
|
||||
use openssl::{pkey::PKey, rsa::Rsa, sha::sha256};
|
||||
use rocket::http::HeaderMap;
|
||||
@@ -57,9 +56,10 @@ impl Signable for serde_json::Value {
|
||||
|
||||
let options_hash = Self::hash(
|
||||
&json!({
|
||||
"@context": "https://w3id.org/identity/v1",
|
||||
"created": creation_date
|
||||
}).to_string(),
|
||||
"@context": "https://w3id.org/identity/v1",
|
||||
"created": creation_date
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
let document_hash = Self::hash(&self.to_string());
|
||||
let to_be_signed = options_hash + &document_hash;
|
||||
@@ -91,7 +91,8 @@ impl Signable for serde_json::Value {
|
||||
&json!({
|
||||
"@context": "https://w3id.org/identity/v1",
|
||||
"created": creation_date
|
||||
}).to_string(),
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
let creation_date = creation_date.as_str();
|
||||
if creation_date.is_none() {
|
||||
@@ -169,7 +170,10 @@ pub fn verify_http_headers<S: Signer + ::std::fmt::Debug>(
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
|
||||
if !sender.verify(&h, &base64::decode(signature).unwrap_or_default()).unwrap_or(false) {
|
||||
if !sender
|
||||
.verify(&h, &base64::decode(signature).unwrap_or_default())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return SignatureValidity::Invalid;
|
||||
}
|
||||
if !headers.contains(&"digest") {
|
||||
|
||||
@@ -10,8 +10,8 @@ extern crate chrono;
|
||||
extern crate failure;
|
||||
#[macro_use]
|
||||
extern crate failure_derive;
|
||||
extern crate hex;
|
||||
extern crate heck;
|
||||
extern crate hex;
|
||||
extern crate openssl;
|
||||
extern crate pulldown_cmark;
|
||||
extern crate reqwest;
|
||||
|
||||
+176
-114
@@ -1,18 +1,20 @@
|
||||
use heck::CamelCase;
|
||||
use openssl::rand::rand_bytes;
|
||||
use pulldown_cmark::{Event, Parser, Options, Tag, html};
|
||||
use pulldown_cmark::{html, Event, Options, Parser, Tag};
|
||||
use rocket::{
|
||||
http::uri::Uri,
|
||||
response::{Redirect, Flash}
|
||||
response::{Flash, Redirect},
|
||||
};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// Generates an hexadecimal representation of 32 bytes of random data
|
||||
pub fn random_hex() -> String {
|
||||
let mut bytes = [0; 32];
|
||||
let mut bytes = [0; 32];
|
||||
rand_bytes(&mut bytes).expect("Error while generating client id");
|
||||
bytes.iter().fold(String::new(), |res, byte| format!("{}{:x}", res, byte))
|
||||
bytes
|
||||
.iter()
|
||||
.fold(String::new(), |res, byte| format!("{}{:x}", res, byte))
|
||||
}
|
||||
|
||||
/// Remove non alphanumeric characters and CamelCase a string
|
||||
@@ -29,7 +31,11 @@ pub fn make_actor_id(name: &str) -> String {
|
||||
* Note that the message should be translated before passed to this function.
|
||||
*/
|
||||
pub fn requires_login<T: Into<Uri<'static>>>(message: &str, url: T) -> Flash<Redirect> {
|
||||
Flash::new(Redirect::to(format!("/login?m={}", Uri::percent_encode(message))), "callback", url.into().to_string())
|
||||
Flash::new(
|
||||
Redirect::to(format!("/login?m={}", Uri::percent_encode(message))),
|
||||
"callback",
|
||||
url.into().to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -45,117 +51,161 @@ pub fn md_to_html(md: &str, base_url: &str) -> (String, HashSet<String>, HashSet
|
||||
let parser = Parser::new_ext(md, Options::all());
|
||||
|
||||
let (parser, mentions, hashtags): (Vec<Event>, Vec<String>, Vec<String>) = parser
|
||||
.scan(None, |state: &mut Option<String>, evt|{
|
||||
let (s, res) = match evt {
|
||||
Event::Text(txt) => match state.take() {
|
||||
Some(mut prev_txt) => {
|
||||
prev_txt.push_str(&txt);
|
||||
(Some(prev_txt), vec![])
|
||||
},
|
||||
None => {
|
||||
(Some(txt.into_owned()), vec![])
|
||||
}
|
||||
},
|
||||
e => match state.take() {
|
||||
Some(prev) => (None, vec![Event::Text(Cow::Owned(prev)), e]),
|
||||
None => (None, vec![e]),
|
||||
}
|
||||
};
|
||||
*state = s;
|
||||
Some(res)
|
||||
})
|
||||
.flat_map(|v| v.into_iter())
|
||||
.map(|evt| match evt {
|
||||
Event::Text(txt) => {
|
||||
let (evts, _, _, _, new_mentions, new_hashtags) = txt.chars().fold((vec![], State::Ready, String::new(), 0, vec![], vec![]), |(mut events, state, mut text_acc, n, mut mentions, mut hashtags), c| {
|
||||
match state {
|
||||
State::Mention => {
|
||||
let char_matches = c.is_alphanumeric() || "@.-_".contains(c);
|
||||
if char_matches && (n < (txt.chars().count() - 1)) {
|
||||
text_acc.push(c);
|
||||
(events, State::Mention, text_acc, n + 1, mentions, hashtags)
|
||||
} else {
|
||||
if char_matches {
|
||||
text_acc.push(c)
|
||||
}
|
||||
let mention = text_acc;
|
||||
let short_mention = mention.splitn(1, '@').nth(0).unwrap_or("");
|
||||
let link = Tag::Link(format!("//{}/@/{}/", base_url, &mention).into(), short_mention.to_owned().into());
|
||||
|
||||
mentions.push(mention.clone());
|
||||
events.push(Event::Start(link.clone()));
|
||||
events.push(Event::Text(format!("@{}", &short_mention).into()));
|
||||
events.push(Event::End(link));
|
||||
|
||||
(events, State::Ready, c.to_string(), n + 1, mentions, hashtags)
|
||||
}
|
||||
.scan(None, |state: &mut Option<String>, evt| {
|
||||
let (s, res) = match evt {
|
||||
Event::Text(txt) => match state.take() {
|
||||
Some(mut prev_txt) => {
|
||||
prev_txt.push_str(&txt);
|
||||
(Some(prev_txt), vec![])
|
||||
}
|
||||
State::Hashtag => {
|
||||
let char_matches = c.is_alphanumeric() || "-_".contains(c);
|
||||
if char_matches && (n < (txt.chars().count() -1)) {
|
||||
text_acc.push(c);
|
||||
(events, State::Hashtag, text_acc, n+1, mentions, hashtags)
|
||||
} else {
|
||||
if char_matches {
|
||||
None => (Some(txt.into_owned()), vec![]),
|
||||
},
|
||||
e => match state.take() {
|
||||
Some(prev) => (None, vec![Event::Text(Cow::Owned(prev)), e]),
|
||||
None => (None, vec![e]),
|
||||
},
|
||||
};
|
||||
*state = s;
|
||||
Some(res)
|
||||
})
|
||||
.flat_map(|v| v.into_iter())
|
||||
.map(|evt| match evt {
|
||||
Event::Text(txt) => {
|
||||
let (evts, _, _, _, new_mentions, new_hashtags) = txt.chars().fold(
|
||||
(vec![], State::Ready, String::new(), 0, vec![], vec![]),
|
||||
|(mut events, state, mut text_acc, n, mut mentions, mut hashtags), c| {
|
||||
match state {
|
||||
State::Mention => {
|
||||
let char_matches = c.is_alphanumeric() || "@.-_".contains(c);
|
||||
if char_matches && (n < (txt.chars().count() - 1)) {
|
||||
text_acc.push(c);
|
||||
(events, State::Mention, text_acc, n + 1, mentions, hashtags)
|
||||
} else {
|
||||
if char_matches {
|
||||
text_acc.push(c)
|
||||
}
|
||||
let mention = text_acc;
|
||||
let short_mention = mention.splitn(1, '@').nth(0).unwrap_or("");
|
||||
let link = Tag::Link(
|
||||
format!("//{}/@/{}/", base_url, &mention).into(),
|
||||
short_mention.to_owned().into(),
|
||||
);
|
||||
|
||||
mentions.push(mention.clone());
|
||||
events.push(Event::Start(link.clone()));
|
||||
events.push(Event::Text(format!("@{}", &short_mention).into()));
|
||||
events.push(Event::End(link));
|
||||
|
||||
(
|
||||
events,
|
||||
State::Ready,
|
||||
c.to_string(),
|
||||
n + 1,
|
||||
mentions,
|
||||
hashtags,
|
||||
)
|
||||
}
|
||||
}
|
||||
State::Hashtag => {
|
||||
let char_matches = c.is_alphanumeric() || "-_".contains(c);
|
||||
if char_matches && (n < (txt.chars().count() - 1)) {
|
||||
text_acc.push(c);
|
||||
(events, State::Hashtag, text_acc, n + 1, mentions, hashtags)
|
||||
} else {
|
||||
if char_matches {
|
||||
text_acc.push(c);
|
||||
}
|
||||
let hashtag = text_acc;
|
||||
let link = Tag::Link(
|
||||
format!("//{}/tag/{}", base_url, &hashtag.to_camel_case())
|
||||
.into(),
|
||||
hashtag.to_owned().into(),
|
||||
);
|
||||
|
||||
hashtags.push(hashtag.clone());
|
||||
events.push(Event::Start(link.clone()));
|
||||
events.push(Event::Text(format!("#{}", &hashtag).into()));
|
||||
events.push(Event::End(link));
|
||||
|
||||
(
|
||||
events,
|
||||
State::Ready,
|
||||
c.to_string(),
|
||||
n + 1,
|
||||
mentions,
|
||||
hashtags,
|
||||
)
|
||||
}
|
||||
}
|
||||
State::Ready => {
|
||||
if c == '@' {
|
||||
events.push(Event::Text(text_acc.into()));
|
||||
(
|
||||
events,
|
||||
State::Mention,
|
||||
String::new(),
|
||||
n + 1,
|
||||
mentions,
|
||||
hashtags,
|
||||
)
|
||||
} else if c == '#' {
|
||||
events.push(Event::Text(text_acc.into()));
|
||||
(
|
||||
events,
|
||||
State::Hashtag,
|
||||
String::new(),
|
||||
n + 1,
|
||||
mentions,
|
||||
hashtags,
|
||||
)
|
||||
} else if c.is_alphanumeric() {
|
||||
text_acc.push(c);
|
||||
if n >= (txt.chars().count() - 1) {
|
||||
// Add the text after at the end, even if it is not followed by a mention.
|
||||
events.push(Event::Text(text_acc.clone().into()))
|
||||
}
|
||||
(events, State::Word, text_acc, n + 1, mentions, hashtags)
|
||||
} else {
|
||||
text_acc.push(c);
|
||||
if n >= (txt.chars().count() - 1) {
|
||||
// Add the text after at the end, even if it is not followed by a mention.
|
||||
events.push(Event::Text(text_acc.clone().into()))
|
||||
}
|
||||
(events, State::Ready, text_acc, n + 1, mentions, hashtags)
|
||||
}
|
||||
}
|
||||
State::Word => {
|
||||
text_acc.push(c);
|
||||
if c.is_alphanumeric() {
|
||||
if n >= (txt.chars().count() - 1) {
|
||||
// Add the text after at the end, even if it is not followed by a mention.
|
||||
events.push(Event::Text(text_acc.clone().into()))
|
||||
}
|
||||
(events, State::Word, text_acc, n + 1, mentions, hashtags)
|
||||
} else {
|
||||
if n >= (txt.chars().count() - 1) {
|
||||
// Add the text after at the end, even if it is not followed by a mention.
|
||||
events.push(Event::Text(text_acc.clone().into()))
|
||||
}
|
||||
(events, State::Ready, text_acc, n + 1, mentions, hashtags)
|
||||
}
|
||||
}
|
||||
let hashtag = text_acc;
|
||||
let link = Tag::Link(format!("//{}/tag/{}", base_url, &hashtag.to_camel_case()).into(), hashtag.to_owned().into());
|
||||
|
||||
hashtags.push(hashtag.clone());
|
||||
events.push(Event::Start(link.clone()));
|
||||
events.push(Event::Text(format!("#{}", &hashtag).into()));
|
||||
events.push(Event::End(link));
|
||||
|
||||
(events, State::Ready, c.to_string(), n + 1, mentions, hashtags)
|
||||
}
|
||||
}
|
||||
State::Ready => {
|
||||
if c == '@' {
|
||||
events.push(Event::Text(text_acc.into()));
|
||||
(events, State::Mention, String::new(), n + 1, mentions, hashtags)
|
||||
} else if c == '#' {
|
||||
events.push(Event::Text(text_acc.into()));
|
||||
(events, State::Hashtag, String::new(), n + 1, mentions, hashtags)
|
||||
} else if c.is_alphanumeric() {
|
||||
text_acc.push(c);
|
||||
if n >= (txt.chars().count() - 1) { // Add the text after at the end, even if it is not followed by a mention.
|
||||
events.push(Event::Text(text_acc.clone().into()))
|
||||
}
|
||||
(events, State::Word, text_acc, n + 1, mentions, hashtags)
|
||||
} else {
|
||||
text_acc.push(c);
|
||||
if n >= (txt.chars().count() - 1) { // Add the text after at the end, even if it is not followed by a mention.
|
||||
events.push(Event::Text(text_acc.clone().into()))
|
||||
}
|
||||
(events, State::Ready, text_acc, n + 1, mentions, hashtags)
|
||||
}
|
||||
}
|
||||
State::Word => {
|
||||
text_acc.push(c);
|
||||
if c.is_alphanumeric() {
|
||||
if n >= (txt.chars().count() - 1) { // Add the text after at the end, even if it is not followed by a mention.
|
||||
events.push(Event::Text(text_acc.clone().into()))
|
||||
}
|
||||
(events, State::Word, text_acc, n + 1, mentions, hashtags)
|
||||
} else {
|
||||
if n >= (txt.chars().count() - 1) { // Add the text after at the end, even if it is not followed by a mention.
|
||||
events.push(Event::Text(text_acc.clone().into()))
|
||||
}
|
||||
(events, State::Ready, text_acc, n + 1, mentions, hashtags)
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
(evts, new_mentions, new_hashtags)
|
||||
},
|
||||
_ => (vec![evt], vec![], vec![])
|
||||
}).fold((vec![],vec![],vec![]), |(mut parser, mut mention, mut hashtag), (mut p, mut m, mut h)| {
|
||||
parser.append(&mut p);
|
||||
mention.append(&mut m);
|
||||
hashtag.append(&mut h);
|
||||
(parser, mention, hashtag)
|
||||
});
|
||||
},
|
||||
);
|
||||
(evts, new_mentions, new_hashtags)
|
||||
}
|
||||
_ => (vec![evt], vec![], vec![]),
|
||||
})
|
||||
.fold(
|
||||
(vec![], vec![], vec![]),
|
||||
|(mut parser, mut mention, mut hashtag), (mut p, mut m, mut h)| {
|
||||
parser.append(&mut p);
|
||||
mention.append(&mut m);
|
||||
hashtag.append(&mut h);
|
||||
(parser, mention, hashtag)
|
||||
},
|
||||
);
|
||||
let parser = parser.into_iter();
|
||||
let mentions = mentions.into_iter().map(|m| String::from(m.trim()));
|
||||
let hashtags = hashtags.into_iter().map(|h| String::from(h.trim()));
|
||||
@@ -188,7 +238,13 @@ mod tests {
|
||||
];
|
||||
|
||||
for (md, mentions) in tests {
|
||||
assert_eq!(md_to_html(md, "").1, mentions.into_iter().map(|s| s.to_string()).collect::<HashSet<String>>());
|
||||
assert_eq!(
|
||||
md_to_html(md, "").1,
|
||||
mentions
|
||||
.into_iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect::<HashSet<String>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,7 +263,13 @@ mod tests {
|
||||
];
|
||||
|
||||
for (md, mentions) in tests {
|
||||
assert_eq!(md_to_html(md, "").2, mentions.into_iter().map(|s| s.to_string()).collect::<HashSet<String>>());
|
||||
assert_eq!(
|
||||
md_to_html(md, "").2,
|
||||
mentions
|
||||
.into_iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect::<HashSet<String>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user