Normalize panic message
Change all unwrap to expect Normalize expect's messages Don't panic where it could be avoided easily
This commit is contained in:
parent
9d70eeae61
commit
4e6f3209d5
|
@ -27,7 +27,7 @@ fn main() {
|
|||
match matches.subcommand() {
|
||||
("instance", Some(args)) => instance::run(args, &conn.expect("Couldn't connect to the database.")),
|
||||
("users", Some(args)) => users::run(args, &conn.expect("Couldn't connect to the database.")),
|
||||
_ => app.print_help().unwrap()
|
||||
_ => app.print_help().expect("Couldn't print help")
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
@ -17,7 +17,7 @@ pub trait FromActivity<T: Object, C>: Sized {
|
|||
|
||||
fn try_from_activity(conn: &C, act: Create) -> bool {
|
||||
if let Ok(obj) = act.create_props.object_object() {
|
||||
Self::from_activity(conn, obj, act.create_props.actor_link::<Id>().unwrap());
|
||||
Self::from_activity(conn, obj, act.create_props.actor_link::<Id>().expect("FromActivity::try_from_activity: id not found error"));
|
||||
true
|
||||
} else {
|
||||
false
|
||||
|
|
|
@ -82,14 +82,13 @@ impl<'a, 'r> FromRequest<'a, 'r> for ApRequest {
|
|||
"application/ld+json" => Outcome::Success(ApRequest),
|
||||
"text/html" => Outcome::Forward(true),
|
||||
_ => Outcome::Forward(false)
|
||||
}).fold(Outcome::Forward(false), |out, ct| if out.is_success() || (out.is_forward() && out.clone().forwarded().unwrap()) {
|
||||
}).fold(Outcome::Forward(false), |out, ct| if out.clone().forwarded().unwrap_or(out.is_success()) {
|
||||
out
|
||||
} else {
|
||||
ct
|
||||
}).map_forward(|_| ())).unwrap_or(Outcome::Forward(()))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn broadcast<S: sign::Signer, A: Activity, T: inbox::WithInbox + Actor>(sender: &S, act: A, to: Vec<T>) {
|
||||
let boxes = to.into_iter()
|
||||
.filter(|u| !u.is_local())
|
||||
|
@ -97,7 +96,8 @@ pub fn broadcast<S: sign::Signer, A: Activity, T: inbox::WithInbox + Actor>(send
|
|||
.collect::<Vec<String>>()
|
||||
.unique();
|
||||
|
||||
let mut act = serde_json::to_value(act).unwrap();
|
||||
|
||||
let mut act = serde_json::to_value(act).expect("activity_pub::broadcast: serialization error");
|
||||
act["@context"] = context();
|
||||
let signed = act.sign(sender);
|
||||
|
||||
|
@ -112,7 +112,14 @@ pub fn broadcast<S: sign::Signer, A: Activity, T: inbox::WithInbox + Actor>(send
|
|||
.body(signed.to_string())
|
||||
.send();
|
||||
match res {
|
||||
Ok(mut r) => println!("Successfully sent activity to inbox ({})\n\n{:?}", inbox, r.text().unwrap()),
|
||||
Ok(mut r) => {
|
||||
println!("Successfully sent activity to inbox ({})", inbox);
|
||||
if let Ok(response) = r.text() {
|
||||
println!("Response: \"{:?}\"\n\n", response)
|
||||
} else {
|
||||
println!("Error while reading response")
|
||||
}
|
||||
},
|
||||
Err(e) => println!("Error while sending to inbox ({:?})", e)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -14,30 +14,30 @@ pub struct Digest(String);
|
|||
|
||||
impl Digest {
|
||||
pub fn digest(body: String) -> HeaderValue {
|
||||
let mut hasher = Hasher::new(MessageDigest::sha256()).unwrap();
|
||||
hasher.update(&body.into_bytes()[..]).unwrap();
|
||||
let res = base64::encode(&hasher.finish().unwrap());
|
||||
HeaderValue::from_str(&format!("SHA-256={}", res)).unwrap()
|
||||
let mut hasher = Hasher::new(MessageDigest::sha256()).expect("Digest::digest: initialization error");
|
||||
hasher.update(&body.into_bytes()[..]).expect("Digest::digest: content insertion error");
|
||||
let res = base64::encode(&hasher.finish().expect("Digest::digest: finalizing error"));
|
||||
HeaderValue::from_str(&format!("SHA-256={}", res)).expect("Digest::digest: header creation error")
|
||||
}
|
||||
|
||||
pub fn verify(&self, body: String) -> bool {
|
||||
if self.algorithm()=="SHA-256" {
|
||||
let mut hasher = Hasher::new(MessageDigest::sha256()).unwrap();
|
||||
hasher.update(&body.into_bytes()).unwrap();
|
||||
self.value().deref()==hasher.finish().unwrap().deref()
|
||||
let mut hasher = Hasher::new(MessageDigest::sha256()).expect("Digest::digest: initialization error");
|
||||
hasher.update(&body.into_bytes()).expect("Digest::digest: content insertion error");
|
||||
self.value().deref()==hasher.finish().expect("Digest::digest: finalizing error").deref()
|
||||
} else {
|
||||
false //algorithm not supported
|
||||
}
|
||||
}
|
||||
|
||||
pub fn algorithm(&self) -> &str {
|
||||
let pos = self.0.find('=').unwrap();
|
||||
let pos = self.0.find('=').expect("Digest::algorithm: invalid header error");
|
||||
&self.0[..pos]
|
||||
}
|
||||
|
||||
pub fn value(&self) -> Vec<u8> {
|
||||
let pos = self.0.find('=').unwrap()+1;
|
||||
base64::decode(&self.0[pos..]).unwrap()
|
||||
let pos = self.0.find('=').expect("Digest::value: invalid header error")+1;
|
||||
base64::decode(&self.0[pos..]).expect("Digest::value: invalid encoding error")
|
||||
}
|
||||
|
||||
pub fn from_header(dig: &str) -> Result<Self, ()> {
|
||||
|
@ -60,13 +60,13 @@ pub fn headers() -> HeaderMap {
|
|||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(USER_AGENT, HeaderValue::from_static(PLUME_USER_AGENT));
|
||||
headers.insert(DATE, HeaderValue::from_str(&date).unwrap());
|
||||
headers.insert(ACCEPT, HeaderValue::from_str(&ap_accept_header().into_iter().collect::<Vec<_>>().join(", ")).unwrap());
|
||||
headers.insert(DATE, HeaderValue::from_str(&date).expect("request::headers: date error"));
|
||||
headers.insert(ACCEPT, HeaderValue::from_str(&ap_accept_header().into_iter().collect::<Vec<_>>().join(", ")).expect("request::headers: accept error"));
|
||||
headers
|
||||
}
|
||||
|
||||
pub fn signature<S: Signer>(signer: &S, headers: HeaderMap) -> HeaderValue {
|
||||
let signed_string = headers.iter().map(|(h,v)| format!("{}: {}", h.as_str().to_lowercase(), v.to_str().unwrap())).collect::<Vec<String>>().join("\n");
|
||||
let signed_string = headers.iter().map(|(h,v)| format!("{}: {}", h.as_str().to_lowercase(), v.to_str().expect("request::signature: invalid header error"))).collect::<Vec<String>>().join("\n");
|
||||
let signed_headers = headers.iter().map(|(h,_)| h.as_str()).collect::<Vec<&str>>().join(" ").to_lowercase();
|
||||
|
||||
let data = signer.sign(signed_string);
|
||||
|
@ -77,5 +77,5 @@ pub fn signature<S: Signer>(signer: &S, headers: HeaderMap) -> HeaderValue {
|
|||
key_id = signer.get_key_id(),
|
||||
signed_headers = signed_headers,
|
||||
signature = sign
|
||||
)).unwrap()
|
||||
)).expect("request::signature: signature header error")
|
||||
}
|
||||
|
|
|
@ -12,9 +12,12 @@ use serde_json;
|
|||
|
||||
/// Returns (public key, private key)
|
||||
pub fn gen_keypair() -> (Vec<u8>, Vec<u8>) {
|
||||
let keypair = Rsa::generate(2048).unwrap();
|
||||
let keypair = PKey::from_rsa(keypair).unwrap();
|
||||
(keypair.public_key_to_pem().unwrap(), keypair.private_key_to_pem_pkcs8().unwrap())
|
||||
let keypair = Rsa::generate(2048).expect("sign::gen_keypair: key generation error");
|
||||
let keypair = PKey::from_rsa(keypair).expect("sign::gen_keypair: parsing error");
|
||||
(
|
||||
keypair.public_key_to_pem().expect("sign::gen_keypair: public key encoding error"),
|
||||
keypair.private_key_to_pem_pkcs8().expect("sign::gen_keypair: private key encoding error")
|
||||
)
|
||||
}
|
||||
|
||||
pub trait Signer {
|
||||
|
@ -101,7 +104,7 @@ pub fn verify_http_headers<S: Signer+::std::fmt::Debug>(sender: &S, all_headers:
|
|||
if sig_header.is_none() {
|
||||
return SignatureValidity::Absent
|
||||
}
|
||||
let sig_header = sig_header.unwrap();
|
||||
let sig_header = sig_header.expect("sign::verify_http_headers: unreachable");
|
||||
|
||||
let mut _key_id = None;
|
||||
let mut _algorithm = None;
|
||||
|
@ -120,8 +123,8 @@ pub fn verify_http_headers<S: Signer+::std::fmt::Debug>(sender: &S, all_headers:
|
|||
if signature.is_none() || headers.is_none() {//missing part of the header
|
||||
return SignatureValidity::Invalid
|
||||
}
|
||||
let headers = headers.unwrap().split_whitespace().collect::<Vec<_>>();
|
||||
let signature = signature.unwrap();
|
||||
let headers = headers.expect("sign::verify_http_headers: unreachable").split_whitespace().collect::<Vec<_>>();
|
||||
let signature = signature.expect("sign::verify_http_headers: unreachable");
|
||||
let h = headers.iter()
|
||||
.map(|header| (header,all_headers.get_one(header)))
|
||||
.map(|(header, value)| format!("{}: {}", header.to_lowercase(), value.unwrap_or("")))
|
||||
|
|
|
@ -65,7 +65,7 @@ impl Blog {
|
|||
find_by!(blogs, find_by_name, actor_id as String, instance_id as i32);
|
||||
|
||||
pub fn get_instance(&self, conn: &Connection) -> Instance {
|
||||
Instance::get(conn, self.instance_id).expect("Couldn't find instance")
|
||||
Instance::get(conn, self.instance_id).expect("Blog::get_instance: instance not found error")
|
||||
}
|
||||
|
||||
pub fn list_authors(&self, conn: &Connection) -> Vec<User> {
|
||||
|
@ -74,7 +74,7 @@ impl Blog {
|
|||
let authors_ids = blog_authors::table.filter(blog_authors::blog_id.eq(self.id)).select(blog_authors::author_id);
|
||||
users::table.filter(users::id.eq_any(authors_ids))
|
||||
.load::<User>(conn)
|
||||
.expect("Couldn't load authors of a blog")
|
||||
.expect("Blog::list_authors: author loading error")
|
||||
}
|
||||
|
||||
pub fn find_for_author(conn: &Connection, author_id: i32) -> Vec<Blog> {
|
||||
|
@ -82,7 +82,7 @@ impl Blog {
|
|||
let author_ids = blog_authors::table.filter(blog_authors::author_id.eq(author_id)).select(blog_authors::blog_id);
|
||||
blogs::table.filter(blogs::id.eq_any(author_ids))
|
||||
.load::<Blog>(conn)
|
||||
.expect("Couldn't load blogs ")
|
||||
.expect("Blog::find_for_author: blog loading error")
|
||||
}
|
||||
|
||||
pub fn find_local(conn: &Connection, name: String) -> Option<Blog> {
|
||||
|
@ -91,9 +91,9 @@ impl Blog {
|
|||
|
||||
pub fn find_by_fqn(conn: &Connection, fqn: String) -> Option<Blog> {
|
||||
if fqn.contains("@") { // remote blog
|
||||
match Instance::find_by_domain(conn, String::from(fqn.split("@").last().unwrap())) {
|
||||
match Instance::find_by_domain(conn, String::from(fqn.split("@").last().expect("Blog::find_by_fqn: unreachable"))) {
|
||||
Some(instance) => {
|
||||
match Blog::find_by_name(conn, String::from(fqn.split("@").nth(0).unwrap()), instance.id) {
|
||||
match Blog::find_by_name(conn, String::from(fqn.split("@").nth(0).expect("Blog::find_by_fqn: unreachable")), instance.id) {
|
||||
Some(u) => Some(u),
|
||||
None => Blog::fetch_from_webfinger(conn, fqn)
|
||||
}
|
||||
|
@ -107,7 +107,7 @@ impl Blog {
|
|||
|
||||
fn fetch_from_webfinger(conn: &Connection, acct: String) -> Option<Blog> {
|
||||
match resolve(acct.clone(), *USE_HTTPS) {
|
||||
Ok(wf) => wf.links.into_iter().find(|l| l.mime_type == Some(String::from("application/activity+json"))).and_then(|l| Blog::fetch_from_url(conn, l.href.expect("No href for AP WF link"))),
|
||||
Ok(wf) => wf.links.into_iter().find(|l| l.mime_type == Some(String::from("application/activity+json"))).and_then(|l| Blog::fetch_from_url(conn, l.href.expect("Blog::fetch_from_webfinger: href not found error"))),
|
||||
Err(details) => {
|
||||
println!("{:?}", details);
|
||||
None
|
||||
|
@ -118,15 +118,15 @@ impl Blog {
|
|||
fn fetch_from_url(conn: &Connection, url: String) -> Option<Blog> {
|
||||
let req = Client::new()
|
||||
.get(&url[..])
|
||||
.header(ACCEPT, HeaderValue::from_str(&ap_accept_header().into_iter().collect::<Vec<_>>().join(", ")).unwrap())
|
||||
.header(ACCEPT, HeaderValue::from_str(&ap_accept_header().into_iter().collect::<Vec<_>>().join(", ")).expect("Blog::fetch_from_url: accept_header generation error"))
|
||||
.send();
|
||||
match req {
|
||||
Ok(mut res) => {
|
||||
let text = &res.text().unwrap();
|
||||
let ap_sign: ApSignature = serde_json::from_str(text).unwrap();
|
||||
let mut json: CustomGroup = serde_json::from_str(text).unwrap();
|
||||
let text = &res.text().expect("Blog::fetch_from_url: body reading error");
|
||||
let ap_sign: ApSignature = serde_json::from_str(text).expect("Blog::fetch_from_url: body parsing error");
|
||||
let mut json: CustomGroup = serde_json::from_str(text).expect("Blog::fetch_from_url: body parsing error");
|
||||
json.custom_props = ap_sign; // without this workaround, publicKey is not correctly deserialized
|
||||
Some(Blog::from_activity(conn, json, Url::parse(url.as_ref()).unwrap().host_str().unwrap().to_string()))
|
||||
Some(Blog::from_activity(conn, json, Url::parse(url.as_ref()).expect("Blog::fetch_from_url: url parsing error").host_str().expect("Blog::fetch_from_url: host extraction error").to_string()))
|
||||
},
|
||||
Err(_) => None
|
||||
}
|
||||
|
@ -188,26 +188,26 @@ impl Blog {
|
|||
if self.outbox_url.len() == 0 {
|
||||
diesel::update(self)
|
||||
.set(blogs::outbox_url.eq(instance.compute_box(BLOG_PREFIX, self.actor_id.clone(), "outbox")))
|
||||
.execute(conn).expect("Couldn't update outbox URL");
|
||||
.execute(conn).expect("Blog::update_boxes: outbox update error");
|
||||
}
|
||||
|
||||
if self.inbox_url.len() == 0 {
|
||||
diesel::update(self)
|
||||
.set(blogs::inbox_url.eq(instance.compute_box(BLOG_PREFIX, self.actor_id.clone(), "inbox")))
|
||||
.execute(conn).expect("Couldn't update inbox URL");
|
||||
.execute(conn).expect("Blog::update_boxes: inbox update error");
|
||||
}
|
||||
|
||||
if self.ap_url.len() == 0 {
|
||||
diesel::update(self)
|
||||
.set(blogs::ap_url.eq(instance.compute_box(BLOG_PREFIX, self.actor_id.clone(), "")))
|
||||
.execute(conn).expect("Couldn't update AP URL");
|
||||
.execute(conn).expect("Blog::update_boxes: ap_url update error");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn outbox(&self, conn: &Connection) -> ActivityStream<OrderedCollection> {
|
||||
let mut coll = OrderedCollection::default();
|
||||
coll.collection_props.items = serde_json::to_value(self.get_activities(conn)).unwrap();
|
||||
coll.collection_props.set_total_items_u64(self.get_activities(conn).len() as u64).unwrap();
|
||||
coll.collection_props.items = serde_json::to_value(self.get_activities(conn)).expect("Blog::outbox: activity serialization error");
|
||||
coll.collection_props.set_total_items_u64(self.get_activities(conn).len() as u64).expect("Blog::outbox: count serialization error");
|
||||
ActivityStream::new(coll)
|
||||
}
|
||||
|
||||
|
@ -216,7 +216,9 @@ impl Blog {
|
|||
}
|
||||
|
||||
pub fn get_keypair(&self) -> PKey<Private> {
|
||||
PKey::from_rsa(Rsa::private_key_from_pem(self.private_key.clone().unwrap().as_ref()).unwrap()).unwrap()
|
||||
PKey::from_rsa(Rsa::private_key_from_pem(self.private_key.clone().expect("Blog::get_keypair: private key not found error").as_ref())
|
||||
.expect("Blog::get_keypair: pem parsing error"))
|
||||
.expect("Blog::get_keypair: private key deserialization error")
|
||||
}
|
||||
|
||||
pub fn webfinger(&self, conn: &Connection) -> Webfinger {
|
||||
|
@ -248,9 +250,9 @@ impl Blog {
|
|||
|
||||
pub fn from_url(conn: &Connection, url: String) -> Option<Blog> {
|
||||
Blog::find_by_ap_url(conn, url.clone()).or_else(|| {
|
||||
// The requested user was not in the DB
|
||||
// The requested blog was not in the DB
|
||||
// We try to fetch it if it is remote
|
||||
if Url::parse(url.as_ref()).unwrap().host_str().unwrap() != BASE_URL.as_str() {
|
||||
if Url::parse(url.as_ref()).expect("Blog::from_url: ap_url parsing error").host_str().expect("Blog::from_url: host extraction error") != BASE_URL.as_str() {
|
||||
Blog::fetch_from_url(conn, url)
|
||||
} else {
|
||||
None
|
||||
|
@ -267,7 +269,7 @@ impl Blog {
|
|||
}
|
||||
|
||||
pub fn to_json(&self, conn: &Connection) -> serde_json::Value {
|
||||
let mut json = serde_json::to_value(self).unwrap();
|
||||
let mut json = serde_json::to_value(self).expect("Blog::to_json: serialization error");
|
||||
json["fqn"] = json!(self.get_fqn(conn));
|
||||
json
|
||||
}
|
||||
|
@ -303,16 +305,17 @@ impl sign::Signer for Blog {
|
|||
|
||||
fn sign(&self, to_sign: String) -> Vec<u8> {
|
||||
let key = self.get_keypair();
|
||||
let mut signer = Signer::new(MessageDigest::sha256(), &key).unwrap();
|
||||
signer.update(to_sign.as_bytes()).unwrap();
|
||||
signer.sign_to_vec().unwrap()
|
||||
let mut signer = Signer::new(MessageDigest::sha256(), &key).expect("Blog::sign: initialization error");
|
||||
signer.update(to_sign.as_bytes()).expect("Blog::sign: content insertion error");
|
||||
signer.sign_to_vec().expect("Blog::sign: finalization error")
|
||||
}
|
||||
|
||||
fn verify(&self, data: String, signature: Vec<u8>) -> bool {
|
||||
let key = PKey::from_rsa(Rsa::public_key_from_pem(self.public_key.as_ref()).unwrap()).unwrap();
|
||||
let mut verifier = Verifier::new(MessageDigest::sha256(), &key).unwrap();
|
||||
verifier.update(data.as_bytes()).unwrap();
|
||||
verifier.verify(&signature).unwrap()
|
||||
let key = PKey::from_rsa(Rsa::public_key_from_pem(self.public_key.as_ref()).expect("Blog::verify: pem parsing error"))
|
||||
.expect("Blog::verify: deserialization error");
|
||||
let mut verifier = Verifier::new(MessageDigest::sha256(), &key).expect("Blog::verify: initialization error");
|
||||
verifier.update(data.as_bytes()).expect("Blog::verify: content insertion error");
|
||||
verifier.verify(&signature).expect("Blog::verify: finalization error")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -332,8 +335,8 @@ impl NewBlog {
|
|||
inbox_url: String::from(""),
|
||||
instance_id: instance_id,
|
||||
ap_url: String::from(""),
|
||||
public_key: String::from_utf8(pub_key).unwrap(),
|
||||
private_key: Some(String::from_utf8(priv_key).unwrap())
|
||||
public_key: String::from_utf8(pub_key).expect("NewBlog::new_local: public key error"),
|
||||
private_key: Some(String::from_utf8(priv_key).expect("NewBlog::new_local: private key error"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -53,11 +53,11 @@ impl Comment {
|
|||
find_by!(comments, find_by_ap_url, ap_url as String);
|
||||
|
||||
pub fn get_author(&self, conn: &Connection) -> User {
|
||||
User::get(conn, self.author_id).unwrap()
|
||||
User::get(conn, self.author_id).expect("Comment::get_author: author error")
|
||||
}
|
||||
|
||||
pub fn get_post(&self, conn: &Connection) -> Post {
|
||||
Post::get(conn, self.post_id).unwrap()
|
||||
Post::get(conn, self.post_id).expect("Comment::get_post: post error")
|
||||
}
|
||||
|
||||
pub fn count_local(conn: &Connection) -> usize {
|
||||
|
@ -65,17 +65,17 @@ impl Comment {
|
|||
let local_authors = users::table.filter(users::instance_id.eq(Instance::local_id(conn))).select(users::id);
|
||||
comments::table.filter(comments::author_id.eq_any(local_authors))
|
||||
.load::<Comment>(conn)
|
||||
.expect("Couldn't load local comments")
|
||||
.len()
|
||||
.expect("Comment::count_local: loading error")
|
||||
.len()// TODO count in database?
|
||||
}
|
||||
|
||||
pub fn to_json(&self, conn: &Connection, others: &Vec<Comment>) -> serde_json::Value {
|
||||
let mut json = serde_json::to_value(self).unwrap();
|
||||
let mut json = serde_json::to_value(self).expect("Comment::to_json: serialization error");
|
||||
json["author"] = self.get_author(conn).to_json(conn);
|
||||
let mentions = Mention::list_for_comment(conn, self.id).into_iter()
|
||||
.map(|m| m.get_mentioned(conn).map(|u| u.get_fqn(conn)).unwrap_or(String::new()))
|
||||
.collect::<Vec<String>>();
|
||||
json["mentions"] = serde_json::to_value(mentions).unwrap();
|
||||
json["mentions"] = serde_json::to_value(mentions).expect("Comment::to_json: mention error");
|
||||
json["responses"] = json!(others.into_iter()
|
||||
.filter(|c| c.in_response_to_id.map(|id| id == self.id).unwrap_or(false))
|
||||
.map(|c| c.to_json(conn, others))
|
||||
|
@ -88,8 +88,8 @@ impl Comment {
|
|||
diesel::update(self)
|
||||
.set(comments::ap_url.eq(self.compute_id(conn)))
|
||||
.execute(conn)
|
||||
.expect("Failed to update comment AP URL");
|
||||
Comment::get(conn, self.id).expect("Couldn't get the updated comment")
|
||||
.expect("Comment::update_ap_url: update error");
|
||||
Comment::get(conn, self.id).expect("Comment::update_ap_url: get error")
|
||||
} else {
|
||||
self.clone()
|
||||
}
|
||||
|
@ -102,53 +102,53 @@ impl Comment {
|
|||
pub fn into_activity(&self, conn: &Connection) -> Note {
|
||||
let (html, mentions) = utils::md_to_html(self.content.get().as_ref());
|
||||
|
||||
let author = User::get(conn, self.author_id).unwrap();
|
||||
let author = User::get(conn, self.author_id).expect("Comment::into_activity: author error");
|
||||
let mut note = Note::default();
|
||||
let to = vec![Id::new(PUBLIC_VISIBILTY.to_string())];
|
||||
|
||||
note.object_props.set_id_string(self.ap_url.clone().unwrap_or(String::new())).expect("NewComment::create: note.id error");
|
||||
note.object_props.set_summary_string(self.spoiler_text.clone()).expect("NewComment::create: note.summary error");
|
||||
note.object_props.set_content_string(html).expect("NewComment::create: note.content error");
|
||||
note.object_props.set_in_reply_to_link(Id::new(self.in_response_to_id.map_or_else(|| Post::get(conn, self.post_id).unwrap().ap_url, |id| {
|
||||
let comm = Comment::get(conn, id).unwrap();
|
||||
note.object_props.set_id_string(self.ap_url.clone().unwrap_or(String::new())).expect("Comment::into_activity: id error");
|
||||
note.object_props.set_summary_string(self.spoiler_text.clone()).expect("Comment::into_activity: summary error");
|
||||
note.object_props.set_content_string(html).expect("Comment::into_activity: content error");
|
||||
note.object_props.set_in_reply_to_link(Id::new(self.in_response_to_id.map_or_else(|| Post::get(conn, self.post_id).expect("Comment::into_activity: post error").ap_url, |id| {
|
||||
let comm = Comment::get(conn, id).expect("Comment::into_activity: comment error");
|
||||
comm.ap_url.clone().unwrap_or(comm.compute_id(conn))
|
||||
}))).expect("NewComment::create: note.in_reply_to error");
|
||||
note.object_props.set_published_string(chrono::Utc::now().to_rfc3339()).expect("NewComment::create: note.published error");
|
||||
note.object_props.set_attributed_to_link(author.clone().into_id()).expect("NewComment::create: note.attributed_to error");
|
||||
note.object_props.set_to_link_vec(to.clone()).expect("NewComment::create: note.to error");
|
||||
}))).expect("Comment::into_activity: in_reply_to error");
|
||||
note.object_props.set_published_string(chrono::Utc::now().to_rfc3339()).expect("Comment::into_activity: published error");
|
||||
note.object_props.set_attributed_to_link(author.clone().into_id()).expect("Comment::into_activity: attributed_to error");
|
||||
note.object_props.set_to_link_vec(to.clone()).expect("Comment::into_activity: to error");
|
||||
note.object_props.set_tag_link_vec(mentions.into_iter().map(|m| Mention::build_activity(conn, m)).collect::<Vec<link::Mention>>())
|
||||
.expect("NewComment::create: note.tag error");
|
||||
.expect("Comment::into_activity: tag error");
|
||||
note
|
||||
}
|
||||
|
||||
pub fn create_activity(&self, conn: &Connection) -> Create {
|
||||
let author = User::get(conn, self.author_id).unwrap();
|
||||
let author = User::get(conn, self.author_id).expect("Comment::create_activity: author error");
|
||||
|
||||
let note = self.into_activity(conn);
|
||||
let mut act = Create::default();
|
||||
act.create_props.set_actor_link(author.into_id()).expect("NewComment::create_acitivity: actor error");
|
||||
act.create_props.set_object_object(note.clone()).expect("NewComment::create_acitivity: object error");
|
||||
act.object_props.set_id_string(format!("{}/activity", self.ap_url.clone().unwrap())).expect("NewComment::create_acitivity: id error");
|
||||
act.object_props.set_to_link_vec(note.object_props.to_link_vec::<Id>().expect("WTF")).expect("NewComment::create_acitivity: to error");
|
||||
act.object_props.set_cc_link_vec::<Id>(vec![]).expect("NewComment::create_acitivity: cc error");
|
||||
act.create_props.set_actor_link(author.into_id()).expect("Comment::create_activity: actor error");
|
||||
act.create_props.set_object_object(note.clone()).expect("Comment::create_activity: object error");
|
||||
act.object_props.set_id_string(format!("{}/activity", self.ap_url.clone().expect("Comment::create_activity: ap_url error"))).expect("Comment::create_activity: id error");
|
||||
act.object_props.set_to_link_vec(note.object_props.to_link_vec::<Id>().expect("Comment::create_activity: id error")).expect("Comment::create_activity: to error");
|
||||
act.object_props.set_cc_link_vec::<Id>(vec![]).expect("Comment::create_activity: cc error");
|
||||
act
|
||||
}
|
||||
}
|
||||
|
||||
impl FromActivity<Note, Connection> for Comment {
|
||||
fn from_activity(conn: &Connection, note: Note, actor: Id) -> Comment {
|
||||
let previous_url = note.object_props.in_reply_to.clone().unwrap().as_str().unwrap().to_string();
|
||||
let previous_url = note.object_props.in_reply_to.clone().expect("Comment::from_activity: not an answer error").as_str().expect("Comment::from_activity: in_reply_to parsing error").to_string();
|
||||
let previous_comment = Comment::find_by_ap_url(conn, previous_url.clone());
|
||||
|
||||
let comm = Comment::insert(conn, NewComment {
|
||||
content: SafeString::new(¬e.object_props.content_string().unwrap()),
|
||||
content: SafeString::new(¬e.object_props.content_string().expect("Comment::from_activity: content deserialization error")),
|
||||
spoiler_text: note.object_props.summary_string().unwrap_or(String::from("")),
|
||||
ap_url: note.object_props.id_string().ok(),
|
||||
in_response_to_id: previous_comment.clone().map(|c| c.id),
|
||||
post_id: previous_comment
|
||||
.map(|c| c.post_id)
|
||||
.unwrap_or_else(|| Post::find_by_ap_url(conn, previous_url).unwrap().id),
|
||||
author_id: User::from_url(conn, actor.clone().into()).unwrap().id,
|
||||
.unwrap_or_else(|| Post::find_by_ap_url(conn, previous_url).expect("Comment::from_activity: post error").id),
|
||||
author_id: User::from_url(conn, actor.clone().into()).expect("Comment::from_activity: author error").id,
|
||||
sensitive: false // "sensitive" is not a standard property, we need to think about how to support it with the activitypub crate
|
||||
});
|
||||
|
||||
|
@ -157,8 +157,8 @@ impl FromActivity<Note, Connection> for Comment {
|
|||
for tag in tags.into_iter() {
|
||||
serde_json::from_value::<link::Mention>(tag)
|
||||
.map(|m| {
|
||||
let author = &Post::get(conn, comm.post_id).unwrap().get_authors(conn)[0];
|
||||
let not_author = m.link_props.href_string().expect("Comment mention: no href") != author.ap_url.clone();
|
||||
let author = &Post::get(conn, comm.post_id).expect("Comment::from_activity: error").get_authors(conn)[0];
|
||||
let not_author = m.link_props.href_string().expect("Comment::from_activity: no href error") != author.ap_url.clone();
|
||||
Mention::from_activity(conn, m, comm.id, false, not_author)
|
||||
}).ok();
|
||||
}
|
||||
|
|
|
@ -38,15 +38,15 @@ impl Follow {
|
|||
}
|
||||
|
||||
pub fn into_activity(&self, conn: &Connection) -> FollowAct {
|
||||
let user = User::get(conn, self.follower_id).unwrap();
|
||||
let target = User::get(conn, self.following_id).unwrap();
|
||||
let user = User::get(conn, self.follower_id).expect("Follow::into_activity: actor not found error");
|
||||
let target = User::get(conn, self.following_id).expect("Follow::into_activity: target not found error");
|
||||
|
||||
let mut act = FollowAct::default();
|
||||
act.follow_props.set_actor_link::<Id>(user.clone().into_id()).expect("Follow::into_activity: actor error");
|
||||
act.follow_props.set_object_object(user.into_activity(&*conn)).unwrap();
|
||||
act.object_props.set_id_string(self.ap_url.clone()).unwrap();
|
||||
act.object_props.set_to_link(target.clone().into_id()).expect("New Follow error while setting 'to'");
|
||||
act.object_props.set_cc_link_vec::<Id>(vec![]).expect("New Follow error while setting 'cc'");
|
||||
act.follow_props.set_object_object(user.into_activity(&*conn)).expect("Follow::into_activity: object error");
|
||||
act.object_props.set_id_string(self.ap_url.clone()).expect("Follow::into_activity: id error");
|
||||
act.object_props.set_to_link(target.clone().into_id()).expect("Follow::into_activity: target error");
|
||||
act.object_props.set_cc_link_vec::<Id>(vec![]).expect("Follow::into_activity: cc error");
|
||||
act
|
||||
}
|
||||
|
||||
|
@ -70,11 +70,11 @@ impl Follow {
|
|||
|
||||
let mut accept = Accept::default();
|
||||
let accept_id = format!("{}#accept", follow.object_props.id_string().unwrap_or(String::new()));
|
||||
accept.object_props.set_id_string(accept_id).expect("accept_follow: id error");
|
||||
accept.object_props.set_to_link(from.clone().into_id()).expect("accept_follow: to error");
|
||||
accept.object_props.set_cc_link_vec::<Id>(vec![]).expect("accept_follow: cc error");
|
||||
accept.accept_props.set_actor_link::<Id>(target.clone().into_id()).unwrap();
|
||||
accept.accept_props.set_object_object(follow).unwrap();
|
||||
accept.object_props.set_id_string(accept_id).expect("Follow::accept_follow: id error");
|
||||
accept.object_props.set_to_link(from.clone().into_id()).expect("Follow::accept_follow: to error");
|
||||
accept.object_props.set_cc_link_vec::<Id>(vec![]).expect("Follow::accept_follow: cc error");
|
||||
accept.accept_props.set_actor_link::<Id>(target.clone().into_id()).expect("Follow::accept_follow: actor error");
|
||||
accept.accept_props.set_object_object(follow).expect("Follow::accept_follow: object error");
|
||||
broadcast(&*target, accept, vec![from.clone()]);
|
||||
res
|
||||
}
|
||||
|
@ -83,12 +83,13 @@ impl Follow {
|
|||
impl FromActivity<FollowAct, Connection> for Follow {
|
||||
fn from_activity(conn: &Connection, follow: FollowAct, _actor: Id) -> Follow {
|
||||
let from_id = follow.follow_props.actor_link::<Id>().map(|l| l.into())
|
||||
.unwrap_or_else(|_| follow.follow_props.actor_object::<Person>().expect("No actor object (nor ID) on Follow").object_props.id_string().expect("No ID on actor on Follow"));
|
||||
let from = User::from_url(conn, from_id).unwrap();
|
||||
match User::from_url(conn, follow.follow_props.object.as_str().unwrap().to_string()) {
|
||||
.unwrap_or_else(|_| follow.follow_props.actor_object::<Person>().expect("Follow::from_activity: actor not found error").object_props.id_string().expect("Follow::from_activity: actor not found error"));
|
||||
let from = User::from_url(conn, from_id).expect("Follow::from_activity: actor not found error");
|
||||
match User::from_url(conn, follow.follow_props.object.as_str().expect("Follow::from_activity: target url parsing error").to_string()) {
|
||||
Some(user) => Follow::accept_follow(conn, &from, &user, follow, from.id, user.id),
|
||||
None => {
|
||||
let blog = Blog::from_url(conn, follow.follow_props.object.as_str().unwrap().to_string()).unwrap();
|
||||
let blog = Blog::from_url(conn, follow.follow_props.object.as_str().expect("Follow::from_activity: target url parsing error").to_string())
|
||||
.expect("Follow::from_activity: target not found error");
|
||||
Follow::accept_follow(conn, &from, &blog, follow, from.id, blog.id)
|
||||
}
|
||||
}
|
||||
|
@ -107,15 +108,15 @@ impl Notify<Connection> for Follow {
|
|||
|
||||
impl Deletable<Connection, Undo> for Follow {
|
||||
fn delete(&self, conn: &Connection) -> Undo {
|
||||
diesel::delete(self).execute(conn).expect("Coudn't delete follow");
|
||||
diesel::delete(self).execute(conn).expect("Follow::delete: follow deletion error");
|
||||
|
||||
// delete associated notification if any
|
||||
if let Some(notif) = Notification::find(conn, notification_kind::FOLLOW, self.id) {
|
||||
diesel::delete(¬if).execute(conn).expect("Couldn't delete follow notification");
|
||||
diesel::delete(¬if).execute(conn).expect("Follow::delete: notification deletion error");
|
||||
}
|
||||
|
||||
let mut undo = Undo::default();
|
||||
undo.undo_props.set_actor_link(User::get(conn, self.follower_id).unwrap().into_id()).expect("Follow::delete: actor error");
|
||||
undo.undo_props.set_actor_link(User::get(conn, self.follower_id).expect("Follow::delete: actor error").into_id()).expect("Follow::delete: actor error");
|
||||
undo.object_props.set_id_string(format!("{}/undo", self.ap_url)).expect("Follow::delete: id error");
|
||||
undo.undo_props.set_object_object(self.into_activity(conn)).expect("Follow::delete: object error");
|
||||
undo
|
||||
|
|
|
@ -44,14 +44,14 @@ impl Instance {
|
|||
instances::table.filter(instances::local.eq(true))
|
||||
.limit(1)
|
||||
.load::<Instance>(conn)
|
||||
.expect("Error loading local instance infos")
|
||||
.expect("Instance::get_local: loading error")
|
||||
.into_iter().nth(0)
|
||||
}
|
||||
|
||||
pub fn get_remotes(conn: &Connection) -> Vec<Instance> {
|
||||
instances::table.filter(instances::local.eq(false))
|
||||
.load::<Instance>(conn)
|
||||
.expect("Error loading remote instances infos")
|
||||
.expect("Instance::get_remotes: loading error")
|
||||
}
|
||||
|
||||
pub fn page(conn: &Connection, (min, max): (i32, i32)) -> Vec<Instance> {
|
||||
|
@ -59,11 +59,11 @@ impl Instance {
|
|||
.offset(min.into())
|
||||
.limit((max - min).into())
|
||||
.load::<Instance>(conn)
|
||||
.expect("Error loading a page of instances")
|
||||
.expect("Instance::page: loading error")
|
||||
}
|
||||
|
||||
pub fn local_id(conn: &Connection) -> i32 {
|
||||
Instance::get_local(conn).unwrap().id
|
||||
Instance::get_local(conn).expect("Instance::local_id: local instance not found error").id
|
||||
}
|
||||
|
||||
insert!(instances, NewInstance);
|
||||
|
@ -74,14 +74,14 @@ impl Instance {
|
|||
diesel::update(self)
|
||||
.set(instances::blocked.eq(!self.blocked))
|
||||
.execute(conn)
|
||||
.expect("Couldn't block/unblock instance");
|
||||
.expect("Instance::toggle_block: update error");
|
||||
}
|
||||
|
||||
/// id: AP object id
|
||||
pub fn is_blocked(conn: &Connection, id: String) -> bool {
|
||||
for block in instances::table.filter(instances::blocked.eq(true))
|
||||
.get_results::<Instance>(conn)
|
||||
.expect("Error listing blocked instances") {
|
||||
.expect("Instance::is_blocked: loading error") {
|
||||
if id.starts_with(format!("https://{}", block.public_domain).as_str()) {
|
||||
return true;
|
||||
}
|
||||
|
@ -94,7 +94,7 @@ impl Instance {
|
|||
users::table.filter(users::instance_id.eq(self.id))
|
||||
.filter(users::is_admin.eq(true))
|
||||
.load::<User>(conn)
|
||||
.expect("Couldn't load admins")
|
||||
.expect("Instance::has_admin: loading error")
|
||||
.len() > 0
|
||||
}
|
||||
|
||||
|
@ -103,7 +103,7 @@ impl Instance {
|
|||
.filter(users::is_admin.eq(true))
|
||||
.limit(1)
|
||||
.get_result::<User>(conn)
|
||||
.expect("Couldn't load admins")
|
||||
.expect("Instance::main_admin: loading error")
|
||||
}
|
||||
|
||||
pub fn compute_box(&self, prefix: &'static str, name: String, box_name: &'static str) -> String {
|
||||
|
@ -128,10 +128,10 @@ impl Instance {
|
|||
instances::short_description_html.eq(sd),
|
||||
instances::long_description_html.eq(ld)
|
||||
)).execute(conn)
|
||||
.expect("Couldn't update instance");
|
||||
.expect("Instance::update: update error");
|
||||
}
|
||||
|
||||
pub fn count(conn: &Connection) -> i64 {
|
||||
instances::table.count().get_result(conn).expect("Couldn't count instances")
|
||||
instances::table.count().get_result(conn).expect("Instance::count: counting error")
|
||||
}
|
||||
}
|
||||
|
|
|
@ -53,7 +53,7 @@ macro_rules! find_by {
|
|||
$(.filter($table::$col.eq($col)))+
|
||||
.limit(1)
|
||||
.load::<Self>(conn)
|
||||
.expect("Error loading $table by $col")
|
||||
.expect("macro::find_by: Error loading $table by $col")
|
||||
.into_iter().nth(0)
|
||||
}
|
||||
};
|
||||
|
@ -78,7 +78,7 @@ macro_rules! list_by {
|
|||
$table::table
|
||||
$(.filter($table::$col.eq($col)))+
|
||||
.load::<Self>(conn)
|
||||
.expect("Error loading $table by $col")
|
||||
.expect("macro::list_by: Error loading $table by $col")
|
||||
}
|
||||
};
|
||||
}
|
||||
|
@ -101,7 +101,7 @@ macro_rules! get {
|
|||
$table::table.filter($table::id.eq(id))
|
||||
.limit(1)
|
||||
.load::<Self>(conn)
|
||||
.expect("Error loading $table by id")
|
||||
.expect("macro::get: Error loading $table by id")
|
||||
.into_iter().nth(0)
|
||||
}
|
||||
};
|
||||
|
@ -127,7 +127,7 @@ macro_rules! insert {
|
|||
diesel::insert_into($table::table)
|
||||
.values(new)
|
||||
.execute(conn)
|
||||
.expect("Error saving new $table");
|
||||
.expect("macro::insert: Error saving new $table");
|
||||
Self::last(conn)
|
||||
}
|
||||
};
|
||||
|
@ -154,9 +154,9 @@ macro_rules! update {
|
|||
diesel::update(self)
|
||||
.set(self)
|
||||
.execute(conn)
|
||||
.expect(concat!("Error updating ", stringify!($table)));
|
||||
.expect(concat!("macro::update: Error updating ", stringify!($table)));
|
||||
Self::get(conn, self.id)
|
||||
.expect(concat!(stringify!($table), " we just updated doesn't exist anymore???"))
|
||||
.expect(concat!("macro::update: ", stringify!($table), " we just updated doesn't exist anymore???"))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
@ -179,9 +179,9 @@ macro_rules! last {
|
|||
$table::table.order_by($table::id.desc())
|
||||
.limit(1)
|
||||
.load::<Self>(conn)
|
||||
.expect(concat!("Error getting last ", stringify!($table)))
|
||||
.expect(concat!("macro::last: Error getting last ", stringify!($table)))
|
||||
.iter().next()
|
||||
.expect(concat!("No last ", stringify!($table)))
|
||||
.expect(concat!("macro::last: No last ", stringify!($table)))
|
||||
.clone()
|
||||
}
|
||||
};
|
||||
|
|
|
@ -42,17 +42,17 @@ impl Like {
|
|||
diesel::update(self)
|
||||
.set(likes::ap_url.eq(format!(
|
||||
"{}/like/{}",
|
||||
User::get(conn, self.user_id).unwrap().ap_url,
|
||||
Post::get(conn, self.post_id).unwrap().ap_url
|
||||
User::get(conn, self.user_id).expect("Like::update_ap_url: user error").ap_url,
|
||||
Post::get(conn, self.post_id).expect("Like::update_ap_url: post error").ap_url
|
||||
)))
|
||||
.execute(conn).expect("Couldn't update AP URL");
|
||||
.execute(conn).expect("Like::update_ap_url: update error");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_activity(&self, conn: &Connection) -> activity::Like {
|
||||
let mut act = activity::Like::default();
|
||||
act.like_props.set_actor_link(User::get(conn, self.user_id).unwrap().into_id()).expect("Like::into_activity: actor error");
|
||||
act.like_props.set_object_link(Post::get(conn, self.post_id).unwrap().into_id()).expect("Like::into_activity: object error");
|
||||
act.like_props.set_actor_link(User::get(conn, self.user_id).expect("Like::into_activity: user error").into_id()).expect("Like::into_activity: actor error");
|
||||
act.like_props.set_object_link(Post::get(conn, self.post_id).expect("Like::into_activity: post error").into_id()).expect("Like::into_activity: object error");
|
||||
act.object_props.set_to_link(Id::new(PUBLIC_VISIBILTY.to_string())).expect("Like::into_activity: to error");
|
||||
act.object_props.set_cc_link_vec::<Id>(vec![]).expect("Like::into_activity: cc error");
|
||||
act.object_props.set_id_string(self.ap_url.clone()).expect("Like::into_activity: id error");
|
||||
|
@ -63,11 +63,11 @@ impl Like {
|
|||
|
||||
impl FromActivity<activity::Like, Connection> for Like {
|
||||
fn from_activity(conn: &Connection, like: activity::Like, _actor: Id) -> Like {
|
||||
let liker = User::from_url(conn, like.like_props.actor.as_str().unwrap().to_string());
|
||||
let post = Post::find_by_ap_url(conn, like.like_props.object.as_str().unwrap().to_string());
|
||||
let liker = User::from_url(conn, like.like_props.actor.as_str().expect("Like::from_activity: actor error").to_string());
|
||||
let post = Post::find_by_ap_url(conn, like.like_props.object.as_str().expect("Like::from_activity: object error").to_string());
|
||||
let res = Like::insert(conn, NewLike {
|
||||
post_id: post.unwrap().id,
|
||||
user_id: liker.unwrap().id,
|
||||
post_id: post.expect("Like::from_activity: post error").id,
|
||||
user_id: liker.expect("Like::from_activity: user error").id,
|
||||
ap_url: like.object_props.id_string().unwrap_or(String::from(""))
|
||||
});
|
||||
res.notify(conn);
|
||||
|
@ -77,7 +77,7 @@ impl FromActivity<activity::Like, Connection> for Like {
|
|||
|
||||
impl Notify<Connection> for Like {
|
||||
fn notify(&self, conn: &Connection) {
|
||||
let post = Post::get(conn, self.post_id).unwrap();
|
||||
let post = Post::get(conn, self.post_id).expect("Like::notify: post error");
|
||||
for author in post.get_authors(conn) {
|
||||
Notification::insert(conn, NewNotification {
|
||||
kind: notification_kind::LIKE.to_string(),
|
||||
|
@ -90,15 +90,15 @@ impl Notify<Connection> for Like {
|
|||
|
||||
impl Deletable<Connection, activity::Undo> for Like {
|
||||
fn delete(&self, conn: &Connection) -> activity::Undo {
|
||||
diesel::delete(self).execute(conn).unwrap();
|
||||
diesel::delete(self).execute(conn).expect("Like::delete: delete error");
|
||||
|
||||
// delete associated notification if any
|
||||
if let Some(notif) = Notification::find(conn, notification_kind::LIKE, self.id) {
|
||||
diesel::delete(¬if).execute(conn).expect("Couldn't delete like notification");
|
||||
diesel::delete(¬if).execute(conn).expect("Like::delete: notification error");
|
||||
}
|
||||
|
||||
let mut act = activity::Undo::default();
|
||||
act.undo_props.set_actor_link(User::get(conn, self.user_id).unwrap().into_id()).expect("Like::delete: actor error");
|
||||
act.undo_props.set_actor_link(User::get(conn, self.user_id).expect("Like::delete: user error").into_id()).expect("Like::delete: actor error");
|
||||
act.undo_props.set_object_object(self.into_activity(conn)).expect("Like::delete: object error");
|
||||
act.object_props.set_id_string(format!("{}#delete", self.ap_url)).expect("Like::delete: id error");
|
||||
act.object_props.set_to_link(Id::new(PUBLIC_VISIBILTY.to_string())).expect("Like::delete: to error");
|
||||
|
|
|
@ -36,9 +36,9 @@ impl Media {
|
|||
list_by!(medias, for_user, owner_id as i32);
|
||||
|
||||
pub fn to_json(&self, conn: &Connection) -> serde_json::Value {
|
||||
let mut json = serde_json::to_value(self).unwrap();
|
||||
let mut json = serde_json::to_value(self).expect("Media::to_json: serialization error");
|
||||
let url = self.url(conn);
|
||||
let (preview, html, md) = match self.file_path.rsplitn(2, '.').next().unwrap() {
|
||||
let (preview, html, md) = match self.file_path.rsplitn(2, '.').next().expect("Media::to_json: extension error") {
|
||||
"png" | "jpg" | "jpeg" | "gif" | "svg" => (
|
||||
format!("<img src=\"{}\" alt=\"{}\" title=\"{}\" class=\"preview\">", url, self.alt_text, self.alt_text),
|
||||
format!("<img src=\"{}\" alt=\"{}\" title=\"{}\">", url, self.alt_text, self.alt_text),
|
||||
|
@ -67,13 +67,13 @@ impl Media {
|
|||
if self.is_remote {
|
||||
self.remote_url.clone().unwrap_or(String::new())
|
||||
} else {
|
||||
ap_url(format!("{}/static/{}", Instance::get_local(conn).unwrap().public_domain, self.file_path))
|
||||
ap_url(format!("{}/static/{}", Instance::get_local(conn).expect("Media::url: local instance not found error").public_domain, self.file_path))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn delete(&self, conn: &Connection) {
|
||||
fs::remove_file(self.file_path.as_str()).expect("Couldn't delete media from disk");
|
||||
diesel::delete(self).execute(conn).expect("Couldn't remove media from DB");
|
||||
fs::remove_file(self.file_path.as_str()).expect("Media::delete: file deletion error");
|
||||
diesel::delete(self).execute(conn).expect("Media::delete: database entry deletion error");
|
||||
}
|
||||
|
||||
pub fn save_remote(conn: &Connection, url: String) -> Media {
|
||||
|
@ -92,6 +92,6 @@ impl Media {
|
|||
diesel::update(self)
|
||||
.set(medias::owner_id.eq(id))
|
||||
.execute(conn)
|
||||
.expect("Couldn't update Media.owner_id");
|
||||
.expect("Media::set_owner: owner update error");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -57,16 +57,16 @@ impl Mention {
|
|||
pub fn build_activity(conn: &Connection, ment: String) -> link::Mention {
|
||||
let user = User::find_by_fqn(conn, ment.clone());
|
||||
let mut mention = link::Mention::default();
|
||||
mention.link_props.set_href_string(user.clone().map(|u| u.ap_url).unwrap_or(String::new())).expect("Error setting mention's href");
|
||||
mention.link_props.set_name_string(format!("@{}", ment)).expect("Error setting mention's name");
|
||||
mention.link_props.set_href_string(user.clone().map(|u| u.ap_url).unwrap_or(String::new())).expect("Mention::build_activity: href error");
|
||||
mention.link_props.set_name_string(format!("@{}", ment)).expect("Mention::build_activity: name error:");
|
||||
mention
|
||||
}
|
||||
|
||||
pub fn to_activity(&self, conn: &Connection) -> link::Mention {
|
||||
let user = self.get_mentioned(conn);
|
||||
let mut mention = link::Mention::default();
|
||||
mention.link_props.set_href_string(user.clone().map(|u| u.ap_url).unwrap_or(String::new())).expect("Error setting mention's href");
|
||||
mention.link_props.set_name_string(user.map(|u| format!("@{}", u.get_fqn(conn))).unwrap_or(String::new())).expect("Error setting mention's name");
|
||||
mention.link_props.set_href_string(user.clone().map(|u| u.ap_url).unwrap_or(String::new())).expect("Mention::to_activity: href error");
|
||||
mention.link_props.set_name_string(user.map(|u| format!("@{}", u.get_fqn(conn))).unwrap_or(String::new())).expect("Mention::to_activity: mention error");
|
||||
mention
|
||||
}
|
||||
|
||||
|
|
|
@ -45,7 +45,7 @@ impl Notification {
|
|||
notifications::table.filter(notifications::user_id.eq(user.id))
|
||||
.order_by(notifications::creation_date.desc())
|
||||
.load::<Notification>(conn)
|
||||
.expect("Couldn't load user notifications")
|
||||
.expect("Notification::find_for_user: notification loading error")
|
||||
}
|
||||
|
||||
pub fn page_for_user(conn: &Connection, user: &User, (min, max): (i32, i32)) -> Vec<Notification> {
|
||||
|
@ -54,7 +54,7 @@ impl Notification {
|
|||
.offset(min.into())
|
||||
.limit((max - min).into())
|
||||
.load::<Notification>(conn)
|
||||
.expect("Couldn't load user notifications page")
|
||||
.expect("Notification::page_for_user: notification loading error")
|
||||
}
|
||||
|
||||
pub fn find<S: Into<String>>(conn: &Connection, kind: S, obj: i32) -> Option<Notification> {
|
||||
|
@ -90,9 +90,9 @@ impl Notification {
|
|||
"user": mention.get_user(conn).map(|u| u.to_json(conn)),
|
||||
"url": mention.get_post(conn).map(|p| p.to_json(conn)["url"].clone())
|
||||
.unwrap_or_else(|| {
|
||||
let comment = mention.get_comment(conn).expect("No comment nor post for mention");
|
||||
let comment = mention.get_comment(conn).expect("Notification::to_json: comment not found error");
|
||||
let post = comment.get_post(conn).to_json(conn);
|
||||
json!(format!("{}#comment-{}", post["url"].as_str().unwrap(), comment.id))
|
||||
json!(format!("{}#comment-{}", post["url"].as_str().expect("Notification::to_json: post url error"), comment.id))
|
||||
})
|
||||
})
|
||||
),
|
||||
|
|
|
@ -122,7 +122,7 @@ impl Post {
|
|||
.offset(min.into())
|
||||
.limit((max - min).into())
|
||||
.load(conn)
|
||||
.expect("Error loading posts by tag")
|
||||
.expect("Post::list_by_tag: loading error")
|
||||
}
|
||||
|
||||
pub fn count_for_tag(conn: &Connection, tag: String) -> i64 {
|
||||
|
@ -132,8 +132,8 @@ impl Post {
|
|||
.filter(posts::published.eq(true))
|
||||
.count()
|
||||
.load(conn)
|
||||
.expect("Error counting posts by tag")
|
||||
.iter().next().unwrap()
|
||||
.expect("Post::count_for_tag: counting error")
|
||||
.iter().next().expect("Post::count_for_tag: no result error")
|
||||
}
|
||||
|
||||
pub fn count_local(conn: &Connection) -> usize {
|
||||
|
@ -144,12 +144,15 @@ impl Post {
|
|||
posts::table.filter(posts::id.eq_any(local_posts_id))
|
||||
.filter(posts::published.eq(true))
|
||||
.load::<Post>(conn)
|
||||
.expect("Couldn't load local posts")
|
||||
.len()
|
||||
.expect("Post::count_local: loading error")
|
||||
.len()// TODO count in database?
|
||||
}
|
||||
|
||||
pub fn count(conn: &Connection) -> i64 {
|
||||
posts::table.filter(posts::published.eq(true)).count().get_result(conn).expect("Couldn't count posts")
|
||||
posts::table.filter(posts::published.eq(true))
|
||||
.count()
|
||||
.get_result(conn)
|
||||
.expect("Post::count: counting error")
|
||||
}
|
||||
|
||||
pub fn get_recents(conn: &Connection, limit: i64) -> Vec<Post> {
|
||||
|
@ -157,7 +160,7 @@ impl Post {
|
|||
.filter(posts::published.eq(true))
|
||||
.limit(limit)
|
||||
.load::<Post>(conn)
|
||||
.expect("Error loading recent posts")
|
||||
.expect("Post::get_recents: loading error")
|
||||
}
|
||||
|
||||
pub fn get_recents_for_author(conn: &Connection, author: &User, limit: i64) -> Vec<Post> {
|
||||
|
@ -169,7 +172,7 @@ impl Post {
|
|||
.order(posts::creation_date.desc())
|
||||
.limit(limit)
|
||||
.load::<Post>(conn)
|
||||
.expect("Error loading recent posts for author")
|
||||
.expect("Post::get_recents_for_author: loading error")
|
||||
}
|
||||
|
||||
pub fn get_recents_for_blog(conn: &Connection, blog: &Blog, limit: i64) -> Vec<Post> {
|
||||
|
@ -178,14 +181,14 @@ impl Post {
|
|||
.order(posts::creation_date.desc())
|
||||
.limit(limit)
|
||||
.load::<Post>(conn)
|
||||
.expect("Error loading recent posts for blog")
|
||||
.expect("Post::get_recents_for_blog: loading error")
|
||||
}
|
||||
|
||||
pub fn get_for_blog(conn: &Connection, blog:&Blog) -> Vec<Post> {
|
||||
posts::table.filter(posts::blog_id.eq(blog.id))
|
||||
.filter(posts::published.eq(true))
|
||||
.load::<Post>(conn)
|
||||
.expect("Error loading posts for blog")
|
||||
.expect("Post::get_for_blog:: loading error")
|
||||
}
|
||||
|
||||
pub fn blog_page(conn: &Connection, blog: &Blog, (min, max): (i32, i32)) -> Vec<Post> {
|
||||
|
@ -195,7 +198,7 @@ impl Post {
|
|||
.offset(min.into())
|
||||
.limit((max - min).into())
|
||||
.load::<Post>(conn)
|
||||
.expect("Error loading a page of posts for blog")
|
||||
.expect("Post::blog_page: loading error")
|
||||
}
|
||||
|
||||
/// Give a page of all the recent posts known to this instance (= federated timeline)
|
||||
|
@ -205,7 +208,7 @@ impl Post {
|
|||
.offset(min.into())
|
||||
.limit((max - min).into())
|
||||
.load::<Post>(conn)
|
||||
.expect("Error loading recent posts page")
|
||||
.expect("Post::get_recents_page: loading error")
|
||||
}
|
||||
|
||||
/// Give a page of posts from a specific instance
|
||||
|
@ -220,7 +223,7 @@ impl Post {
|
|||
.offset(min.into())
|
||||
.limit((max - min).into())
|
||||
.load::<Post>(conn)
|
||||
.expect("Error loading local posts page")
|
||||
.expect("Post::get_instance_page: loading error")
|
||||
}
|
||||
|
||||
/// Give a page of customized user feed, based on a list of followed users
|
||||
|
@ -236,7 +239,7 @@ impl Post {
|
|||
.offset(min.into())
|
||||
.limit((max - min).into())
|
||||
.load::<Post>(conn)
|
||||
.expect("Error loading user feed page")
|
||||
.expect("Post::user_feed_page: loading error")
|
||||
}
|
||||
|
||||
pub fn drafts_by_author(conn: &Connection, author: &User) -> Vec<Post> {
|
||||
|
@ -247,14 +250,14 @@ impl Post {
|
|||
.filter(posts::published.eq(false))
|
||||
.filter(posts::id.eq_any(posts))
|
||||
.load::<Post>(conn)
|
||||
.expect("Error listing drafts")
|
||||
.expect("Post::drafts_by_author: loading error")
|
||||
}
|
||||
|
||||
pub fn get_authors(&self, conn: &Connection) -> Vec<User> {
|
||||
use schema::users;
|
||||
use schema::post_authors;
|
||||
let author_list = PostAuthor::belonging_to(self).select(post_authors::author_id);
|
||||
users::table.filter(users::id.eq_any(author_list)).load::<User>(conn).unwrap()
|
||||
users::table.filter(users::id.eq_any(author_list)).load::<User>(conn).expect("Post::get_authors: loading error")
|
||||
}
|
||||
|
||||
pub fn get_blog(&self, conn: &Connection) -> Blog {
|
||||
|
@ -262,30 +265,30 @@ impl Post {
|
|||
blogs::table.filter(blogs::id.eq(self.blog_id))
|
||||
.limit(1)
|
||||
.load::<Blog>(conn)
|
||||
.expect("Couldn't load blog associted to post")
|
||||
.into_iter().nth(0).unwrap()
|
||||
.expect("Post::get_blog: loading error")
|
||||
.into_iter().nth(0).expect("Post::get_blog: no result error")
|
||||
}
|
||||
|
||||
pub fn get_likes(&self, conn: &Connection) -> Vec<Like> {
|
||||
use schema::likes;
|
||||
likes::table.filter(likes::post_id.eq(self.id))
|
||||
.load::<Like>(conn)
|
||||
.expect("Couldn't load likes associted to post")
|
||||
.expect("Post::get_likes: loading error")
|
||||
}
|
||||
|
||||
pub fn get_reshares(&self, conn: &Connection) -> Vec<Reshare> {
|
||||
use schema::reshares;
|
||||
reshares::table.filter(reshares::post_id.eq(self.id))
|
||||
.load::<Reshare>(conn)
|
||||
.expect("Couldn't load reshares associted to post")
|
||||
.expect("Post::get_reshares: loading error")
|
||||
}
|
||||
|
||||
pub fn update_ap_url(&self, conn: &Connection) -> Post {
|
||||
if self.ap_url.len() == 0 {
|
||||
diesel::update(self)
|
||||
.set(posts::ap_url.eq(self.compute_id(conn)))
|
||||
.execute(conn).expect("Couldn't update AP URL");
|
||||
Post::get(conn, self.id).unwrap()
|
||||
.execute(conn).expect("Post::update_ap_url: update error");
|
||||
Post::get(conn, self.id).expect("Post::update_ap_url: get error")
|
||||
} else {
|
||||
self.clone()
|
||||
}
|
||||
|
@ -359,7 +362,7 @@ impl Post {
|
|||
|
||||
pub fn handle_update(conn: &Connection, updated: Article) {
|
||||
let id = updated.object_props.id_string().expect("Post::handle_update: id error");
|
||||
let mut post = Post::find_by_ap_url(conn, id).unwrap();
|
||||
let mut post = Post::find_by_ap_url(conn, id).expect("Post::handle_update: finding error");
|
||||
|
||||
if let Ok(title) = updated.object_props.name_string() {
|
||||
post.slug = title.to_kebab_case();
|
||||
|
@ -423,7 +426,7 @@ impl FromActivity<Article, Connection> for Post {
|
|||
|
||||
let title = article.object_props.name_string().expect("Post::from_activity: title error");
|
||||
let post = Post::insert(conn, NewPost {
|
||||
blog_id: blog.expect("Received a new Article without a blog").id,
|
||||
blog_id: blog.expect("Post::from_activity: blog not found error").id,
|
||||
slug: title.to_kebab_case(),
|
||||
title: title,
|
||||
content: SafeString::new(&article.object_props.content_string().expect("Post::from_activity: content error")),
|
||||
|
|
|
@ -37,10 +37,10 @@ impl Reshare {
|
|||
diesel::update(self)
|
||||
.set(reshares::ap_url.eq(format!(
|
||||
"{}/reshare/{}",
|
||||
User::get(conn, self.user_id).unwrap().ap_url,
|
||||
Post::get(conn, self.post_id).unwrap().ap_url
|
||||
User::get(conn, self.user_id).expect("Reshare::update_ap_url: user error").ap_url,
|
||||
Post::get(conn, self.post_id).expect("Reshare::update_ap_url: post error").ap_url
|
||||
)))
|
||||
.execute(conn).expect("Couldn't update AP URL");
|
||||
.execute(conn).expect("Reshare::update_ap_url: update error");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -49,7 +49,7 @@ impl Reshare {
|
|||
.order(reshares::creation_date.desc())
|
||||
.limit(limit)
|
||||
.load::<Reshare>(conn)
|
||||
.expect("Error loading recent reshares for user")
|
||||
.expect("Reshare::get_recents_for_author: loading error")
|
||||
}
|
||||
|
||||
pub fn get_post(&self, conn: &Connection) -> Option<Post> {
|
||||
|
@ -62,9 +62,11 @@ impl Reshare {
|
|||
|
||||
pub fn into_activity(&self, conn: &Connection) -> Announce {
|
||||
let mut act = Announce::default();
|
||||
act.announce_props.set_actor_link(User::get(conn, self.user_id).unwrap().into_id()).unwrap();
|
||||
act.announce_props.set_object_link(Post::get(conn, self.post_id).unwrap().into_id()).unwrap();
|
||||
act.object_props.set_id_string(self.ap_url.clone()).unwrap();
|
||||
act.announce_props.set_actor_link(User::get(conn, self.user_id).expect("Reshare::into_activity: user error").into_id())
|
||||
.expect("Reshare::into_activity: actor error");
|
||||
act.announce_props.set_object_link(Post::get(conn, self.post_id).expect("Reshare::into_activity: post error").into_id())
|
||||
.expect("Reshare::into_activity: object error");
|
||||
act.object_props.set_id_string(self.ap_url.clone()).expect("Reshare::into_activity: id error");
|
||||
act.object_props.set_to_link(Id::new(PUBLIC_VISIBILTY.to_string())).expect("Reshare::into_activity: to error");
|
||||
act.object_props.set_cc_link_vec::<Id>(vec![]).expect("Reshare::into_activity: cc error");
|
||||
|
||||
|
@ -77,8 +79,8 @@ impl FromActivity<Announce, Connection> for Reshare {
|
|||
let user = User::from_url(conn, announce.announce_props.actor_link::<Id>().expect("Reshare::from_activity: actor error").into());
|
||||
let post = Post::find_by_ap_url(conn, announce.announce_props.object_link::<Id>().expect("Reshare::from_activity: object error").into());
|
||||
let reshare = Reshare::insert(conn, NewReshare {
|
||||
post_id: post.unwrap().id,
|
||||
user_id: user.unwrap().id,
|
||||
post_id: post.expect("Reshare::from_activity: post error").id,
|
||||
user_id: user.expect("Reshare::from_activity: user error").id,
|
||||
ap_url: announce.object_props.id_string().unwrap_or(String::from(""))
|
||||
});
|
||||
reshare.notify(conn);
|
||||
|
@ -88,7 +90,7 @@ impl FromActivity<Announce, Connection> for Reshare {
|
|||
|
||||
impl Notify<Connection> for Reshare {
|
||||
fn notify(&self, conn: &Connection) {
|
||||
let post = self.get_post(conn).unwrap();
|
||||
let post = self.get_post(conn).expect("Reshare::notify: post error");
|
||||
for author in post.get_authors(conn) {
|
||||
Notification::insert(conn, NewNotification {
|
||||
kind: notification_kind::RESHARE.to_string(),
|
||||
|
@ -101,16 +103,16 @@ impl Notify<Connection> for Reshare {
|
|||
|
||||
impl Deletable<Connection, Undo> for Reshare {
|
||||
fn delete(&self, conn: &Connection) -> Undo {
|
||||
diesel::delete(self).execute(conn).unwrap();
|
||||
diesel::delete(self).execute(conn).expect("Reshare::delete: delete error");
|
||||
|
||||
// delete associated notification if any
|
||||
if let Some(notif) = Notification::find(conn, notification_kind::RESHARE, self.id) {
|
||||
diesel::delete(¬if).execute(conn).expect("Couldn't delete reshare notification");
|
||||
diesel::delete(¬if).execute(conn).expect("Reshare::delete: notification error");
|
||||
}
|
||||
|
||||
let mut act = Undo::default();
|
||||
act.undo_props.set_actor_link(User::get(conn, self.user_id).unwrap().into_id()).unwrap();
|
||||
act.undo_props.set_object_object(self.into_activity(conn)).unwrap();
|
||||
act.undo_props.set_actor_link(User::get(conn, self.user_id).expect("Reshare::delete: user error").into_id()).expect("Reshare::delete: actor error");
|
||||
act.undo_props.set_object_object(self.into_activity(conn)).expect("Reshare::delete: object error");
|
||||
act.object_props.set_id_string(format!("{}#delete", self.ap_url)).expect("Reshare::delete: id error");
|
||||
act.object_props.set_to_link(Id::new(PUBLIC_VISIBILTY.to_string())).expect("Reshare::delete: to error");
|
||||
act.object_props.set_cc_link_vec::<Id>(vec![]).expect("Reshare::delete: cc error");
|
||||
|
|
|
@ -29,7 +29,10 @@ impl Tag {
|
|||
|
||||
pub fn into_activity(&self, conn: &Connection) -> Hashtag {
|
||||
let mut ht = Hashtag::default();
|
||||
ht.set_href_string(ap_url(format!("{}/tag/{}", Instance::get_local(conn).unwrap().public_domain, self.tag))).expect("Tag::into_activity: href error");
|
||||
ht.set_href_string(ap_url(format!("{}/tag/{}",
|
||||
Instance::get_local(conn).expect("Tag::into_activity: local instance not found error").public_domain,
|
||||
self.tag)
|
||||
)).expect("Tag::into_activity: href error");
|
||||
ht.set_name_string(self.tag.clone()).expect("Tag::into_activity: name error");
|
||||
ht
|
||||
}
|
||||
|
|
|
@ -102,7 +102,7 @@ impl User {
|
|||
pub fn one_by_instance(conn: &Connection) -> Vec<User> {
|
||||
users::table.filter(users::instance_id.eq_any(users::table.select(users::instance_id).distinct()))
|
||||
.load::<User>(conn)
|
||||
.expect("Error in User::on_by_instance")
|
||||
.expect("User::one_by_instance: loading error")
|
||||
}
|
||||
|
||||
pub fn delete(&self, conn: &Connection) {
|
||||
|
@ -113,31 +113,31 @@ impl User {
|
|||
.filter(post_authors::author_id.eq(self.id))
|
||||
.select(post_authors::post_id)
|
||||
.load(conn)
|
||||
.expect("Couldn't load posts IDs");
|
||||
.expect("User::delete: post loading error");
|
||||
for post_id in all_their_posts_ids {
|
||||
let has_other_authors = post_authors::table
|
||||
.filter(post_authors::post_id.eq(post_id))
|
||||
.filter(post_authors::author_id.ne(self.id))
|
||||
.count()
|
||||
.load(conn)
|
||||
.expect("Couldn't count other authors").iter().next().unwrap_or(&0) > &0;
|
||||
.expect("User::delete: count author error").iter().next().unwrap_or(&0) > &0;
|
||||
if !has_other_authors {
|
||||
Post::get(conn, post_id).expect("Post is already gone").delete(conn);
|
||||
Post::get(conn, post_id).expect("User::delete: post not found error").delete(conn);
|
||||
}
|
||||
}
|
||||
|
||||
diesel::delete(self).execute(conn).expect("Couldn't remove user from DB");
|
||||
diesel::delete(self).execute(conn).expect("User::delete: user deletion error");
|
||||
}
|
||||
|
||||
pub fn get_instance(&self, conn: &Connection) -> Instance {
|
||||
Instance::get(conn, self.instance_id).expect("Couldn't find instance")
|
||||
Instance::get(conn, self.instance_id).expect("User::get_instance: instance not found error")
|
||||
}
|
||||
|
||||
pub fn grant_admin_rights(&self, conn: &Connection) {
|
||||
diesel::update(self)
|
||||
.set(users::is_admin.eq(true))
|
||||
.execute(conn)
|
||||
.expect("Couldn't grant admin rights");
|
||||
.expect("User::grand_admin_rights: update error");
|
||||
}
|
||||
|
||||
pub fn update(&self, conn: &Connection, name: String, email: String, summary: String) -> User {
|
||||
|
@ -147,15 +147,15 @@ impl User {
|
|||
users::email.eq(email),
|
||||
users::summary.eq(summary),
|
||||
)).execute(conn)
|
||||
.expect("Couldn't update user");
|
||||
User::get(conn, self.id).unwrap()
|
||||
.expect("User::update: update error");
|
||||
User::get(conn, self.id).expect("User::update: get error")
|
||||
}
|
||||
|
||||
pub fn count_local(conn: &Connection) -> usize {
|
||||
users::table.filter(users::instance_id.eq(Instance::local_id(conn)))
|
||||
.load::<User>(conn)
|
||||
.expect("Couldn't load local users")
|
||||
.len()
|
||||
.expect("User::count_local: loading error")
|
||||
.len()// TODO count in database?
|
||||
}
|
||||
|
||||
pub fn find_local(conn: &Connection, username: String) -> Option<User> {
|
||||
|
@ -164,9 +164,9 @@ impl User {
|
|||
|
||||
pub fn find_by_fqn(conn: &Connection, fqn: String) -> Option<User> {
|
||||
if fqn.contains("@") { // remote user
|
||||
match Instance::find_by_domain(conn, String::from(fqn.split("@").last().unwrap())) {
|
||||
match Instance::find_by_domain(conn, String::from(fqn.split("@").last().expect("User::find_by_fqn: host error"))) {
|
||||
Some(instance) => {
|
||||
match User::find_by_name(conn, String::from(fqn.split("@").nth(0).unwrap()), instance.id) {
|
||||
match User::find_by_name(conn, String::from(fqn.split("@").nth(0).expect("User::find_by_fqn: name error")), instance.id) {
|
||||
Some(u) => Some(u),
|
||||
None => User::fetch_from_webfinger(conn, fqn)
|
||||
}
|
||||
|
@ -180,7 +180,7 @@ impl User {
|
|||
|
||||
fn fetch_from_webfinger(conn: &Connection, acct: String) -> Option<User> {
|
||||
match resolve(acct.clone(), *USE_HTTPS) {
|
||||
Ok(wf) => wf.links.into_iter().find(|l| l.mime_type == Some(String::from("application/activity+json"))).and_then(|l| User::fetch_from_url(conn, l.href.expect("No href for AP WF link"))),
|
||||
Ok(wf) => wf.links.into_iter().find(|l| l.mime_type == Some(String::from("application/activity+json"))).and_then(|l| User::fetch_from_url(conn, l.href.expect("User::fetch_from_webginfer: href not found error"))),
|
||||
Err(details) => {
|
||||
println!("WF Error: {:?}", details);
|
||||
None
|
||||
|
@ -191,7 +191,7 @@ impl User {
|
|||
fn fetch(url: String) -> Option<CustomPerson> {
|
||||
let req = Client::new()
|
||||
.get(&url[..])
|
||||
.header(ACCEPT, HeaderValue::from_str(&ap_accept_header().into_iter().collect::<Vec<_>>().join(", ")).unwrap())
|
||||
.header(ACCEPT, HeaderValue::from_str(&ap_accept_header().into_iter().collect::<Vec<_>>().join(", ")).expect("User::fetch: accept header error"))
|
||||
.send();
|
||||
match req {
|
||||
Ok(mut res) => {
|
||||
|
@ -212,7 +212,9 @@ impl User {
|
|||
}
|
||||
|
||||
pub fn fetch_from_url(conn: &Connection, url: String) -> Option<User> {
|
||||
User::fetch(url.clone()).map(|json| (User::from_activity(conn, json, Url::parse(url.as_ref()).unwrap().host_str().unwrap().to_string())))
|
||||
User::fetch(url.clone()).map(|json| (User::from_activity(conn, json, Url::parse(url.as_ref())
|
||||
.expect("User::fetch_from_url: url error").host_str()
|
||||
.expect("User::fetch_from_url: host error").to_string())))
|
||||
}
|
||||
|
||||
fn from_activity(conn: &Connection, acct: CustomPerson, inst: String) -> User {
|
||||
|
@ -277,16 +279,16 @@ impl User {
|
|||
users::avatar_id.eq(Some(avatar.id)),
|
||||
users::last_fetched_date.eq(Utc::now().naive_utc())
|
||||
)).execute(conn)
|
||||
.expect("Couldn't update user")
|
||||
.expect("User::refetch: update error")
|
||||
});
|
||||
}
|
||||
|
||||
pub fn hash_pass(pass: String) -> String {
|
||||
bcrypt::hash(pass.as_str(), 10).unwrap()
|
||||
bcrypt::hash(pass.as_str(), 10).expect("User::hash_pass: hashing error")
|
||||
}
|
||||
|
||||
pub fn auth(&self, pass: String) -> bool {
|
||||
if let Ok(valid) = bcrypt::verify(pass.as_str(), self.hashed_password.clone().unwrap().as_str()) {
|
||||
if let Ok(valid) = bcrypt::verify(pass.as_str(), self.hashed_password.clone().expect("User::auth: no password error").as_str()) {
|
||||
valid
|
||||
} else {
|
||||
false
|
||||
|
@ -298,31 +300,31 @@ impl User {
|
|||
if self.outbox_url.len() == 0 {
|
||||
diesel::update(self)
|
||||
.set(users::outbox_url.eq(instance.compute_box(USER_PREFIX, self.username.clone(), "outbox")))
|
||||
.execute(conn).expect("Couldn't update outbox URL");
|
||||
.execute(conn).expect("User::update_boxes: outbox update error");
|
||||
}
|
||||
|
||||
if self.inbox_url.len() == 0 {
|
||||
diesel::update(self)
|
||||
.set(users::inbox_url.eq(instance.compute_box(USER_PREFIX, self.username.clone(), "inbox")))
|
||||
.execute(conn).expect("Couldn't update inbox URL");
|
||||
.execute(conn).expect("User::update_boxes: inbox update error");
|
||||
}
|
||||
|
||||
if self.ap_url.len() == 0 {
|
||||
diesel::update(self)
|
||||
.set(users::ap_url.eq(instance.compute_box(USER_PREFIX, self.username.clone(), "")))
|
||||
.execute(conn).expect("Couldn't update AP URL");
|
||||
.execute(conn).expect("User::update_boxes: ap_url update error");
|
||||
}
|
||||
|
||||
if self.shared_inbox_url.is_none() {
|
||||
diesel::update(self)
|
||||
.set(users::shared_inbox_url.eq(ap_url(format!("{}/inbox", Instance::get_local(conn).unwrap().public_domain))))
|
||||
.execute(conn).expect("Couldn't update shared inbox URL");
|
||||
.set(users::shared_inbox_url.eq(ap_url(format!("{}/inbox", Instance::get_local(conn).expect("User::update_boxes: local instance not found error").public_domain))))
|
||||
.execute(conn).expect("User::update_boxes: shared inbox update error");
|
||||
}
|
||||
|
||||
if self.followers_endpoint.len() == 0 {
|
||||
diesel::update(self)
|
||||
.set(users::followers_endpoint.eq(instance.compute_box(USER_PREFIX, self.username.clone(), "followers")))
|
||||
.execute(conn).expect("Couldn't update followers endpoint");
|
||||
.execute(conn).expect("User::update_boxes: follower update error");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -332,27 +334,27 @@ impl User {
|
|||
.offset(min.into())
|
||||
.limit((max - min).into())
|
||||
.load::<User>(conn)
|
||||
.expect("Error getting local users page")
|
||||
.expect("User::get_local_page: loading error")
|
||||
}
|
||||
|
||||
pub fn outbox(&self, conn: &Connection) -> ActivityStream<OrderedCollection> {
|
||||
let acts = self.get_activities(conn);
|
||||
let n_acts = acts.len();
|
||||
let mut coll = OrderedCollection::default();
|
||||
coll.collection_props.items = serde_json::to_value(acts).unwrap();
|
||||
coll.collection_props.set_total_items_u64(n_acts as u64).unwrap();
|
||||
coll.collection_props.items = serde_json::to_value(acts).expect("User::outbox: activity error");
|
||||
coll.collection_props.set_total_items_u64(n_acts as u64).expect("User::outbox: count error");
|
||||
ActivityStream::new(coll)
|
||||
}
|
||||
|
||||
pub fn fetch_outbox<T: Activity>(&self) -> Vec<T> {
|
||||
let req = Client::new()
|
||||
.get(&self.outbox_url[..])
|
||||
.header(ACCEPT, HeaderValue::from_str(&ap_accept_header().into_iter().collect::<Vec<_>>().join(", ")).unwrap())
|
||||
.header(ACCEPT, HeaderValue::from_str(&ap_accept_header().into_iter().collect::<Vec<_>>().join(", ")).expect("User::fetch_outbox: accept header error"))
|
||||
.send();
|
||||
match req {
|
||||
Ok(mut res) => {
|
||||
let text = &res.text().unwrap();
|
||||
let json: serde_json::Value = serde_json::from_str(text).unwrap();
|
||||
let text = &res.text().expect("User::fetch_outbox: body error");
|
||||
let json: serde_json::Value = serde_json::from_str(text).expect("User::fetch_outbox: parsing error");
|
||||
json["items"].as_array()
|
||||
.expect("Outbox.items is not an array")
|
||||
.into_iter()
|
||||
|
@ -369,14 +371,14 @@ impl User {
|
|||
pub fn fetch_followers_ids(&self) -> Vec<String> {
|
||||
let req = Client::new()
|
||||
.get(&self.followers_endpoint[..])
|
||||
.header(ACCEPT, HeaderValue::from_str(&ap_accept_header().into_iter().collect::<Vec<_>>().join(", ")).unwrap())
|
||||
.header(ACCEPT, HeaderValue::from_str(&ap_accept_header().into_iter().collect::<Vec<_>>().join(", ")).expect("User::fetch_followers_ids: accept header error"))
|
||||
.send();
|
||||
match req {
|
||||
Ok(mut res) => {
|
||||
let text = &res.text().unwrap();
|
||||
let json: serde_json::Value = serde_json::from_str(text).unwrap();
|
||||
let text = &res.text().expect("User::fetch_followers_ids: body error");
|
||||
let json: serde_json::Value = serde_json::from_str(text).expect("User::fetch_followers_ids: parsing error");
|
||||
json["items"].as_array()
|
||||
.expect("Followers.items is not an array")
|
||||
.expect("User::fetch_followers_ids: not an array error")
|
||||
.into_iter()
|
||||
.filter_map(|j| serde_json::from_value(j.clone()).ok())
|
||||
.collect::<Vec<String>>()
|
||||
|
@ -395,9 +397,9 @@ impl User {
|
|||
let posts = posts::table
|
||||
.filter(posts::published.eq(true))
|
||||
.filter(posts::id.eq_any(posts_by_self))
|
||||
.load::<Post>(conn).unwrap();
|
||||
.load::<Post>(conn).expect("User::get_activities: loading error");
|
||||
posts.into_iter().map(|p| {
|
||||
serde_json::to_value(p.create_activity(conn)).unwrap()
|
||||
serde_json::to_value(p.create_activity(conn)).expect("User::get_activities: creation error")
|
||||
}).collect::<Vec<serde_json::Value>>()
|
||||
}
|
||||
|
||||
|
@ -412,7 +414,7 @@ impl User {
|
|||
pub fn get_followers(&self, conn: &Connection) -> Vec<User> {
|
||||
use schema::follows;
|
||||
let follows = Follow::belonging_to(self).select(follows::follower_id);
|
||||
users::table.filter(users::id.eq_any(follows)).load::<User>(conn).unwrap()
|
||||
users::table.filter(users::id.eq_any(follows)).load::<User>(conn).expect("User::get_followers: loading error")
|
||||
}
|
||||
|
||||
pub fn get_followers_page(&self, conn: &Connection, (min, max): (i32, i32)) -> Vec<User> {
|
||||
|
@ -421,13 +423,13 @@ impl User {
|
|||
users::table.filter(users::id.eq_any(follows))
|
||||
.offset(min.into())
|
||||
.limit((max - min).into())
|
||||
.load::<User>(conn).unwrap()
|
||||
.load::<User>(conn).expect("User::get_followers_page: loading error")
|
||||
}
|
||||
|
||||
pub fn get_following(&self, conn: &Connection) -> Vec<User> {
|
||||
use schema::follows::dsl::*;
|
||||
let f = follows.filter(follower_id.eq(self.id)).select(following_id);
|
||||
users::table.filter(users::id.eq_any(f)).load::<User>(conn).unwrap()
|
||||
users::table.filter(users::id.eq_any(f)).load::<User>(conn).expect("User::get_following: loading error")
|
||||
}
|
||||
|
||||
pub fn is_followed_by(&self, conn: &Connection, other_id: i32) -> bool {
|
||||
|
@ -436,8 +438,8 @@ impl User {
|
|||
.filter(follows::follower_id.eq(other_id))
|
||||
.filter(follows::following_id.eq(self.id))
|
||||
.load::<Follow>(conn)
|
||||
.expect("Couldn't load follow relationship")
|
||||
.len() > 0
|
||||
.expect("User::is_followed_by: loading error")
|
||||
.len() > 0// TODO count in database?
|
||||
}
|
||||
|
||||
pub fn is_following(&self, conn: &Connection, other_id: i32) -> bool {
|
||||
|
@ -446,8 +448,8 @@ impl User {
|
|||
.filter(follows::follower_id.eq(self.id))
|
||||
.filter(follows::following_id.eq(other_id))
|
||||
.load::<Follow>(conn)
|
||||
.expect("Couldn't load follow relationship")
|
||||
.len() > 0
|
||||
.expect("User::is_following: loading error")
|
||||
.len() > 0// TODO count in database?
|
||||
}
|
||||
|
||||
pub fn has_liked(&self, conn: &Connection, post: &Post) -> bool {
|
||||
|
@ -456,8 +458,8 @@ impl User {
|
|||
.filter(likes::post_id.eq(post.id))
|
||||
.filter(likes::user_id.eq(self.id))
|
||||
.load::<Like>(conn)
|
||||
.expect("Couldn't load likes")
|
||||
.len() > 0
|
||||
.expect("User::has_liked: loading error")
|
||||
.len() > 0// TODO count in database?
|
||||
}
|
||||
|
||||
pub fn has_reshared(&self, conn: &Connection, post: &Post) -> bool {
|
||||
|
@ -466,8 +468,8 @@ impl User {
|
|||
.filter(reshares::post_id.eq(post.id))
|
||||
.filter(reshares::user_id.eq(self.id))
|
||||
.load::<Reshare>(conn)
|
||||
.expect("Couldn't load reshares")
|
||||
.len() > 0
|
||||
.expect("User::has_reshared: loading error")
|
||||
.len() > 0// TODO count in database?
|
||||
}
|
||||
|
||||
pub fn is_author_in(&self, conn: &Connection, blog: Blog) -> bool {
|
||||
|
@ -475,12 +477,14 @@ impl User {
|
|||
blog_authors::table.filter(blog_authors::author_id.eq(self.id))
|
||||
.filter(blog_authors::blog_id.eq(blog.id))
|
||||
.load::<BlogAuthor>(conn)
|
||||
.expect("Couldn't load blog/author relationship")
|
||||
.len() > 0
|
||||
.expect("User::is_author_in: loading error")
|
||||
.len() > 0// TODO count in database?
|
||||
}
|
||||
|
||||
pub fn get_keypair(&self) -> PKey<Private> {
|
||||
PKey::from_rsa(Rsa::private_key_from_pem(self.private_key.clone().unwrap().as_ref()).unwrap()).unwrap()
|
||||
PKey::from_rsa(Rsa::private_key_from_pem(self.private_key.clone().expect("User::get_keypair: private key not found error").as_ref())
|
||||
.expect("User::get_keypair: pem parsing error"))
|
||||
.expect("User::get_keypair: private key deserialization error")
|
||||
}
|
||||
|
||||
pub fn into_activity(&self, conn: &Connection) -> CustomPerson {
|
||||
|
@ -514,7 +518,7 @@ impl User {
|
|||
}
|
||||
|
||||
pub fn to_json(&self, conn: &Connection) -> serde_json::Value {
|
||||
let mut json = serde_json::to_value(self).unwrap();
|
||||
let mut json = serde_json::to_value(self).expect("User::to_json: serializing error");
|
||||
json["fqn"] = serde_json::Value::String(self.get_fqn(conn));
|
||||
json["name"] = if self.display_name.len() > 0 {
|
||||
json!(self.display_name)
|
||||
|
@ -556,7 +560,7 @@ impl User {
|
|||
User::find_by_ap_url(conn, url.clone()).or_else(|| {
|
||||
// The requested user was not in the DB
|
||||
// We try to fetch it if it is remote
|
||||
if Url::parse(url.as_ref()).unwrap().host_str().unwrap() != BASE_URL.as_str() {
|
||||
if Url::parse(url.as_ref()).expect("User::from_url: url error").host_str().expect("User::from_url: host error") != BASE_URL.as_str() {
|
||||
User::fetch_from_url(conn, url)
|
||||
} else {
|
||||
None
|
||||
|
@ -568,7 +572,7 @@ impl User {
|
|||
diesel::update(self)
|
||||
.set(users::avatar_id.eq(id))
|
||||
.execute(conn)
|
||||
.expect("Couldn't update user avatar");
|
||||
.expect("User::set_avatar: update error");
|
||||
}
|
||||
|
||||
pub fn needs_update(&self) -> bool {
|
||||
|
@ -584,7 +588,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for User {
|
|||
request.cookies()
|
||||
.get_private(AUTH_COOKIE)
|
||||
.and_then(|cookie| cookie.value().parse().ok())
|
||||
.map(|id| User::get(&*conn, id).unwrap())
|
||||
.map(|id| User::get(&*conn, id).expect("User::from_request: user not found error"))
|
||||
.or_forward(())
|
||||
}
|
||||
}
|
||||
|
@ -619,16 +623,17 @@ impl Signer for User {
|
|||
|
||||
fn sign(&self, to_sign: String) -> Vec<u8> {
|
||||
let key = self.get_keypair();
|
||||
let mut signer = sign::Signer::new(MessageDigest::sha256(), &key).unwrap();
|
||||
signer.update(to_sign.as_bytes()).unwrap();
|
||||
signer.sign_to_vec().unwrap()
|
||||
let mut signer = sign::Signer::new(MessageDigest::sha256(), &key).expect("User::sign: initialization error");
|
||||
signer.update(to_sign.as_bytes()).expect("User::sign: content insertion error");
|
||||
signer.sign_to_vec().expect("User::sign: finalization error")
|
||||
}
|
||||
|
||||
fn verify(&self, data: String, signature: Vec<u8>) -> bool {
|
||||
let key = PKey::from_rsa(Rsa::public_key_from_pem(self.public_key.as_ref()).unwrap()).unwrap();
|
||||
let mut verifier = sign::Verifier::new(MessageDigest::sha256(), &key).unwrap();
|
||||
verifier.update(data.as_bytes()).unwrap();
|
||||
verifier.verify(&signature).unwrap()
|
||||
let key = PKey::from_rsa(Rsa::public_key_from_pem(self.public_key.as_ref()).expect("User::verify: pem parsing error"))
|
||||
.expect("User::verify: deserialization error");
|
||||
let mut verifier = sign::Verifier::new(MessageDigest::sha256(), &key).expect("User::verify: initialization error");
|
||||
verifier.update(data.as_bytes()).expect("User::verify: content insertion error");
|
||||
verifier.verify(&signature).expect("User::verify: finalization error")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -655,8 +660,8 @@ impl NewUser {
|
|||
hashed_password: Some(password),
|
||||
instance_id: Instance::local_id(conn),
|
||||
ap_url: String::from(""),
|
||||
public_key: String::from_utf8(pub_key).unwrap(),
|
||||
private_key: Some(String::from_utf8(priv_key).unwrap()),
|
||||
public_key: String::from_utf8(pub_key).expect("NewUser::new_local: public key error"),
|
||||
private_key: Some(String::from_utf8(priv_key).expect("NewUser::new_local: private key error")),
|
||||
shared_inbox_url: None,
|
||||
followers_endpoint: String::from(""),
|
||||
avatar_id: None
|
||||
|
|
Loading…
Reference in New Issue