mirror of
https://git.joinplu.me/Plume/Plume.git
synced 2024-11-26 21:41:04 +00:00
Merge pull request #281 from Plume-org/panic-refactor
Panic less and with better messages
This commit is contained in:
commit
879fde81ba
32 changed files with 441 additions and 413 deletions
|
@ -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
|
||||
|
|
|
@ -19,7 +19,7 @@ fn get(id: i32, conn: DbConn) -> Json<serde_json::Value> {
|
|||
|
||||
#[get("/posts")]
|
||||
fn list(conn: DbConn, uri: &Origin) -> Json<serde_json::Value> {
|
||||
let query: PostEndpoint = serde_qs::from_str(uri.query().unwrap_or("")).expect("Invalid query string");
|
||||
let query: PostEndpoint = serde_qs::from_str(uri.query().unwrap_or("")).expect("api::list: invalid query error");
|
||||
let post = <Post as Provider<Connection>>::list(&*conn, query);
|
||||
Json(json!(post))
|
||||
}
|
||||
|
|
|
@ -16,7 +16,7 @@ use plume_models::{
|
|||
|
||||
pub trait Inbox {
|
||||
fn received(&self, conn: &Connection, act: serde_json::Value) -> Result<(), Error> {
|
||||
let actor_id = Id::new(act["actor"].as_str().unwrap_or_else(|| act["actor"]["id"].as_str().expect("No actor ID for incoming activity")));
|
||||
let actor_id = Id::new(act["actor"].as_str().unwrap_or_else(|| act["actor"]["id"].as_str().expect("Inbox::received: actor_id missing error")));
|
||||
match act["type"].as_str() {
|
||||
Some(t) => {
|
||||
match t {
|
||||
|
@ -47,7 +47,7 @@ pub trait Inbox {
|
|||
},
|
||||
"Undo" => {
|
||||
let act: Undo = serde_json::from_value(act.clone())?;
|
||||
match act.undo_props.object["type"].as_str().unwrap() {
|
||||
match act.undo_props.object["type"].as_str().expect("Inbox::received: undo without original type error") {
|
||||
"Like" => {
|
||||
likes::Like::delete_id(act.undo_props.object_object::<Like>()?.object_props.id_string()?, conn);
|
||||
Ok(())
|
||||
|
|
|
@ -56,7 +56,7 @@ fn init_pool() -> Option<DbPool> {
|
|||
}
|
||||
|
||||
fn main() {
|
||||
let pool = init_pool().expect("Couldn't intialize database pool");
|
||||
let pool = init_pool().expect("main: database pool initialization error");
|
||||
rocket::ignite()
|
||||
.mount("/", routes![
|
||||
routes::blogs::paginated_details,
|
||||
|
@ -176,6 +176,6 @@ fn main() {
|
|||
("/login".to_owned(), "/login".to_owned(), rocket::http::Method::Post),
|
||||
("/users/new".to_owned(), "/users/new".to_owned(), rocket::http::Method::Post),
|
||||
])
|
||||
.finalize().unwrap())
|
||||
.finalize().expect("main: csrf fairing creation error"))
|
||||
.launch();
|
||||
}
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
use activitypub::collection::OrderedCollection;
|
||||
use atom_syndication::{Entry, FeedBuilder};
|
||||
use rocket::{
|
||||
http::ContentType,
|
||||
request::LenientForm,
|
||||
response::{Redirect, Flash, content::Content},
|
||||
http::ContentType
|
||||
response::{Redirect, Flash, content::Content}
|
||||
};
|
||||
use rocket_contrib::Template;
|
||||
use serde_json;
|
||||
|
@ -49,9 +49,9 @@ fn details(name: String, conn: DbConn, user: Option<User>) -> Template {
|
|||
}
|
||||
|
||||
#[get("/~/<name>", rank = 1)]
|
||||
fn activity_details(name: String, conn: DbConn, _ap: ApRequest) -> ActivityStream<CustomGroup> {
|
||||
let blog = Blog::find_local(&*conn, name).unwrap();
|
||||
ActivityStream::new(blog.into_activity(&*conn))
|
||||
fn activity_details(name: String, conn: DbConn, _ap: ApRequest) -> Option<ActivityStream<CustomGroup>> {
|
||||
let blog = Blog::find_local(&*conn, name)?;
|
||||
Some(ActivityStream::new(blog.into_activity(&*conn)))
|
||||
}
|
||||
|
||||
#[get("/blogs/new")]
|
||||
|
@ -130,22 +130,23 @@ fn create(conn: DbConn, data: LenientForm<NewBlogForm>, user: User) -> Result<Re
|
|||
}
|
||||
|
||||
#[get("/~/<name>/outbox")]
|
||||
fn outbox(name: String, conn: DbConn) -> ActivityStream<OrderedCollection> {
|
||||
let blog = Blog::find_local(&*conn, name).unwrap();
|
||||
blog.outbox(&*conn)
|
||||
fn outbox(name: String, conn: DbConn) -> Option<ActivityStream<OrderedCollection>> {
|
||||
let blog = Blog::find_local(&*conn, name)?;
|
||||
Some(blog.outbox(&*conn))
|
||||
}
|
||||
|
||||
#[get("/~/<name>/atom.xml")]
|
||||
fn atom_feed(name: String, conn: DbConn) -> Content<String> {
|
||||
let blog = Blog::find_by_fqn(&*conn, name.clone()).expect("Unable to find blog");
|
||||
fn atom_feed(name: String, conn: DbConn) -> Option<Content<String>> {
|
||||
let blog = Blog::find_by_fqn(&*conn, name.clone())?;
|
||||
let feed = FeedBuilder::default()
|
||||
.title(blog.title.clone())
|
||||
.id(Instance::get_local(&*conn).unwrap().compute_box("~", name, "atom.xml"))
|
||||
.id(Instance::get_local(&*conn).expect("blogs::atom_feed: local instance not found error")
|
||||
.compute_box("~", name, "atom.xml"))
|
||||
.entries(Post::get_recents_for_blog(&*conn, &blog, 15)
|
||||
.into_iter()
|
||||
.map(|p| super::post_to_atom(p, &*conn))
|
||||
.collect::<Vec<Entry>>())
|
||||
.build()
|
||||
.expect("Error building Atom feed");
|
||||
Content(ContentType::new("application", "atom+xml"), feed.to_string())
|
||||
.expect("blogs::atom_feed: feed creation error");
|
||||
Some(Content(ContentType::new("application", "atom+xml"), feed.to_string()))
|
||||
}
|
||||
|
|
|
@ -28,9 +28,10 @@ struct NewCommentForm {
|
|||
}
|
||||
|
||||
#[post("/~/<blog_name>/<slug>/comment", data = "<data>")]
|
||||
fn create(blog_name: String, slug: String, data: LenientForm<NewCommentForm>, user: User, conn: DbConn, worker: State<Pool<ThunkWorker<()>>>) -> Result<Redirect, Template> {
|
||||
let blog = Blog::find_by_fqn(&*conn, blog_name.clone()).unwrap();
|
||||
let post = Post::find_by_slug(&*conn, slug.clone(), blog.id).unwrap();
|
||||
fn create(blog_name: String, slug: String, data: LenientForm<NewCommentForm>, user: User, conn: DbConn, worker: State<Pool<ThunkWorker<()>>>)
|
||||
-> Result<Redirect, Option<Template>> {
|
||||
let blog = Blog::find_by_fqn(&*conn, blog_name.clone()).ok_or(None)?;
|
||||
let post = Post::find_by_slug(&*conn, slug.clone(), blog.id).ok_or(None)?;
|
||||
let form = data.get();
|
||||
form.validate()
|
||||
.map(|_| {
|
||||
|
@ -63,7 +64,7 @@ fn create(blog_name: String, slug: String, data: LenientForm<NewCommentForm>, us
|
|||
let comments = Comment::list_by_post(&*conn, post.id);
|
||||
let comms = comments.clone();
|
||||
|
||||
Template::render("posts/details", json!({
|
||||
Some(Template::render("posts/details", json!({
|
||||
"author": post.get_authors(&*conn)[0].to_json(&*conn),
|
||||
"post": post,
|
||||
"blog": blog,
|
||||
|
@ -74,10 +75,10 @@ fn create(blog_name: String, slug: String, data: LenientForm<NewCommentForm>, us
|
|||
"has_reshared": user.has_reshared(&*conn, &post),
|
||||
"account": user.to_json(&*conn),
|
||||
"date": &post.creation_date.timestamp(),
|
||||
"previous": form.responding_to.map(|r| Comment::get(&*conn, r).expect("Error retrieving previous comment").to_json(&*conn, &vec![])),
|
||||
"previous": form.responding_to.and_then(|r| Comment::get(&*conn, r)).map(|r| r.to_json(&*conn, &vec![])),
|
||||
"user_fqn": user.get_fqn(&*conn),
|
||||
"errors": errors
|
||||
}))
|
||||
})))
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
@ -6,21 +6,21 @@ use plume_models::users::User;
|
|||
|
||||
#[catch(404)]
|
||||
fn not_found(req: &Request) -> Template {
|
||||
let conn = req.guard::<DbConn>().expect("404: DbConn error");
|
||||
let conn = req.guard::<DbConn>().succeeded();
|
||||
let user = User::from_request(req).succeeded();
|
||||
Template::render("errors/404", json!({
|
||||
"error_message": "Page not found",
|
||||
"account": user.map(|u| u.to_json(&*conn))
|
||||
"account": user.and_then(|u| conn.map(|conn| u.to_json(&*conn)))
|
||||
}))
|
||||
}
|
||||
|
||||
#[catch(500)]
|
||||
fn server_error(req: &Request) -> Template {
|
||||
let conn = req.guard::<DbConn>().expect("500: DbConn error");
|
||||
let conn = req.guard::<DbConn>().succeeded();
|
||||
let user = User::from_request(req).succeeded();
|
||||
Template::render("errors/500", json!({
|
||||
"error_message": "Server error",
|
||||
"account": user.map(|u| u.to_json(&*conn))
|
||||
"account": user.and_then(|u| conn.map(|conn| u.to_json(&*conn)))
|
||||
}))
|
||||
}
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
use gettextrs::gettext;
|
||||
use rocket::{request::LenientForm, response::Redirect};
|
||||
use rocket::{request::LenientForm, response::{status, Redirect}};
|
||||
use rocket_contrib::{Json, Template};
|
||||
use serde_json;
|
||||
use validator::{Validate};
|
||||
|
@ -52,7 +52,7 @@ fn index(conn: DbConn, user: Option<User>) -> Template {
|
|||
|
||||
#[get("/local?<page>")]
|
||||
fn paginated_local(conn: DbConn, user: Option<User>, page: Page) -> Template {
|
||||
let instance = Instance::get_local(&*conn).unwrap();
|
||||
let instance = Instance::get_local(&*conn).expect("instance::paginated_local: local instance not found error");
|
||||
let articles = Post::get_instance_page(&*conn, instance.id, page.limits());
|
||||
Template::render("instance/local", json!({
|
||||
"account": user.map(|u| u.to_json(&*conn)),
|
||||
|
@ -129,7 +129,7 @@ fn update_settings(conn: DbConn, admin: Admin, form: LenientForm<InstanceSetting
|
|||
let form = form.get();
|
||||
form.validate()
|
||||
.map(|_| {
|
||||
let instance = Instance::get_local(&*conn).unwrap();
|
||||
let instance = Instance::get_local(&*conn).expect("instance::update_settings: local instance not found error");
|
||||
instance.update(&*conn,
|
||||
form.name.clone(),
|
||||
form.open_registrations,
|
||||
|
@ -196,31 +196,31 @@ fn ban(_admin: Admin, conn: DbConn, id: i32) -> Redirect {
|
|||
}
|
||||
|
||||
#[post("/inbox", data = "<data>")]
|
||||
fn shared_inbox(conn: DbConn, data: String, headers: Headers) -> String {
|
||||
let act: serde_json::Value = serde_json::from_str(&data[..]).unwrap();
|
||||
fn shared_inbox(conn: DbConn, data: String, headers: Headers) -> Result<String, status::BadRequest<&'static str>> {
|
||||
let act: serde_json::Value = serde_json::from_str(&data[..]).expect("instance::shared_inbox: deserialization error");
|
||||
|
||||
let activity = act.clone();
|
||||
let actor_id = activity["actor"].as_str()
|
||||
.unwrap_or_else(|| activity["actor"]["id"].as_str().expect("No actor ID for incoming activity, blocks by panicking"));
|
||||
.or_else(|| activity["actor"]["id"].as_str()).ok_or(status::BadRequest(Some("Missing actor id for activity")))?;
|
||||
|
||||
let actor = User::from_url(&conn, actor_id.to_owned()).unwrap();
|
||||
let actor = User::from_url(&conn, actor_id.to_owned()).expect("instance::shared_inbox: user error");
|
||||
if !verify_http_headers(&actor, headers.0.clone(), data).is_secure() &&
|
||||
!act.clone().verify(&actor) {
|
||||
println!("Rejected invalid activity supposedly from {}, with headers {:?}", actor.username, headers.0);
|
||||
return "invalid signature".to_owned();
|
||||
return Err(status::BadRequest(Some("Invalid signature")));
|
||||
}
|
||||
|
||||
if Instance::is_blocked(&*conn, actor_id.to_string()) {
|
||||
return String::new();
|
||||
return Ok(String::new());
|
||||
}
|
||||
let instance = Instance::get_local(&*conn).unwrap();
|
||||
match instance.received(&*conn, act) {
|
||||
let instance = Instance::get_local(&*conn).expect("instance::shared_inbox: local instance not found error");
|
||||
Ok(match instance.received(&*conn, act) {
|
||||
Ok(_) => String::new(),
|
||||
Err(e) => {
|
||||
println!("Shared inbox error: {}\n{}", e.as_fail(), e.backtrace());
|
||||
format!("Error: {}", e.as_fail())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[get("/nodeinfo")]
|
||||
|
@ -263,7 +263,7 @@ fn about(user: Option<User>, conn: DbConn) -> Template {
|
|||
|
||||
#[get("/manifest.json")]
|
||||
fn web_manifest(conn: DbConn) -> Json<serde_json::Value> {
|
||||
let instance = Instance::get_local(&*conn).unwrap();
|
||||
let instance = Instance::get_local(&*conn).expect("instance::web_manifest: local instance not found error");
|
||||
Json(json!({
|
||||
"name": &instance.name,
|
||||
"description": &instance.short_description,
|
||||
|
|
|
@ -12,9 +12,9 @@ use plume_models::{
|
|||
};
|
||||
|
||||
#[post("/~/<blog>/<slug>/like")]
|
||||
fn create(blog: String, slug: String, user: User, conn: DbConn, worker: State<Pool<ThunkWorker<()>>>) -> Redirect {
|
||||
let b = Blog::find_by_fqn(&*conn, blog.clone()).unwrap();
|
||||
let post = Post::find_by_slug(&*conn, slug.clone(), b.id).unwrap();
|
||||
fn create(blog: String, slug: String, user: User, conn: DbConn, worker: State<Pool<ThunkWorker<()>>>) -> Option<Redirect> {
|
||||
let b = Blog::find_by_fqn(&*conn, blog.clone())?;
|
||||
let post = Post::find_by_slug(&*conn, slug.clone(), b.id)?;
|
||||
|
||||
if !user.has_liked(&*conn, &post) {
|
||||
let like = likes::Like::insert(&*conn, likes::NewLike {
|
||||
|
@ -29,13 +29,13 @@ fn create(blog: String, slug: String, user: User, conn: DbConn, worker: State<Po
|
|||
let act = like.into_activity(&*conn);
|
||||
worker.execute(Thunk::of(move || broadcast(&user, act, dest)));
|
||||
} else {
|
||||
let like = likes::Like::find_by_user_on_post(&*conn, user.id, post.id).unwrap();
|
||||
let like = likes::Like::find_by_user_on_post(&*conn, user.id, post.id).expect("likes::create: like exist but not found error");
|
||||
let delete_act = like.delete(&*conn);
|
||||
let dest = User::one_by_instance(&*conn);
|
||||
worker.execute(Thunk::of(move || broadcast(&user, delete_act, dest)));
|
||||
}
|
||||
|
||||
Redirect::to(uri!(super::posts::details: blog = blog, slug = slug))
|
||||
Some(Redirect::to(uri!(super::posts::details: blog = blog, slug = slug)))
|
||||
}
|
||||
|
||||
#[post("/~/<blog>/<slug>/like", rank = 2)]
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
use guid_create::GUID;
|
||||
use multipart::server::{Multipart, save::{SavedData, SaveResult}};
|
||||
use rocket::{Data, http::ContentType, response::Redirect};
|
||||
use rocket::{Data, http::ContentType, response::{Redirect, status}};
|
||||
use rocket_contrib::Template;
|
||||
use serde_json;
|
||||
use std::fs;
|
||||
|
@ -25,30 +25,27 @@ fn new(user: User, conn: DbConn) -> Template {
|
|||
}
|
||||
|
||||
#[post("/medias/new", data = "<data>")]
|
||||
fn upload(user: User, data: Data, ct: &ContentType, conn: DbConn) -> Redirect {
|
||||
fn upload(user: User, data: Data, ct: &ContentType, conn: DbConn) -> Result<Redirect, status::BadRequest<&'static str>> {
|
||||
if ct.is_form_data() {
|
||||
let (_, boundary) = ct.params().find(|&(k, _)| k == "boundary").expect("No boundary");
|
||||
let (_, boundary) = ct.params().find(|&(k, _)| k == "boundary").ok_or_else(|| status::BadRequest(Some("No boundary")))?;
|
||||
|
||||
match Multipart::with_body(data.open(), boundary).save().temp() {
|
||||
SaveResult::Full(entries) => {
|
||||
let fields = entries.fields;
|
||||
|
||||
let filename = fields.get(&"file".to_string()).unwrap().into_iter().next().unwrap().headers
|
||||
.filename.clone()
|
||||
.unwrap_or("x.png".to_string()); // PNG by default
|
||||
let ext = filename.rsplitn(2, ".")
|
||||
.next()
|
||||
.unwrap();
|
||||
let filename = fields.get(&"file".to_string()).and_then(|v| v.into_iter().next())
|
||||
.ok_or_else(|| status::BadRequest(Some("No file uploaded")))?.headers
|
||||
.filename.clone();
|
||||
let ext = filename.and_then(|f| f.rsplit('.').next().map(|ext| ext.to_owned()))
|
||||
.unwrap_or("png".to_owned());
|
||||
let dest = format!("static/media/{}.{}", GUID::rand().to_string(), ext);
|
||||
|
||||
if let SavedData::Bytes(ref bytes) = fields[&"file".to_string()][0].data {
|
||||
fs::write(&dest, bytes).expect("Couldn't save upload");
|
||||
} else {
|
||||
if let SavedData::File(ref path, _) = fields[&"file".to_string()][0].data {
|
||||
fs::copy(path, &dest).expect("Couldn't copy temp upload");
|
||||
} else {
|
||||
println!("not file");
|
||||
return Redirect::to(uri!(new));
|
||||
match fields[&"file".to_string()][0].data {
|
||||
SavedData::Bytes(ref bytes) => fs::write(&dest, bytes).expect("media::upload: Couldn't save upload"),
|
||||
SavedData::File(ref path, _) => {fs::copy(path, &dest).expect("media::upload: Couldn't copy upload");},
|
||||
_ => {
|
||||
println!("not a file");
|
||||
return Ok(Redirect::to(uri!(new)));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -67,16 +64,16 @@ fn upload(user: User, data: Data, ct: &ContentType, conn: DbConn) -> Redirect {
|
|||
owner_id: user.id
|
||||
});
|
||||
println!("ok");
|
||||
Redirect::to(uri!(details: id = media.id))
|
||||
Ok(Redirect::to(uri!(details: id = media.id)))
|
||||
},
|
||||
SaveResult::Partial(_, _) | SaveResult::Error(_) => {
|
||||
println!("partial err");
|
||||
Redirect::to(uri!(new))
|
||||
Ok(Redirect::to(uri!(new)))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
println!("not form data");
|
||||
Redirect::to(uri!(new))
|
||||
Ok(Redirect::to(uri!(new)))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -98,15 +95,15 @@ fn details(id: i32, user: User, conn: DbConn) -> Template {
|
|||
}
|
||||
|
||||
#[post("/medias/<id>/delete")]
|
||||
fn delete(id: i32, _user: User, conn: DbConn) -> Redirect {
|
||||
let media = Media::get(&*conn, id).expect("Media to delete not found");
|
||||
fn delete(id: i32, _user: User, conn: DbConn) -> Option<Redirect> {
|
||||
let media = Media::get(&*conn, id)?;
|
||||
media.delete(&*conn);
|
||||
Redirect::to(uri!(list))
|
||||
Some(Redirect::to(uri!(list)))
|
||||
}
|
||||
|
||||
#[post("/medias/<id>/avatar")]
|
||||
fn set_avatar(id: i32, user: User, conn: DbConn) -> Redirect {
|
||||
let media = Media::get(&*conn, id).expect("Media to delete not found");
|
||||
fn set_avatar(id: i32, user: User, conn: DbConn) -> Option<Redirect> {
|
||||
let media = Media::get(&*conn, id)?;
|
||||
user.set_avatar(&*conn, media.id);
|
||||
Redirect::to(uri!(details: id = id))
|
||||
Some(Redirect::to(uri!(details: id = id)))
|
||||
}
|
||||
|
|
|
@ -58,7 +58,8 @@ fn details_response(blog: String, slug: String, conn: DbConn, user: Option<User>
|
|||
"has_reshared": user.clone().map(|u| u.has_reshared(&*conn, &post)).unwrap_or(false),
|
||||
"account": &user.clone().map(|u| u.to_json(&*conn)),
|
||||
"date": &post.creation_date.timestamp(),
|
||||
"previous": query.and_then(|q| q.responding_to.map(|r| Comment::get(&*conn, r).expect("Error retrieving previous comment").to_json(&*conn, &vec![]))),
|
||||
"previous": query.and_then(|q| q.responding_to.map(|r| Comment::get(&*conn, r)
|
||||
.expect("posts::details_reponse: Error retrieving previous comment").to_json(&*conn, &vec![]))),
|
||||
"user_fqn": user.clone().map(|u| u.get_fqn(&*conn)).unwrap_or(String::new()),
|
||||
"is_author": user.clone().map(|u| post.get_authors(&*conn).into_iter().any(|a| u.id == a.id)).unwrap_or(false),
|
||||
"is_following": user.map(|u| u.is_following(&*conn, post.get_authors(&*conn)[0].id)).unwrap_or(false)
|
||||
|
@ -73,13 +74,13 @@ fn details_response(blog: String, slug: String, conn: DbConn, user: Option<User>
|
|||
}
|
||||
|
||||
#[get("/~/<blog>/<slug>", rank = 3)]
|
||||
fn activity_details(blog: String, slug: String, conn: DbConn, _ap: ApRequest) -> Result<ActivityStream<Article>, String> {
|
||||
let blog = Blog::find_by_fqn(&*conn, blog).unwrap();
|
||||
let post = Post::find_by_slug(&*conn, slug, blog.id).unwrap();
|
||||
fn activity_details(blog: String, slug: String, conn: DbConn, _ap: ApRequest) -> Result<ActivityStream<Article>, Option<String>> {
|
||||
let blog = Blog::find_by_fqn(&*conn, blog).ok_or(None)?;
|
||||
let post = Post::find_by_slug(&*conn, slug, blog.id).ok_or(None)?;
|
||||
if post.published {
|
||||
Ok(ActivityStream::new(post.into_activity(&*conn)))
|
||||
} else {
|
||||
Err(String::from("Not published yet."))
|
||||
Err(Some(String::from("Not published yet.")))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -92,42 +93,42 @@ fn new_auth(blog: String) -> Flash<Redirect> {
|
|||
}
|
||||
|
||||
#[get("/~/<blog>/new", rank = 1)]
|
||||
fn new(blog: String, user: User, conn: DbConn) -> Template {
|
||||
let b = Blog::find_by_fqn(&*conn, blog.to_string()).unwrap();
|
||||
fn new(blog: String, user: User, conn: DbConn) -> Option<Template> {
|
||||
let b = Blog::find_by_fqn(&*conn, blog.to_string())?;
|
||||
|
||||
if !user.is_author_in(&*conn, b.clone()) {
|
||||
Template::render("errors/403", json!({
|
||||
Some(Template::render("errors/403", json!({// TODO actually return 403 error code
|
||||
"error_message": "You are not author in this blog."
|
||||
}))
|
||||
})))
|
||||
} else {
|
||||
Template::render("posts/new", json!({
|
||||
Some(Template::render("posts/new", json!({
|
||||
"account": user.to_json(&*conn),
|
||||
"instance": Instance::get_local(&*conn),
|
||||
"editing": false,
|
||||
"errors": null,
|
||||
"form": null,
|
||||
"is_draft": true,
|
||||
}))
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
#[get("/~/<blog>/<slug>/edit")]
|
||||
fn edit(blog: String, slug: String, user: User, conn: DbConn) -> Template {
|
||||
let b = Blog::find_by_fqn(&*conn, blog.to_string());
|
||||
let post = b.clone().and_then(|blog| Post::find_by_slug(&*conn, slug, blog.id)).expect("Post to edit not found");
|
||||
fn edit(blog: String, slug: String, user: User, conn: DbConn) -> Option<Template> {
|
||||
let b = Blog::find_by_fqn(&*conn, blog.to_string())?;
|
||||
let post = Post::find_by_slug(&*conn, slug, b.id)?;
|
||||
|
||||
if !user.is_author_in(&*conn, b.clone().unwrap()) {
|
||||
Template::render("errors/403", json!({
|
||||
if !user.is_author_in(&*conn, b) {
|
||||
Some(Template::render("errors/403", json!({// TODO actually return 403 error code
|
||||
"error_message": "You are not author in this blog."
|
||||
}))
|
||||
})))
|
||||
} else {
|
||||
let source = if post.source.clone().len() > 0 {
|
||||
post.source.clone()
|
||||
let source = if post.source.len() > 0 {
|
||||
post.source
|
||||
} else {
|
||||
post.content.clone().get().clone() // fallback to HTML if the markdown was not stored
|
||||
post.content.get().clone() // fallback to HTML if the markdown was not stored
|
||||
};
|
||||
|
||||
Template::render("posts/new", json!({
|
||||
Some(Template::render("posts/new", json!({
|
||||
"account": user.to_json(&*conn),
|
||||
"instance": Instance::get_local(&*conn),
|
||||
"editing": true,
|
||||
|
@ -145,14 +146,15 @@ fn edit(blog: String, slug: String, user: User, conn: DbConn) -> Template {
|
|||
draft: true,
|
||||
},
|
||||
"is_draft": !post.published
|
||||
}))
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
#[post("/~/<blog>/<slug>/edit", data = "<data>")]
|
||||
fn update(blog: String, slug: String, user: User, conn: DbConn, data: LenientForm<NewPostForm>, worker: State<Pool<ThunkWorker<()>>>) -> Result<Redirect, Template> {
|
||||
let b = Blog::find_by_fqn(&*conn, blog.to_string());
|
||||
let mut post = b.clone().and_then(|blog| Post::find_by_slug(&*conn, slug.clone(), blog.id)).expect("Post to update not found");
|
||||
fn update(blog: String, slug: String, user: User, conn: DbConn, data: LenientForm<NewPostForm>, worker: State<Pool<ThunkWorker<()>>>)
|
||||
-> Result<Redirect, Option<Template>> {
|
||||
let b = Blog::find_by_fqn(&*conn, blog.to_string()).ok_or(None)?;
|
||||
let mut post = Post::find_by_slug(&*conn, slug.clone(), b.id).ok_or(None)?;
|
||||
|
||||
let form = data.get();
|
||||
let new_slug = if !post.published {
|
||||
|
@ -167,7 +169,7 @@ fn update(blog: String, slug: String, user: User, conn: DbConn, data: LenientFor
|
|||
};
|
||||
|
||||
if new_slug != slug {
|
||||
if let Some(_) = Post::find_by_slug(&*conn, new_slug.clone(), b.clone().unwrap().id) {
|
||||
if let Some(_) = Post::find_by_slug(&*conn, new_slug.clone(), b.id) {
|
||||
errors.add("title", ValidationError {
|
||||
code: Cow::from("existing_slug"),
|
||||
message: Some(Cow::from("A post with the same title already exists.")),
|
||||
|
@ -177,7 +179,7 @@ fn update(blog: String, slug: String, user: User, conn: DbConn, data: LenientFor
|
|||
}
|
||||
|
||||
if errors.is_empty() {
|
||||
if !user.is_author_in(&*conn, b.clone().unwrap()) {
|
||||
if !user.is_author_in(&*conn, b) {
|
||||
// actually it's not "Ok"…
|
||||
Ok(Redirect::to(uri!(super::blogs::details: name = blog)))
|
||||
} else {
|
||||
|
@ -229,14 +231,14 @@ fn update(blog: String, slug: String, user: User, conn: DbConn, data: LenientFor
|
|||
Ok(Redirect::to(uri!(details: blog = blog, slug = new_slug)))
|
||||
}
|
||||
} else {
|
||||
Err(Template::render("posts/new", json!({
|
||||
Err(Some(Template::render("posts/new", json!({
|
||||
"account": user.to_json(&*conn),
|
||||
"instance": Instance::get_local(&*conn),
|
||||
"editing": true,
|
||||
"errors": errors.inner(),
|
||||
"form": form,
|
||||
"is_draft": form.draft,
|
||||
})))
|
||||
}))))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -263,8 +265,8 @@ fn valid_slug(title: &str) -> Result<(), ValidationError> {
|
|||
}
|
||||
|
||||
#[post("/~/<blog_name>/new", data = "<data>")]
|
||||
fn create(blog_name: String, data: LenientForm<NewPostForm>, user: User, conn: DbConn, worker: State<Pool<ThunkWorker<()>>>) -> Result<Redirect, Template> {
|
||||
let blog = Blog::find_by_fqn(&*conn, blog_name.to_string()).unwrap();
|
||||
fn create(blog_name: String, data: LenientForm<NewPostForm>, user: User, conn: DbConn, worker: State<Pool<ThunkWorker<()>>>) -> Result<Redirect, Option<Template>> {
|
||||
let blog = Blog::find_by_fqn(&*conn, blog_name.to_string()).ok_or(None)?;
|
||||
let form = data.get();
|
||||
let slug = form.title.to_string().to_kebab_case();
|
||||
|
||||
|
@ -331,14 +333,14 @@ fn create(blog_name: String, data: LenientForm<NewPostForm>, user: User, conn: D
|
|||
Ok(Redirect::to(uri!(details: blog = blog_name, slug = slug)))
|
||||
}
|
||||
} else {
|
||||
Err(Template::render("posts/new", json!({
|
||||
Err(Some(Template::render("posts/new", json!({
|
||||
"account": user.to_json(&*conn),
|
||||
"instance": Instance::get_local(&*conn),
|
||||
"editing": false,
|
||||
"errors": errors.inner(),
|
||||
"form": form,
|
||||
"is_draft": form.draft
|
||||
})))
|
||||
}))))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -12,9 +12,9 @@ use plume_models::{
|
|||
};
|
||||
|
||||
#[post("/~/<blog>/<slug>/reshare")]
|
||||
fn create(blog: String, slug: String, user: User, conn: DbConn, worker: State<Pool<ThunkWorker<()>>>) -> Redirect {
|
||||
let b = Blog::find_by_fqn(&*conn, blog.clone()).unwrap();
|
||||
let post = Post::find_by_slug(&*conn, slug.clone(), b.id).unwrap();
|
||||
fn create(blog: String, slug: String, user: User, conn: DbConn, worker: State<Pool<ThunkWorker<()>>>) -> Option<Redirect> {
|
||||
let b = Blog::find_by_fqn(&*conn, blog.clone())?;
|
||||
let post = Post::find_by_slug(&*conn, slug.clone(), b.id)?;
|
||||
|
||||
if !user.has_reshared(&*conn, &post) {
|
||||
let reshare = Reshare::insert(&*conn, NewReshare {
|
||||
|
@ -29,13 +29,14 @@ fn create(blog: String, slug: String, user: User, conn: DbConn, worker: State<Po
|
|||
let act = reshare.into_activity(&*conn);
|
||||
worker.execute(Thunk::of(move || broadcast(&user, act, dest)));
|
||||
} else {
|
||||
let reshare = Reshare::find_by_user_on_post(&*conn, user.id, post.id).unwrap();
|
||||
let reshare = Reshare::find_by_user_on_post(&*conn, user.id, post.id)
|
||||
.expect("reshares::create: reshare exist but not found error");
|
||||
let delete_act = reshare.delete(&*conn);
|
||||
let dest = User::one_by_instance(&*conn);
|
||||
worker.execute(Thunk::of(move || broadcast(&user, delete_act, dest)));
|
||||
}
|
||||
|
||||
Redirect::to(uri!(super::posts::details: blog = blog, slug = slug))
|
||||
Some(Redirect::to(uri!(super::posts::details: blog = blog, slug = slug)))
|
||||
}
|
||||
|
||||
#[post("/~/<blog>/<slug>/reshare", rank=1)]
|
||||
|
|
|
@ -50,22 +50,23 @@ struct LoginForm {
|
|||
fn create(conn: DbConn, data: LenientForm<LoginForm>, flash: Option<FlashMessage>, mut cookies: Cookies) -> Result<Redirect, Template> {
|
||||
let form = data.get();
|
||||
let user = User::find_by_email(&*conn, form.email_or_name.to_string())
|
||||
.map(|u| Ok(u))
|
||||
.unwrap_or_else(|| User::find_local(&*conn, form.email_or_name.to_string()).map(|u| Ok(u)).unwrap_or(Err(())));
|
||||
|
||||
.or_else(|| User::find_local(&*conn, form.email_or_name.to_string()));
|
||||
let mut errors = match form.validate() {
|
||||
Ok(_) => ValidationErrors::new(),
|
||||
Err(e) => e
|
||||
};
|
||||
if let Err(_) = user.clone() {
|
||||
|
||||
if let Some(user) = user.clone() {
|
||||
if !user.auth(form.password.clone()) {
|
||||
let mut err = ValidationError::new("invalid_login");
|
||||
err.message = Some(Cow::from("Invalid username or password"));
|
||||
errors.add("email_or_name", err)
|
||||
}
|
||||
} else {
|
||||
// Fake password verification, only to avoid different login times
|
||||
// that could be used to see if an email adress is registered or not
|
||||
User::get(&*conn, 1).map(|u| u.auth(form.password.clone()));
|
||||
|
||||
let mut err = ValidationError::new("invalid_login");
|
||||
err.message = Some(Cow::from("Invalid username or password"));
|
||||
errors.add("email_or_name", err)
|
||||
} else if !user.clone().expect("User not found").auth(form.password.clone()) {
|
||||
let mut err = ValidationError::new("invalid_login");
|
||||
err.message = Some(Cow::from("Invalid username or password"));
|
||||
errors.add("email_or_name", err)
|
||||
|
@ -107,7 +108,6 @@ fn create(conn: DbConn, data: LenientForm<LoginForm>, flash: Option<FlashMessage
|
|||
|
||||
#[get("/logout")]
|
||||
fn delete(mut cookies: Cookies) -> Redirect {
|
||||
let cookie = cookies.get_private(AUTH_COOKIE).unwrap();
|
||||
cookies.remove_private(cookie);
|
||||
cookies.get_private(AUTH_COOKIE).map(|cookie| cookies.remove_private(cookie));
|
||||
Redirect::to("/")
|
||||
}
|
||||
|
|
|
@ -10,19 +10,19 @@ use plume_models::{
|
|||
use routes::Page;
|
||||
|
||||
#[get("/tag/<name>")]
|
||||
fn tag(user: Option<User>, conn: DbConn, name: String) -> Template {
|
||||
fn tag(user: Option<User>, conn: DbConn, name: String) -> Option<Template> {
|
||||
paginated_tag(user, conn, name, Page::first())
|
||||
}
|
||||
|
||||
#[get("/tag/<name>?<page>")]
|
||||
fn paginated_tag(user: Option<User>, conn: DbConn, name: String, page: Page) -> Template {
|
||||
let tag = Tag::find_by_name(&*conn, name).expect("Rendering tags::tag: tag not found");
|
||||
fn paginated_tag(user: Option<User>, conn: DbConn, name: String, page: Page) -> Option<Template> {
|
||||
let tag = Tag::find_by_name(&*conn, name)?;
|
||||
let posts = Post::list_by_tag(&*conn, tag.tag.clone(), page.limits());
|
||||
Template::render("tags/index", json!({
|
||||
Some(Template::render("tags/index", json!({
|
||||
"tag": tag.clone(),
|
||||
"account": user.map(|u| u.to_json(&*conn)),
|
||||
"articles": posts.into_iter().map(|p| p.to_json(&*conn)).collect::<Vec<serde_json::Value>>(),
|
||||
"page": page.page,
|
||||
"n_pages": Page::total(Post::count_for_tag(&*conn, tag.tag) as i32)
|
||||
}))
|
||||
})))
|
||||
}
|
||||
|
|
|
@ -6,7 +6,7 @@ use activitypub::{
|
|||
use atom_syndication::{Entry, FeedBuilder};
|
||||
use rocket::{
|
||||
request::LenientForm,
|
||||
response::{Redirect, Flash, Content},
|
||||
response::{Content, Flash, Redirect, status},
|
||||
http::{ContentType, Cookies}
|
||||
};
|
||||
use rocket_contrib::Template;
|
||||
|
@ -70,7 +70,7 @@ fn details(name: String, conn: DbConn, account: Option<User>, worker: Worker, fe
|
|||
worker.execute(Thunk::of(move || {
|
||||
for user_id in user_clone.fetch_followers_ids() {
|
||||
let follower = User::find_by_ap_url(&*fecth_followers_conn, user_id.clone())
|
||||
.unwrap_or_else(|| User::fetch_from_url(&*fecth_followers_conn, user_id).expect("Couldn't fetch follower"));
|
||||
.unwrap_or_else(|| User::fetch_from_url(&*fecth_followers_conn, user_id).expect("user::details: Couldn't fetch follower"));
|
||||
follows::Follow::insert(&*fecth_followers_conn, follows::NewFollow {
|
||||
follower_id: follower.id,
|
||||
following_id: user_clone.id,
|
||||
|
@ -121,8 +121,8 @@ fn dashboard_auth() -> Flash<Redirect> {
|
|||
}
|
||||
|
||||
#[post("/@/<name>/follow")]
|
||||
fn follow(name: String, conn: DbConn, user: User, worker: Worker) -> Redirect {
|
||||
let target = User::find_by_fqn(&*conn, name.clone()).unwrap();
|
||||
fn follow(name: String, conn: DbConn, user: User, worker: Worker) -> Option<Redirect> {
|
||||
let target = User::find_by_fqn(&*conn, name.clone())?;
|
||||
if let Some(follow) = follows::Follow::find(&*conn, user.id, target.id) {
|
||||
let delete_act = follow.delete(&*conn);
|
||||
worker.execute(Thunk::of(move || broadcast(&user, delete_act, vec![target])));
|
||||
|
@ -137,7 +137,7 @@ fn follow(name: String, conn: DbConn, user: User, worker: Worker) -> Redirect {
|
|||
let act = f.into_activity(&*conn);
|
||||
worker.execute(Thunk::of(move || broadcast(&user, act, vec![target])));
|
||||
}
|
||||
Redirect::to(uri!(details: name = name))
|
||||
Some(Redirect::to(uri!(details: name = name)))
|
||||
}
|
||||
|
||||
#[post("/@/<name>/follow", rank = 2)]
|
||||
|
@ -176,9 +176,9 @@ fn followers(name: String, conn: DbConn, account: Option<User>) -> Template {
|
|||
|
||||
|
||||
#[get("/@/<name>", rank = 1)]
|
||||
fn activity_details(name: String, conn: DbConn, _ap: ApRequest) -> ActivityStream<CustomPerson> {
|
||||
let user = User::find_local(&*conn, name).unwrap();
|
||||
ActivityStream::new(user.into_activity(&*conn))
|
||||
fn activity_details(name: String, conn: DbConn, _ap: ApRequest) -> Option<ActivityStream<CustomPerson>> {
|
||||
let user = User::find_local(&*conn, name)?;
|
||||
Some(ActivityStream::new(user.into_activity(&*conn)))
|
||||
}
|
||||
|
||||
#[get("/users/new")]
|
||||
|
@ -228,17 +228,16 @@ fn update(_name: String, conn: DbConn, user: User, data: LenientForm<UpdateUserF
|
|||
}
|
||||
|
||||
#[post("/@/<name>/delete")]
|
||||
fn delete(name: String, conn: DbConn, user: User, mut cookies: Cookies) -> Redirect {
|
||||
let account = User::find_by_fqn(&*conn, name.clone()).unwrap();
|
||||
fn delete(name: String, conn: DbConn, user: User, mut cookies: Cookies) -> Option<Redirect> {
|
||||
let account = User::find_by_fqn(&*conn, name.clone())?;
|
||||
if user.id == account.id {
|
||||
account.delete(&*conn);
|
||||
|
||||
let cookie = cookies.get_private(AUTH_COOKIE).unwrap();
|
||||
cookies.remove_private(cookie);
|
||||
cookies.get_private(AUTH_COOKIE).map(|cookie| cookies.remove_private(cookie));
|
||||
|
||||
Redirect::to(uri!(super::instance::index))
|
||||
Some(Redirect::to(uri!(super::instance::index)))
|
||||
} else {
|
||||
Redirect::to(uri!(edit: name = name))
|
||||
Some(Redirect::to(uri!(edit: name = name)))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -291,54 +290,54 @@ fn create(conn: DbConn, data: LenientForm<NewUserForm>) -> Result<Redirect, Temp
|
|||
}
|
||||
|
||||
#[get("/@/<name>/outbox")]
|
||||
fn outbox(name: String, conn: DbConn) -> ActivityStream<OrderedCollection> {
|
||||
let user = User::find_local(&*conn, name).unwrap();
|
||||
user.outbox(&*conn)
|
||||
fn outbox(name: String, conn: DbConn) -> Option<ActivityStream<OrderedCollection>> {
|
||||
let user = User::find_local(&*conn, name)?;
|
||||
Some(user.outbox(&*conn))
|
||||
}
|
||||
|
||||
#[post("/@/<name>/inbox", data = "<data>")]
|
||||
fn inbox(name: String, conn: DbConn, data: String, headers: Headers) -> String {
|
||||
let user = User::find_local(&*conn, name).unwrap();
|
||||
let act: serde_json::Value = serde_json::from_str(&data[..]).unwrap();
|
||||
fn inbox(name: String, conn: DbConn, data: String, headers: Headers) -> Result<String, Option<status::BadRequest<&'static str>>> {
|
||||
let user = User::find_local(&*conn, name).ok_or(None)?;
|
||||
let act: serde_json::Value = serde_json::from_str(&data[..]).expect("user::inbox: deserialization error");
|
||||
|
||||
let activity = act.clone();
|
||||
let actor_id = activity["actor"].as_str()
|
||||
.unwrap_or_else(|| activity["actor"]["id"].as_str().expect("User: No actor ID for incoming activity, blocks by panicking"));
|
||||
.or_else(|| activity["actor"]["id"].as_str()).ok_or(Some(status::BadRequest(Some("Missing actor id for activity"))))?;
|
||||
|
||||
let actor = User::from_url(&conn, actor_id.to_owned()).unwrap();
|
||||
let actor = User::from_url(&conn, actor_id.to_owned()).expect("user::inbox: user error");
|
||||
if !verify_http_headers(&actor, headers.0.clone(), data).is_secure() &&
|
||||
!act.clone().verify(&actor) {
|
||||
println!("Rejected invalid activity supposedly from {}, with headers {:?}", actor.username, headers.0);
|
||||
return "invalid signature".to_owned();
|
||||
return Err(Some(status::BadRequest(Some("Invalid signature"))));
|
||||
}
|
||||
|
||||
if Instance::is_blocked(&*conn, actor_id.to_string()) {
|
||||
return String::new();
|
||||
return Ok(String::new());
|
||||
}
|
||||
match user.received(&*conn, act) {
|
||||
Ok(match user.received(&*conn, act) {
|
||||
Ok(_) => String::new(),
|
||||
Err(e) => {
|
||||
println!("User inbox error: {}\n{}", e.as_fail(), e.backtrace());
|
||||
format!("Error: {}", e.as_fail())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[get("/@/<name>/followers")]
|
||||
fn ap_followers(name: String, conn: DbConn, _ap: ApRequest) -> ActivityStream<OrderedCollection> {
|
||||
let user = User::find_local(&*conn, name).unwrap();
|
||||
fn ap_followers(name: String, conn: DbConn, _ap: ApRequest) -> Option<ActivityStream<OrderedCollection>> {
|
||||
let user = User::find_local(&*conn, name)?;
|
||||
let followers = user.get_followers(&*conn).into_iter().map(|f| Id::new(f.ap_url)).collect::<Vec<Id>>();
|
||||
|
||||
let mut coll = OrderedCollection::default();
|
||||
coll.object_props.set_id_string(user.followers_endpoint).expect("Follower collection: id error");
|
||||
coll.collection_props.set_total_items_u64(followers.len() as u64).expect("Follower collection: totalItems error");
|
||||
coll.collection_props.set_items_link_vec(followers).expect("Follower collection: items error");
|
||||
ActivityStream::new(coll)
|
||||
coll.object_props.set_id_string(user.followers_endpoint).expect("user::ap_followers: id error");
|
||||
coll.collection_props.set_total_items_u64(followers.len() as u64).expect("user::ap_followers: totalItems error");
|
||||
coll.collection_props.set_items_link_vec(followers).expect("user::ap_followers items error");
|
||||
Some(ActivityStream::new(coll))
|
||||
}
|
||||
|
||||
#[get("/@/<name>/atom.xml")]
|
||||
fn atom_feed(name: String, conn: DbConn) -> Content<String> {
|
||||
let author = User::find_by_fqn(&*conn, name.clone()).expect("Unable to find author");
|
||||
fn atom_feed(name: String, conn: DbConn) -> Option<Content<String>> {
|
||||
let author = User::find_by_fqn(&*conn, name.clone())?;
|
||||
let feed = FeedBuilder::default()
|
||||
.title(author.display_name.clone())
|
||||
.id(Instance::get_local(&*conn).unwrap().compute_box("~", name, "atom.xml"))
|
||||
|
@ -347,6 +346,6 @@ fn atom_feed(name: String, conn: DbConn) -> Content<String> {
|
|||
.map(|p| super::post_to_atom(p, &*conn))
|
||||
.collect::<Vec<Entry>>())
|
||||
.build()
|
||||
.expect("Error building Atom feed");
|
||||
Content(ContentType::new("application", "atom+xml"), feed.to_string())
|
||||
.expect("user::atom_feed: Error building Atom feed");
|
||||
Some(Content(ContentType::new("application", "atom+xml"), feed.to_string()))
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue