Merge pull request #281 from Plume-org/panic-refactor
Panic less and with better messages
This commit is contained in:
commit
879fde81ba
@ -27,7 +27,7 @@ fn main() {
|
|||||||
match matches.subcommand() {
|
match matches.subcommand() {
|
||||||
("instance", Some(args)) => instance::run(args, &conn.expect("Couldn't connect to the database.")),
|
("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.")),
|
("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 {
|
fn try_from_activity(conn: &C, act: Create) -> bool {
|
||||||
if let Ok(obj) = act.create_props.object_object() {
|
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
|
true
|
||||||
} else {
|
} else {
|
||||||
false
|
false
|
||||||
|
@ -82,14 +82,13 @@ impl<'a, 'r> FromRequest<'a, 'r> for ApRequest {
|
|||||||
"application/ld+json" => Outcome::Success(ApRequest),
|
"application/ld+json" => Outcome::Success(ApRequest),
|
||||||
"text/html" => Outcome::Forward(true),
|
"text/html" => Outcome::Forward(true),
|
||||||
_ => Outcome::Forward(false)
|
_ => 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
|
out
|
||||||
} else {
|
} else {
|
||||||
ct
|
ct
|
||||||
}).map_forward(|_| ())).unwrap_or(Outcome::Forward(()))
|
}).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>) {
|
pub fn broadcast<S: sign::Signer, A: Activity, T: inbox::WithInbox + Actor>(sender: &S, act: A, to: Vec<T>) {
|
||||||
let boxes = to.into_iter()
|
let boxes = to.into_iter()
|
||||||
.filter(|u| !u.is_local())
|
.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>>()
|
.collect::<Vec<String>>()
|
||||||
.unique();
|
.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();
|
act["@context"] = context();
|
||||||
let signed = act.sign(sender);
|
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())
|
.body(signed.to_string())
|
||||||
.send();
|
.send();
|
||||||
match res {
|
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)
|
Err(e) => println!("Error while sending to inbox ({:?})", e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -14,30 +14,30 @@ pub struct Digest(String);
|
|||||||
|
|
||||||
impl Digest {
|
impl Digest {
|
||||||
pub fn digest(body: String) -> HeaderValue {
|
pub fn digest(body: String) -> HeaderValue {
|
||||||
let mut hasher = Hasher::new(MessageDigest::sha256()).unwrap();
|
let mut hasher = Hasher::new(MessageDigest::sha256()).expect("Digest::digest: initialization error");
|
||||||
hasher.update(&body.into_bytes()[..]).unwrap();
|
hasher.update(&body.into_bytes()[..]).expect("Digest::digest: content insertion error");
|
||||||
let res = base64::encode(&hasher.finish().unwrap());
|
let res = base64::encode(&hasher.finish().expect("Digest::digest: finalizing error"));
|
||||||
HeaderValue::from_str(&format!("SHA-256={}", res)).unwrap()
|
HeaderValue::from_str(&format!("SHA-256={}", res)).expect("Digest::digest: header creation error")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn verify(&self, body: String) -> bool {
|
pub fn verify(&self, body: String) -> bool {
|
||||||
if self.algorithm()=="SHA-256" {
|
if self.algorithm()=="SHA-256" {
|
||||||
let mut hasher = Hasher::new(MessageDigest::sha256()).unwrap();
|
let mut hasher = Hasher::new(MessageDigest::sha256()).expect("Digest::digest: initialization error");
|
||||||
hasher.update(&body.into_bytes()).unwrap();
|
hasher.update(&body.into_bytes()).expect("Digest::digest: content insertion error");
|
||||||
self.value().deref()==hasher.finish().unwrap().deref()
|
self.value().deref()==hasher.finish().expect("Digest::digest: finalizing error").deref()
|
||||||
} else {
|
} else {
|
||||||
false //algorithm not supported
|
false //algorithm not supported
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn algorithm(&self) -> &str {
|
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]
|
&self.0[..pos]
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn value(&self) -> Vec<u8> {
|
pub fn value(&self) -> Vec<u8> {
|
||||||
let pos = self.0.find('=').unwrap()+1;
|
let pos = self.0.find('=').expect("Digest::value: invalid header error")+1;
|
||||||
base64::decode(&self.0[pos..]).unwrap()
|
base64::decode(&self.0[pos..]).expect("Digest::value: invalid encoding error")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_header(dig: &str) -> Result<Self, ()> {
|
pub fn from_header(dig: &str) -> Result<Self, ()> {
|
||||||
@ -60,13 +60,13 @@ pub fn headers() -> HeaderMap {
|
|||||||
|
|
||||||
let mut headers = HeaderMap::new();
|
let mut headers = HeaderMap::new();
|
||||||
headers.insert(USER_AGENT, HeaderValue::from_static(PLUME_USER_AGENT));
|
headers.insert(USER_AGENT, HeaderValue::from_static(PLUME_USER_AGENT));
|
||||||
headers.insert(DATE, HeaderValue::from_str(&date).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(", ")).unwrap());
|
headers.insert(ACCEPT, HeaderValue::from_str(&ap_accept_header().into_iter().collect::<Vec<_>>().join(", ")).expect("request::headers: accept error"));
|
||||||
headers
|
headers
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn signature<S: Signer>(signer: &S, headers: HeaderMap) -> HeaderValue {
|
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 signed_headers = headers.iter().map(|(h,_)| h.as_str()).collect::<Vec<&str>>().join(" ").to_lowercase();
|
||||||
|
|
||||||
let data = signer.sign(signed_string);
|
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(),
|
key_id = signer.get_key_id(),
|
||||||
signed_headers = signed_headers,
|
signed_headers = signed_headers,
|
||||||
signature = sign
|
signature = sign
|
||||||
)).unwrap()
|
)).expect("request::signature: signature header error")
|
||||||
}
|
}
|
||||||
|
@ -12,9 +12,12 @@ use serde_json;
|
|||||||
|
|
||||||
/// Returns (public key, private key)
|
/// Returns (public key, private key)
|
||||||
pub fn gen_keypair() -> (Vec<u8>, Vec<u8>) {
|
pub fn gen_keypair() -> (Vec<u8>, Vec<u8>) {
|
||||||
let keypair = Rsa::generate(2048).unwrap();
|
let keypair = Rsa::generate(2048).expect("sign::gen_keypair: key generation error");
|
||||||
let keypair = PKey::from_rsa(keypair).unwrap();
|
let keypair = PKey::from_rsa(keypair).expect("sign::gen_keypair: parsing error");
|
||||||
(keypair.public_key_to_pem().unwrap(), keypair.private_key_to_pem_pkcs8().unwrap())
|
(
|
||||||
|
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 {
|
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() {
|
if sig_header.is_none() {
|
||||||
return SignatureValidity::Absent
|
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 _key_id = None;
|
||||||
let mut _algorithm = 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
|
if signature.is_none() || headers.is_none() {//missing part of the header
|
||||||
return SignatureValidity::Invalid
|
return SignatureValidity::Invalid
|
||||||
}
|
}
|
||||||
let headers = headers.unwrap().split_whitespace().collect::<Vec<_>>();
|
let headers = headers.expect("sign::verify_http_headers: unreachable").split_whitespace().collect::<Vec<_>>();
|
||||||
let signature = signature.unwrap();
|
let signature = signature.expect("sign::verify_http_headers: unreachable");
|
||||||
let h = headers.iter()
|
let h = headers.iter()
|
||||||
.map(|header| (header,all_headers.get_one(header)))
|
.map(|header| (header,all_headers.get_one(header)))
|
||||||
.map(|(header, value)| format!("{}: {}", header.to_lowercase(), value.unwrap_or("")))
|
.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);
|
find_by!(blogs, find_by_name, actor_id as String, instance_id as i32);
|
||||||
|
|
||||||
pub fn get_instance(&self, conn: &Connection) -> Instance {
|
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> {
|
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);
|
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))
|
users::table.filter(users::id.eq_any(authors_ids))
|
||||||
.load::<User>(conn)
|
.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> {
|
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);
|
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))
|
blogs::table.filter(blogs::id.eq_any(author_ids))
|
||||||
.load::<Blog>(conn)
|
.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> {
|
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> {
|
pub fn find_by_fqn(conn: &Connection, fqn: String) -> Option<Blog> {
|
||||||
if fqn.contains("@") { // remote 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) => {
|
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),
|
Some(u) => Some(u),
|
||||||
None => Blog::fetch_from_webfinger(conn, fqn)
|
None => Blog::fetch_from_webfinger(conn, fqn)
|
||||||
}
|
}
|
||||||
@ -107,7 +107,7 @@ impl Blog {
|
|||||||
|
|
||||||
fn fetch_from_webfinger(conn: &Connection, acct: String) -> Option<Blog> {
|
fn fetch_from_webfinger(conn: &Connection, acct: String) -> Option<Blog> {
|
||||||
match resolve(acct.clone(), *USE_HTTPS) {
|
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) => {
|
Err(details) => {
|
||||||
println!("{:?}", details);
|
println!("{:?}", details);
|
||||||
None
|
None
|
||||||
@ -118,15 +118,15 @@ impl Blog {
|
|||||||
fn fetch_from_url(conn: &Connection, url: String) -> Option<Blog> {
|
fn fetch_from_url(conn: &Connection, url: String) -> Option<Blog> {
|
||||||
let req = Client::new()
|
let req = Client::new()
|
||||||
.get(&url[..])
|
.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();
|
.send();
|
||||||
match req {
|
match req {
|
||||||
Ok(mut res) => {
|
Ok(mut res) => {
|
||||||
let text = &res.text().unwrap();
|
let text = &res.text().expect("Blog::fetch_from_url: body reading error");
|
||||||
let ap_sign: ApSignature = serde_json::from_str(text).unwrap();
|
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).unwrap();
|
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
|
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
|
Err(_) => None
|
||||||
}
|
}
|
||||||
@ -188,26 +188,26 @@ impl Blog {
|
|||||||
if self.outbox_url.len() == 0 {
|
if self.outbox_url.len() == 0 {
|
||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(blogs::outbox_url.eq(instance.compute_box(BLOG_PREFIX, self.actor_id.clone(), "outbox")))
|
.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 {
|
if self.inbox_url.len() == 0 {
|
||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(blogs::inbox_url.eq(instance.compute_box(BLOG_PREFIX, self.actor_id.clone(), "inbox")))
|
.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 {
|
if self.ap_url.len() == 0 {
|
||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(blogs::ap_url.eq(instance.compute_box(BLOG_PREFIX, self.actor_id.clone(), "")))
|
.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> {
|
pub fn outbox(&self, conn: &Connection) -> ActivityStream<OrderedCollection> {
|
||||||
let mut coll = OrderedCollection::default();
|
let mut coll = OrderedCollection::default();
|
||||||
coll.collection_props.items = serde_json::to_value(self.get_activities(conn)).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).unwrap();
|
coll.collection_props.set_total_items_u64(self.get_activities(conn).len() as u64).expect("Blog::outbox: count serialization error");
|
||||||
ActivityStream::new(coll)
|
ActivityStream::new(coll)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -216,7 +216,9 @@ impl Blog {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_keypair(&self) -> PKey<Private> {
|
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 {
|
pub fn webfinger(&self, conn: &Connection) -> Webfinger {
|
||||||
@ -248,9 +250,9 @@ impl Blog {
|
|||||||
|
|
||||||
pub fn from_url(conn: &Connection, url: String) -> Option<Blog> {
|
pub fn from_url(conn: &Connection, url: String) -> Option<Blog> {
|
||||||
Blog::find_by_ap_url(conn, url.clone()).or_else(|| {
|
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
|
// 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)
|
Blog::fetch_from_url(conn, url)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
@ -267,7 +269,7 @@ impl Blog {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn to_json(&self, conn: &Connection) -> serde_json::Value {
|
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["fqn"] = json!(self.get_fqn(conn));
|
||||||
json
|
json
|
||||||
}
|
}
|
||||||
@ -303,16 +305,17 @@ impl sign::Signer for Blog {
|
|||||||
|
|
||||||
fn sign(&self, to_sign: String) -> Vec<u8> {
|
fn sign(&self, to_sign: String) -> Vec<u8> {
|
||||||
let key = self.get_keypair();
|
let key = self.get_keypair();
|
||||||
let mut signer = Signer::new(MessageDigest::sha256(), &key).unwrap();
|
let mut signer = Signer::new(MessageDigest::sha256(), &key).expect("Blog::sign: initialization error");
|
||||||
signer.update(to_sign.as_bytes()).unwrap();
|
signer.update(to_sign.as_bytes()).expect("Blog::sign: content insertion error");
|
||||||
signer.sign_to_vec().unwrap()
|
signer.sign_to_vec().expect("Blog::sign: finalization error")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn verify(&self, data: String, signature: Vec<u8>) -> bool {
|
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 key = PKey::from_rsa(Rsa::public_key_from_pem(self.public_key.as_ref()).expect("Blog::verify: pem parsing error"))
|
||||||
let mut verifier = Verifier::new(MessageDigest::sha256(), &key).unwrap();
|
.expect("Blog::verify: deserialization error");
|
||||||
verifier.update(data.as_bytes()).unwrap();
|
let mut verifier = Verifier::new(MessageDigest::sha256(), &key).expect("Blog::verify: initialization error");
|
||||||
verifier.verify(&signature).unwrap()
|
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(""),
|
inbox_url: String::from(""),
|
||||||
instance_id: instance_id,
|
instance_id: instance_id,
|
||||||
ap_url: String::from(""),
|
ap_url: String::from(""),
|
||||||
public_key: String::from_utf8(pub_key).unwrap(),
|
public_key: String::from_utf8(pub_key).expect("NewBlog::new_local: public key error"),
|
||||||
private_key: Some(String::from_utf8(priv_key).unwrap())
|
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);
|
find_by!(comments, find_by_ap_url, ap_url as String);
|
||||||
|
|
||||||
pub fn get_author(&self, conn: &Connection) -> User {
|
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 {
|
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 {
|
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);
|
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))
|
comments::table.filter(comments::author_id.eq_any(local_authors))
|
||||||
.load::<Comment>(conn)
|
.load::<Comment>(conn)
|
||||||
.expect("Couldn't load local comments")
|
.expect("Comment::count_local: loading error")
|
||||||
.len()
|
.len()// TODO count in database?
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn to_json(&self, conn: &Connection, others: &Vec<Comment>) -> serde_json::Value {
|
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);
|
json["author"] = self.get_author(conn).to_json(conn);
|
||||||
let mentions = Mention::list_for_comment(conn, self.id).into_iter()
|
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()))
|
.map(|m| m.get_mentioned(conn).map(|u| u.get_fqn(conn)).unwrap_or(String::new()))
|
||||||
.collect::<Vec<String>>();
|
.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()
|
json["responses"] = json!(others.into_iter()
|
||||||
.filter(|c| c.in_response_to_id.map(|id| id == self.id).unwrap_or(false))
|
.filter(|c| c.in_response_to_id.map(|id| id == self.id).unwrap_or(false))
|
||||||
.map(|c| c.to_json(conn, others))
|
.map(|c| c.to_json(conn, others))
|
||||||
@ -88,8 +88,8 @@ impl Comment {
|
|||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(comments::ap_url.eq(self.compute_id(conn)))
|
.set(comments::ap_url.eq(self.compute_id(conn)))
|
||||||
.execute(conn)
|
.execute(conn)
|
||||||
.expect("Failed to update comment AP URL");
|
.expect("Comment::update_ap_url: update error");
|
||||||
Comment::get(conn, self.id).expect("Couldn't get the updated comment")
|
Comment::get(conn, self.id).expect("Comment::update_ap_url: get error")
|
||||||
} else {
|
} else {
|
||||||
self.clone()
|
self.clone()
|
||||||
}
|
}
|
||||||
@ -102,53 +102,53 @@ impl Comment {
|
|||||||
pub fn into_activity(&self, conn: &Connection) -> Note {
|
pub fn into_activity(&self, conn: &Connection) -> Note {
|
||||||
let (html, mentions) = utils::md_to_html(self.content.get().as_ref());
|
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 mut note = Note::default();
|
||||||
let to = vec![Id::new(PUBLIC_VISIBILTY.to_string())];
|
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_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("NewComment::create: note.summary 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("NewComment::create: note.content 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).unwrap().ap_url, |id| {
|
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).unwrap();
|
let comm = Comment::get(conn, id).expect("Comment::into_activity: comment error");
|
||||||
comm.ap_url.clone().unwrap_or(comm.compute_id(conn))
|
comm.ap_url.clone().unwrap_or(comm.compute_id(conn))
|
||||||
}))).expect("NewComment::create: note.in_reply_to error");
|
}))).expect("Comment::into_activity: 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_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("NewComment::create: note.attributed_to 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("NewComment::create: note.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>>())
|
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
|
note
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_activity(&self, conn: &Connection) -> Create {
|
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 note = self.into_activity(conn);
|
||||||
let mut act = Create::default();
|
let mut act = Create::default();
|
||||||
act.create_props.set_actor_link(author.into_id()).expect("NewComment::create_acitivity: actor 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("NewComment::create_acitivity: object 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().unwrap())).expect("NewComment::create_acitivity: id 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("WTF")).expect("NewComment::create_acitivity: to 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("NewComment::create_acitivity: cc error");
|
act.object_props.set_cc_link_vec::<Id>(vec![]).expect("Comment::create_activity: cc error");
|
||||||
act
|
act
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FromActivity<Note, Connection> for Comment {
|
impl FromActivity<Note, Connection> for Comment {
|
||||||
fn from_activity(conn: &Connection, note: Note, actor: Id) -> 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 previous_comment = Comment::find_by_ap_url(conn, previous_url.clone());
|
||||||
|
|
||||||
let comm = Comment::insert(conn, NewComment {
|
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("")),
|
spoiler_text: note.object_props.summary_string().unwrap_or(String::from("")),
|
||||||
ap_url: note.object_props.id_string().ok(),
|
ap_url: note.object_props.id_string().ok(),
|
||||||
in_response_to_id: previous_comment.clone().map(|c| c.id),
|
in_response_to_id: previous_comment.clone().map(|c| c.id),
|
||||||
post_id: previous_comment
|
post_id: previous_comment
|
||||||
.map(|c| c.post_id)
|
.map(|c| c.post_id)
|
||||||
.unwrap_or_else(|| Post::find_by_ap_url(conn, previous_url).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()).unwrap().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
|
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() {
|
for tag in tags.into_iter() {
|
||||||
serde_json::from_value::<link::Mention>(tag)
|
serde_json::from_value::<link::Mention>(tag)
|
||||||
.map(|m| {
|
.map(|m| {
|
||||||
let author = &Post::get(conn, comm.post_id).unwrap().get_authors(conn)[0];
|
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 mention: no href") != author.ap_url.clone();
|
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)
|
Mention::from_activity(conn, m, comm.id, false, not_author)
|
||||||
}).ok();
|
}).ok();
|
||||||
}
|
}
|
||||||
|
@ -38,15 +38,15 @@ impl Follow {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn into_activity(&self, conn: &Connection) -> FollowAct {
|
pub fn into_activity(&self, conn: &Connection) -> FollowAct {
|
||||||
let user = User::get(conn, self.follower_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).unwrap();
|
let target = User::get(conn, self.following_id).expect("Follow::into_activity: target not found error");
|
||||||
|
|
||||||
let mut act = FollowAct::default();
|
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_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.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()).unwrap();
|
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("New Follow error while setting 'to'");
|
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("New Follow error while setting 'cc'");
|
act.object_props.set_cc_link_vec::<Id>(vec![]).expect("Follow::into_activity: cc error");
|
||||||
act
|
act
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -70,11 +70,11 @@ impl Follow {
|
|||||||
|
|
||||||
let mut accept = Accept::default();
|
let mut accept = Accept::default();
|
||||||
let accept_id = format!("{}#accept", follow.object_props.id_string().unwrap_or(String::new()));
|
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_id_string(accept_id).expect("Follow::accept_follow: id error");
|
||||||
accept.object_props.set_to_link(from.clone().into_id()).expect("accept_follow: to 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("accept_follow: cc 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()).unwrap();
|
accept.accept_props.set_actor_link::<Id>(target.clone().into_id()).expect("Follow::accept_follow: actor error");
|
||||||
accept.accept_props.set_object_object(follow).unwrap();
|
accept.accept_props.set_object_object(follow).expect("Follow::accept_follow: object error");
|
||||||
broadcast(&*target, accept, vec![from.clone()]);
|
broadcast(&*target, accept, vec![from.clone()]);
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
@ -83,12 +83,13 @@ impl Follow {
|
|||||||
impl FromActivity<FollowAct, Connection> for Follow {
|
impl FromActivity<FollowAct, Connection> for Follow {
|
||||||
fn from_activity(conn: &Connection, follow: FollowAct, _actor: Id) -> Follow {
|
fn from_activity(conn: &Connection, follow: FollowAct, _actor: Id) -> Follow {
|
||||||
let from_id = follow.follow_props.actor_link::<Id>().map(|l| l.into())
|
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"));
|
.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).unwrap();
|
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().unwrap().to_string()) {
|
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),
|
Some(user) => Follow::accept_follow(conn, &from, &user, follow, from.id, user.id),
|
||||||
None => {
|
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)
|
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 {
|
impl Deletable<Connection, Undo> for Follow {
|
||||||
fn delete(&self, conn: &Connection) -> Undo {
|
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
|
// delete associated notification if any
|
||||||
if let Some(notif) = Notification::find(conn, notification_kind::FOLLOW, self.id) {
|
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();
|
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.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.undo_props.set_object_object(self.into_activity(conn)).expect("Follow::delete: object error");
|
||||||
undo
|
undo
|
||||||
|
@ -44,14 +44,14 @@ impl Instance {
|
|||||||
instances::table.filter(instances::local.eq(true))
|
instances::table.filter(instances::local.eq(true))
|
||||||
.limit(1)
|
.limit(1)
|
||||||
.load::<Instance>(conn)
|
.load::<Instance>(conn)
|
||||||
.expect("Error loading local instance infos")
|
.expect("Instance::get_local: loading error")
|
||||||
.into_iter().nth(0)
|
.into_iter().nth(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_remotes(conn: &Connection) -> Vec<Instance> {
|
pub fn get_remotes(conn: &Connection) -> Vec<Instance> {
|
||||||
instances::table.filter(instances::local.eq(false))
|
instances::table.filter(instances::local.eq(false))
|
||||||
.load::<Instance>(conn)
|
.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> {
|
pub fn page(conn: &Connection, (min, max): (i32, i32)) -> Vec<Instance> {
|
||||||
@ -59,11 +59,11 @@ impl Instance {
|
|||||||
.offset(min.into())
|
.offset(min.into())
|
||||||
.limit((max - min).into())
|
.limit((max - min).into())
|
||||||
.load::<Instance>(conn)
|
.load::<Instance>(conn)
|
||||||
.expect("Error loading a page of instances")
|
.expect("Instance::page: loading error")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn local_id(conn: &Connection) -> i32 {
|
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);
|
insert!(instances, NewInstance);
|
||||||
@ -74,14 +74,14 @@ impl Instance {
|
|||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(instances::blocked.eq(!self.blocked))
|
.set(instances::blocked.eq(!self.blocked))
|
||||||
.execute(conn)
|
.execute(conn)
|
||||||
.expect("Couldn't block/unblock instance");
|
.expect("Instance::toggle_block: update error");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// id: AP object id
|
/// id: AP object id
|
||||||
pub fn is_blocked(conn: &Connection, id: String) -> bool {
|
pub fn is_blocked(conn: &Connection, id: String) -> bool {
|
||||||
for block in instances::table.filter(instances::blocked.eq(true))
|
for block in instances::table.filter(instances::blocked.eq(true))
|
||||||
.get_results::<Instance>(conn)
|
.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()) {
|
if id.starts_with(format!("https://{}", block.public_domain).as_str()) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@ -94,7 +94,7 @@ impl Instance {
|
|||||||
users::table.filter(users::instance_id.eq(self.id))
|
users::table.filter(users::instance_id.eq(self.id))
|
||||||
.filter(users::is_admin.eq(true))
|
.filter(users::is_admin.eq(true))
|
||||||
.load::<User>(conn)
|
.load::<User>(conn)
|
||||||
.expect("Couldn't load admins")
|
.expect("Instance::has_admin: loading error")
|
||||||
.len() > 0
|
.len() > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -103,7 +103,7 @@ impl Instance {
|
|||||||
.filter(users::is_admin.eq(true))
|
.filter(users::is_admin.eq(true))
|
||||||
.limit(1)
|
.limit(1)
|
||||||
.get_result::<User>(conn)
|
.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 {
|
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::short_description_html.eq(sd),
|
||||||
instances::long_description_html.eq(ld)
|
instances::long_description_html.eq(ld)
|
||||||
)).execute(conn)
|
)).execute(conn)
|
||||||
.expect("Couldn't update instance");
|
.expect("Instance::update: update error");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn count(conn: &Connection) -> i64 {
|
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)))+
|
$(.filter($table::$col.eq($col)))+
|
||||||
.limit(1)
|
.limit(1)
|
||||||
.load::<Self>(conn)
|
.load::<Self>(conn)
|
||||||
.expect("Error loading $table by $col")
|
.expect("macro::find_by: Error loading $table by $col")
|
||||||
.into_iter().nth(0)
|
.into_iter().nth(0)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -78,7 +78,7 @@ macro_rules! list_by {
|
|||||||
$table::table
|
$table::table
|
||||||
$(.filter($table::$col.eq($col)))+
|
$(.filter($table::$col.eq($col)))+
|
||||||
.load::<Self>(conn)
|
.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))
|
$table::table.filter($table::id.eq(id))
|
||||||
.limit(1)
|
.limit(1)
|
||||||
.load::<Self>(conn)
|
.load::<Self>(conn)
|
||||||
.expect("Error loading $table by id")
|
.expect("macro::get: Error loading $table by id")
|
||||||
.into_iter().nth(0)
|
.into_iter().nth(0)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -127,7 +127,7 @@ macro_rules! insert {
|
|||||||
diesel::insert_into($table::table)
|
diesel::insert_into($table::table)
|
||||||
.values(new)
|
.values(new)
|
||||||
.execute(conn)
|
.execute(conn)
|
||||||
.expect("Error saving new $table");
|
.expect("macro::insert: Error saving new $table");
|
||||||
Self::last(conn)
|
Self::last(conn)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -154,9 +154,9 @@ macro_rules! update {
|
|||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(self)
|
.set(self)
|
||||||
.execute(conn)
|
.execute(conn)
|
||||||
.expect(concat!("Error updating ", stringify!($table)));
|
.expect(concat!("macro::update: Error updating ", stringify!($table)));
|
||||||
Self::get(conn, self.id)
|
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())
|
$table::table.order_by($table::id.desc())
|
||||||
.limit(1)
|
.limit(1)
|
||||||
.load::<Self>(conn)
|
.load::<Self>(conn)
|
||||||
.expect(concat!("Error getting last ", stringify!($table)))
|
.expect(concat!("macro::last: Error getting last ", stringify!($table)))
|
||||||
.iter().next()
|
.iter().next()
|
||||||
.expect(concat!("No last ", stringify!($table)))
|
.expect(concat!("macro::last: No last ", stringify!($table)))
|
||||||
.clone()
|
.clone()
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -42,17 +42,17 @@ impl Like {
|
|||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(likes::ap_url.eq(format!(
|
.set(likes::ap_url.eq(format!(
|
||||||
"{}/like/{}",
|
"{}/like/{}",
|
||||||
User::get(conn, self.user_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).unwrap().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 {
|
pub fn into_activity(&self, conn: &Connection) -> activity::Like {
|
||||||
let mut act = activity::Like::default();
|
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_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).unwrap().into_id()).expect("Like::into_activity: object 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_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_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");
|
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 {
|
impl FromActivity<activity::Like, Connection> for Like {
|
||||||
fn from_activity(conn: &Connection, like: activity::Like, _actor: Id) -> 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 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().unwrap().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 {
|
let res = Like::insert(conn, NewLike {
|
||||||
post_id: post.unwrap().id,
|
post_id: post.expect("Like::from_activity: post error").id,
|
||||||
user_id: liker.unwrap().id,
|
user_id: liker.expect("Like::from_activity: user error").id,
|
||||||
ap_url: like.object_props.id_string().unwrap_or(String::from(""))
|
ap_url: like.object_props.id_string().unwrap_or(String::from(""))
|
||||||
});
|
});
|
||||||
res.notify(conn);
|
res.notify(conn);
|
||||||
@ -77,7 +77,7 @@ impl FromActivity<activity::Like, Connection> for Like {
|
|||||||
|
|
||||||
impl Notify<Connection> for Like {
|
impl Notify<Connection> for Like {
|
||||||
fn notify(&self, conn: &Connection) {
|
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) {
|
for author in post.get_authors(conn) {
|
||||||
Notification::insert(conn, NewNotification {
|
Notification::insert(conn, NewNotification {
|
||||||
kind: notification_kind::LIKE.to_string(),
|
kind: notification_kind::LIKE.to_string(),
|
||||||
@ -90,15 +90,15 @@ impl Notify<Connection> for Like {
|
|||||||
|
|
||||||
impl Deletable<Connection, activity::Undo> for Like {
|
impl Deletable<Connection, activity::Undo> for Like {
|
||||||
fn delete(&self, conn: &Connection) -> activity::Undo {
|
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
|
// delete associated notification if any
|
||||||
if let Some(notif) = Notification::find(conn, notification_kind::LIKE, self.id) {
|
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();
|
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.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_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");
|
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);
|
list_by!(medias, for_user, owner_id as i32);
|
||||||
|
|
||||||
pub fn to_json(&self, conn: &Connection) -> serde_json::Value {
|
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 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" => (
|
"png" | "jpg" | "jpeg" | "gif" | "svg" => (
|
||||||
format!("<img src=\"{}\" alt=\"{}\" title=\"{}\" class=\"preview\">", url, self.alt_text, self.alt_text),
|
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),
|
format!("<img src=\"{}\" alt=\"{}\" title=\"{}\">", url, self.alt_text, self.alt_text),
|
||||||
@ -67,13 +67,13 @@ impl Media {
|
|||||||
if self.is_remote {
|
if self.is_remote {
|
||||||
self.remote_url.clone().unwrap_or(String::new())
|
self.remote_url.clone().unwrap_or(String::new())
|
||||||
} else {
|
} 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) {
|
pub fn delete(&self, conn: &Connection) {
|
||||||
fs::remove_file(self.file_path.as_str()).expect("Couldn't delete media from disk");
|
fs::remove_file(self.file_path.as_str()).expect("Media::delete: file deletion error");
|
||||||
diesel::delete(self).execute(conn).expect("Couldn't remove media from DB");
|
diesel::delete(self).execute(conn).expect("Media::delete: database entry deletion error");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn save_remote(conn: &Connection, url: String) -> Media {
|
pub fn save_remote(conn: &Connection, url: String) -> Media {
|
||||||
@ -92,6 +92,6 @@ impl Media {
|
|||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(medias::owner_id.eq(id))
|
.set(medias::owner_id.eq(id))
|
||||||
.execute(conn)
|
.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 {
|
pub fn build_activity(conn: &Connection, ment: String) -> link::Mention {
|
||||||
let user = User::find_by_fqn(conn, ment.clone());
|
let user = User::find_by_fqn(conn, ment.clone());
|
||||||
let mut mention = link::Mention::default();
|
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_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("Error setting mention's name");
|
mention.link_props.set_name_string(format!("@{}", ment)).expect("Mention::build_activity: name error:");
|
||||||
mention
|
mention
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn to_activity(&self, conn: &Connection) -> link::Mention {
|
pub fn to_activity(&self, conn: &Connection) -> link::Mention {
|
||||||
let user = self.get_mentioned(conn);
|
let user = self.get_mentioned(conn);
|
||||||
let mut mention = link::Mention::default();
|
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_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("Error setting mention's name");
|
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
|
mention
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -45,7 +45,7 @@ impl Notification {
|
|||||||
notifications::table.filter(notifications::user_id.eq(user.id))
|
notifications::table.filter(notifications::user_id.eq(user.id))
|
||||||
.order_by(notifications::creation_date.desc())
|
.order_by(notifications::creation_date.desc())
|
||||||
.load::<Notification>(conn)
|
.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> {
|
pub fn page_for_user(conn: &Connection, user: &User, (min, max): (i32, i32)) -> Vec<Notification> {
|
||||||
@ -54,7 +54,7 @@ impl Notification {
|
|||||||
.offset(min.into())
|
.offset(min.into())
|
||||||
.limit((max - min).into())
|
.limit((max - min).into())
|
||||||
.load::<Notification>(conn)
|
.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> {
|
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)),
|
"user": mention.get_user(conn).map(|u| u.to_json(conn)),
|
||||||
"url": mention.get_post(conn).map(|p| p.to_json(conn)["url"].clone())
|
"url": mention.get_post(conn).map(|p| p.to_json(conn)["url"].clone())
|
||||||
.unwrap_or_else(|| {
|
.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);
|
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())
|
.offset(min.into())
|
||||||
.limit((max - min).into())
|
.limit((max - min).into())
|
||||||
.load(conn)
|
.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 {
|
pub fn count_for_tag(conn: &Connection, tag: String) -> i64 {
|
||||||
@ -132,8 +132,8 @@ impl Post {
|
|||||||
.filter(posts::published.eq(true))
|
.filter(posts::published.eq(true))
|
||||||
.count()
|
.count()
|
||||||
.load(conn)
|
.load(conn)
|
||||||
.expect("Error counting posts by tag")
|
.expect("Post::count_for_tag: counting error")
|
||||||
.iter().next().unwrap()
|
.iter().next().expect("Post::count_for_tag: no result error")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn count_local(conn: &Connection) -> usize {
|
pub fn count_local(conn: &Connection) -> usize {
|
||||||
@ -144,12 +144,15 @@ impl Post {
|
|||||||
posts::table.filter(posts::id.eq_any(local_posts_id))
|
posts::table.filter(posts::id.eq_any(local_posts_id))
|
||||||
.filter(posts::published.eq(true))
|
.filter(posts::published.eq(true))
|
||||||
.load::<Post>(conn)
|
.load::<Post>(conn)
|
||||||
.expect("Couldn't load local posts")
|
.expect("Post::count_local: loading error")
|
||||||
.len()
|
.len()// TODO count in database?
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn count(conn: &Connection) -> i64 {
|
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> {
|
pub fn get_recents(conn: &Connection, limit: i64) -> Vec<Post> {
|
||||||
@ -157,7 +160,7 @@ impl Post {
|
|||||||
.filter(posts::published.eq(true))
|
.filter(posts::published.eq(true))
|
||||||
.limit(limit)
|
.limit(limit)
|
||||||
.load::<Post>(conn)
|
.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> {
|
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())
|
.order(posts::creation_date.desc())
|
||||||
.limit(limit)
|
.limit(limit)
|
||||||
.load::<Post>(conn)
|
.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> {
|
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())
|
.order(posts::creation_date.desc())
|
||||||
.limit(limit)
|
.limit(limit)
|
||||||
.load::<Post>(conn)
|
.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> {
|
pub fn get_for_blog(conn: &Connection, blog:&Blog) -> Vec<Post> {
|
||||||
posts::table.filter(posts::blog_id.eq(blog.id))
|
posts::table.filter(posts::blog_id.eq(blog.id))
|
||||||
.filter(posts::published.eq(true))
|
.filter(posts::published.eq(true))
|
||||||
.load::<Post>(conn)
|
.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> {
|
pub fn blog_page(conn: &Connection, blog: &Blog, (min, max): (i32, i32)) -> Vec<Post> {
|
||||||
@ -195,7 +198,7 @@ impl Post {
|
|||||||
.offset(min.into())
|
.offset(min.into())
|
||||||
.limit((max - min).into())
|
.limit((max - min).into())
|
||||||
.load::<Post>(conn)
|
.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)
|
/// Give a page of all the recent posts known to this instance (= federated timeline)
|
||||||
@ -205,7 +208,7 @@ impl Post {
|
|||||||
.offset(min.into())
|
.offset(min.into())
|
||||||
.limit((max - min).into())
|
.limit((max - min).into())
|
||||||
.load::<Post>(conn)
|
.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
|
/// Give a page of posts from a specific instance
|
||||||
@ -220,7 +223,7 @@ impl Post {
|
|||||||
.offset(min.into())
|
.offset(min.into())
|
||||||
.limit((max - min).into())
|
.limit((max - min).into())
|
||||||
.load::<Post>(conn)
|
.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
|
/// Give a page of customized user feed, based on a list of followed users
|
||||||
@ -236,7 +239,7 @@ impl Post {
|
|||||||
.offset(min.into())
|
.offset(min.into())
|
||||||
.limit((max - min).into())
|
.limit((max - min).into())
|
||||||
.load::<Post>(conn)
|
.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> {
|
pub fn drafts_by_author(conn: &Connection, author: &User) -> Vec<Post> {
|
||||||
@ -247,14 +250,14 @@ impl Post {
|
|||||||
.filter(posts::published.eq(false))
|
.filter(posts::published.eq(false))
|
||||||
.filter(posts::id.eq_any(posts))
|
.filter(posts::id.eq_any(posts))
|
||||||
.load::<Post>(conn)
|
.load::<Post>(conn)
|
||||||
.expect("Error listing drafts")
|
.expect("Post::drafts_by_author: loading error")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_authors(&self, conn: &Connection) -> Vec<User> {
|
pub fn get_authors(&self, conn: &Connection) -> Vec<User> {
|
||||||
use schema::users;
|
use schema::users;
|
||||||
use schema::post_authors;
|
use schema::post_authors;
|
||||||
let author_list = PostAuthor::belonging_to(self).select(post_authors::author_id);
|
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 {
|
pub fn get_blog(&self, conn: &Connection) -> Blog {
|
||||||
@ -262,30 +265,30 @@ impl Post {
|
|||||||
blogs::table.filter(blogs::id.eq(self.blog_id))
|
blogs::table.filter(blogs::id.eq(self.blog_id))
|
||||||
.limit(1)
|
.limit(1)
|
||||||
.load::<Blog>(conn)
|
.load::<Blog>(conn)
|
||||||
.expect("Couldn't load blog associted to post")
|
.expect("Post::get_blog: loading error")
|
||||||
.into_iter().nth(0).unwrap()
|
.into_iter().nth(0).expect("Post::get_blog: no result error")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_likes(&self, conn: &Connection) -> Vec<Like> {
|
pub fn get_likes(&self, conn: &Connection) -> Vec<Like> {
|
||||||
use schema::likes;
|
use schema::likes;
|
||||||
likes::table.filter(likes::post_id.eq(self.id))
|
likes::table.filter(likes::post_id.eq(self.id))
|
||||||
.load::<Like>(conn)
|
.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> {
|
pub fn get_reshares(&self, conn: &Connection) -> Vec<Reshare> {
|
||||||
use schema::reshares;
|
use schema::reshares;
|
||||||
reshares::table.filter(reshares::post_id.eq(self.id))
|
reshares::table.filter(reshares::post_id.eq(self.id))
|
||||||
.load::<Reshare>(conn)
|
.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 {
|
pub fn update_ap_url(&self, conn: &Connection) -> Post {
|
||||||
if self.ap_url.len() == 0 {
|
if self.ap_url.len() == 0 {
|
||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(posts::ap_url.eq(self.compute_id(conn)))
|
.set(posts::ap_url.eq(self.compute_id(conn)))
|
||||||
.execute(conn).expect("Couldn't update AP URL");
|
.execute(conn).expect("Post::update_ap_url: update error");
|
||||||
Post::get(conn, self.id).unwrap()
|
Post::get(conn, self.id).expect("Post::update_ap_url: get error")
|
||||||
} else {
|
} else {
|
||||||
self.clone()
|
self.clone()
|
||||||
}
|
}
|
||||||
@ -359,7 +362,7 @@ impl Post {
|
|||||||
|
|
||||||
pub fn handle_update(conn: &Connection, updated: Article) {
|
pub fn handle_update(conn: &Connection, updated: Article) {
|
||||||
let id = updated.object_props.id_string().expect("Post::handle_update: id error");
|
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() {
|
if let Ok(title) = updated.object_props.name_string() {
|
||||||
post.slug = title.to_kebab_case();
|
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 title = article.object_props.name_string().expect("Post::from_activity: title error");
|
||||||
let post = Post::insert(conn, NewPost {
|
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(),
|
slug: title.to_kebab_case(),
|
||||||
title: title,
|
title: title,
|
||||||
content: SafeString::new(&article.object_props.content_string().expect("Post::from_activity: content error")),
|
content: SafeString::new(&article.object_props.content_string().expect("Post::from_activity: content error")),
|
||||||
|
@ -37,10 +37,10 @@ impl Reshare {
|
|||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(reshares::ap_url.eq(format!(
|
.set(reshares::ap_url.eq(format!(
|
||||||
"{}/reshare/{}",
|
"{}/reshare/{}",
|
||||||
User::get(conn, self.user_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).unwrap().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())
|
.order(reshares::creation_date.desc())
|
||||||
.limit(limit)
|
.limit(limit)
|
||||||
.load::<Reshare>(conn)
|
.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> {
|
pub fn get_post(&self, conn: &Connection) -> Option<Post> {
|
||||||
@ -62,9 +62,11 @@ impl Reshare {
|
|||||||
|
|
||||||
pub fn into_activity(&self, conn: &Connection) -> Announce {
|
pub fn into_activity(&self, conn: &Connection) -> Announce {
|
||||||
let mut act = Announce::default();
|
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_actor_link(User::get(conn, self.user_id).expect("Reshare::into_activity: user error").into_id())
|
||||||
act.announce_props.set_object_link(Post::get(conn, self.post_id).unwrap().into_id()).unwrap();
|
.expect("Reshare::into_activity: actor error");
|
||||||
act.object_props.set_id_string(self.ap_url.clone()).unwrap();
|
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_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");
|
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 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 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 {
|
let reshare = Reshare::insert(conn, NewReshare {
|
||||||
post_id: post.unwrap().id,
|
post_id: post.expect("Reshare::from_activity: post error").id,
|
||||||
user_id: user.unwrap().id,
|
user_id: user.expect("Reshare::from_activity: user error").id,
|
||||||
ap_url: announce.object_props.id_string().unwrap_or(String::from(""))
|
ap_url: announce.object_props.id_string().unwrap_or(String::from(""))
|
||||||
});
|
});
|
||||||
reshare.notify(conn);
|
reshare.notify(conn);
|
||||||
@ -88,7 +90,7 @@ impl FromActivity<Announce, Connection> for Reshare {
|
|||||||
|
|
||||||
impl Notify<Connection> for Reshare {
|
impl Notify<Connection> for Reshare {
|
||||||
fn notify(&self, conn: &Connection) {
|
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) {
|
for author in post.get_authors(conn) {
|
||||||
Notification::insert(conn, NewNotification {
|
Notification::insert(conn, NewNotification {
|
||||||
kind: notification_kind::RESHARE.to_string(),
|
kind: notification_kind::RESHARE.to_string(),
|
||||||
@ -101,16 +103,16 @@ impl Notify<Connection> for Reshare {
|
|||||||
|
|
||||||
impl Deletable<Connection, Undo> for Reshare {
|
impl Deletable<Connection, Undo> for Reshare {
|
||||||
fn delete(&self, conn: &Connection) -> Undo {
|
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
|
// delete associated notification if any
|
||||||
if let Some(notif) = Notification::find(conn, notification_kind::RESHARE, self.id) {
|
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();
|
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_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)).unwrap();
|
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_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_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");
|
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 {
|
pub fn into_activity(&self, conn: &Connection) -> Hashtag {
|
||||||
let mut ht = Hashtag::default();
|
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.set_name_string(self.tag.clone()).expect("Tag::into_activity: name error");
|
||||||
ht
|
ht
|
||||||
}
|
}
|
||||||
|
@ -102,7 +102,7 @@ impl User {
|
|||||||
pub fn one_by_instance(conn: &Connection) -> Vec<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()))
|
users::table.filter(users::instance_id.eq_any(users::table.select(users::instance_id).distinct()))
|
||||||
.load::<User>(conn)
|
.load::<User>(conn)
|
||||||
.expect("Error in User::on_by_instance")
|
.expect("User::one_by_instance: loading error")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn delete(&self, conn: &Connection) {
|
pub fn delete(&self, conn: &Connection) {
|
||||||
@ -113,31 +113,31 @@ impl User {
|
|||||||
.filter(post_authors::author_id.eq(self.id))
|
.filter(post_authors::author_id.eq(self.id))
|
||||||
.select(post_authors::post_id)
|
.select(post_authors::post_id)
|
||||||
.load(conn)
|
.load(conn)
|
||||||
.expect("Couldn't load posts IDs");
|
.expect("User::delete: post loading error");
|
||||||
for post_id in all_their_posts_ids {
|
for post_id in all_their_posts_ids {
|
||||||
let has_other_authors = post_authors::table
|
let has_other_authors = post_authors::table
|
||||||
.filter(post_authors::post_id.eq(post_id))
|
.filter(post_authors::post_id.eq(post_id))
|
||||||
.filter(post_authors::author_id.ne(self.id))
|
.filter(post_authors::author_id.ne(self.id))
|
||||||
.count()
|
.count()
|
||||||
.load(conn)
|
.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 {
|
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 {
|
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) {
|
pub fn grant_admin_rights(&self, conn: &Connection) {
|
||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(users::is_admin.eq(true))
|
.set(users::is_admin.eq(true))
|
||||||
.execute(conn)
|
.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 {
|
pub fn update(&self, conn: &Connection, name: String, email: String, summary: String) -> User {
|
||||||
@ -147,15 +147,15 @@ impl User {
|
|||||||
users::email.eq(email),
|
users::email.eq(email),
|
||||||
users::summary.eq(summary),
|
users::summary.eq(summary),
|
||||||
)).execute(conn)
|
)).execute(conn)
|
||||||
.expect("Couldn't update user");
|
.expect("User::update: update error");
|
||||||
User::get(conn, self.id).unwrap()
|
User::get(conn, self.id).expect("User::update: get error")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn count_local(conn: &Connection) -> usize {
|
pub fn count_local(conn: &Connection) -> usize {
|
||||||
users::table.filter(users::instance_id.eq(Instance::local_id(conn)))
|
users::table.filter(users::instance_id.eq(Instance::local_id(conn)))
|
||||||
.load::<User>(conn)
|
.load::<User>(conn)
|
||||||
.expect("Couldn't load local users")
|
.expect("User::count_local: loading error")
|
||||||
.len()
|
.len()// TODO count in database?
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn find_local(conn: &Connection, username: String) -> Option<User> {
|
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> {
|
pub fn find_by_fqn(conn: &Connection, fqn: String) -> Option<User> {
|
||||||
if fqn.contains("@") { // remote 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) => {
|
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),
|
Some(u) => Some(u),
|
||||||
None => User::fetch_from_webfinger(conn, fqn)
|
None => User::fetch_from_webfinger(conn, fqn)
|
||||||
}
|
}
|
||||||
@ -180,7 +180,7 @@ impl User {
|
|||||||
|
|
||||||
fn fetch_from_webfinger(conn: &Connection, acct: String) -> Option<User> {
|
fn fetch_from_webfinger(conn: &Connection, acct: String) -> Option<User> {
|
||||||
match resolve(acct.clone(), *USE_HTTPS) {
|
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) => {
|
Err(details) => {
|
||||||
println!("WF Error: {:?}", details);
|
println!("WF Error: {:?}", details);
|
||||||
None
|
None
|
||||||
@ -191,7 +191,7 @@ impl User {
|
|||||||
fn fetch(url: String) -> Option<CustomPerson> {
|
fn fetch(url: String) -> Option<CustomPerson> {
|
||||||
let req = Client::new()
|
let req = Client::new()
|
||||||
.get(&url[..])
|
.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();
|
.send();
|
||||||
match req {
|
match req {
|
||||||
Ok(mut res) => {
|
Ok(mut res) => {
|
||||||
@ -212,7 +212,9 @@ impl User {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn fetch_from_url(conn: &Connection, url: String) -> Option<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 {
|
fn from_activity(conn: &Connection, acct: CustomPerson, inst: String) -> User {
|
||||||
@ -277,16 +279,16 @@ impl User {
|
|||||||
users::avatar_id.eq(Some(avatar.id)),
|
users::avatar_id.eq(Some(avatar.id)),
|
||||||
users::last_fetched_date.eq(Utc::now().naive_utc())
|
users::last_fetched_date.eq(Utc::now().naive_utc())
|
||||||
)).execute(conn)
|
)).execute(conn)
|
||||||
.expect("Couldn't update user")
|
.expect("User::refetch: update error")
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn hash_pass(pass: String) -> String {
|
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 {
|
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
|
valid
|
||||||
} else {
|
} else {
|
||||||
false
|
false
|
||||||
@ -298,31 +300,31 @@ impl User {
|
|||||||
if self.outbox_url.len() == 0 {
|
if self.outbox_url.len() == 0 {
|
||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(users::outbox_url.eq(instance.compute_box(USER_PREFIX, self.username.clone(), "outbox")))
|
.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 {
|
if self.inbox_url.len() == 0 {
|
||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(users::inbox_url.eq(instance.compute_box(USER_PREFIX, self.username.clone(), "inbox")))
|
.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 {
|
if self.ap_url.len() == 0 {
|
||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(users::ap_url.eq(instance.compute_box(USER_PREFIX, self.username.clone(), "")))
|
.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() {
|
if self.shared_inbox_url.is_none() {
|
||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(users::shared_inbox_url.eq(ap_url(format!("{}/inbox", Instance::get_local(conn).unwrap().public_domain))))
|
.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("Couldn't update shared inbox URL");
|
.execute(conn).expect("User::update_boxes: shared inbox update error");
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.followers_endpoint.len() == 0 {
|
if self.followers_endpoint.len() == 0 {
|
||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(users::followers_endpoint.eq(instance.compute_box(USER_PREFIX, self.username.clone(), "followers")))
|
.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())
|
.offset(min.into())
|
||||||
.limit((max - min).into())
|
.limit((max - min).into())
|
||||||
.load::<User>(conn)
|
.load::<User>(conn)
|
||||||
.expect("Error getting local users page")
|
.expect("User::get_local_page: loading error")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn outbox(&self, conn: &Connection) -> ActivityStream<OrderedCollection> {
|
pub fn outbox(&self, conn: &Connection) -> ActivityStream<OrderedCollection> {
|
||||||
let acts = self.get_activities(conn);
|
let acts = self.get_activities(conn);
|
||||||
let n_acts = acts.len();
|
let n_acts = acts.len();
|
||||||
let mut coll = OrderedCollection::default();
|
let mut coll = OrderedCollection::default();
|
||||||
coll.collection_props.items = serde_json::to_value(acts).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).unwrap();
|
coll.collection_props.set_total_items_u64(n_acts as u64).expect("User::outbox: count error");
|
||||||
ActivityStream::new(coll)
|
ActivityStream::new(coll)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fetch_outbox<T: Activity>(&self) -> Vec<T> {
|
pub fn fetch_outbox<T: Activity>(&self) -> Vec<T> {
|
||||||
let req = Client::new()
|
let req = Client::new()
|
||||||
.get(&self.outbox_url[..])
|
.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();
|
.send();
|
||||||
match req {
|
match req {
|
||||||
Ok(mut res) => {
|
Ok(mut res) => {
|
||||||
let text = &res.text().unwrap();
|
let text = &res.text().expect("User::fetch_outbox: body error");
|
||||||
let json: serde_json::Value = serde_json::from_str(text).unwrap();
|
let json: serde_json::Value = serde_json::from_str(text).expect("User::fetch_outbox: parsing error");
|
||||||
json["items"].as_array()
|
json["items"].as_array()
|
||||||
.expect("Outbox.items is not an array")
|
.expect("Outbox.items is not an array")
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@ -369,14 +371,14 @@ impl User {
|
|||||||
pub fn fetch_followers_ids(&self) -> Vec<String> {
|
pub fn fetch_followers_ids(&self) -> Vec<String> {
|
||||||
let req = Client::new()
|
let req = Client::new()
|
||||||
.get(&self.followers_endpoint[..])
|
.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();
|
.send();
|
||||||
match req {
|
match req {
|
||||||
Ok(mut res) => {
|
Ok(mut res) => {
|
||||||
let text = &res.text().unwrap();
|
let text = &res.text().expect("User::fetch_followers_ids: body error");
|
||||||
let json: serde_json::Value = serde_json::from_str(text).unwrap();
|
let json: serde_json::Value = serde_json::from_str(text).expect("User::fetch_followers_ids: parsing error");
|
||||||
json["items"].as_array()
|
json["items"].as_array()
|
||||||
.expect("Followers.items is not an array")
|
.expect("User::fetch_followers_ids: not an array error")
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(|j| serde_json::from_value(j.clone()).ok())
|
.filter_map(|j| serde_json::from_value(j.clone()).ok())
|
||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
@ -395,9 +397,9 @@ impl User {
|
|||||||
let posts = posts::table
|
let posts = posts::table
|
||||||
.filter(posts::published.eq(true))
|
.filter(posts::published.eq(true))
|
||||||
.filter(posts::id.eq_any(posts_by_self))
|
.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| {
|
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>>()
|
}).collect::<Vec<serde_json::Value>>()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -412,7 +414,7 @@ impl User {
|
|||||||
pub fn get_followers(&self, conn: &Connection) -> Vec<User> {
|
pub fn get_followers(&self, conn: &Connection) -> Vec<User> {
|
||||||
use schema::follows;
|
use schema::follows;
|
||||||
let follows = Follow::belonging_to(self).select(follows::follower_id);
|
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> {
|
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))
|
users::table.filter(users::id.eq_any(follows))
|
||||||
.offset(min.into())
|
.offset(min.into())
|
||||||
.limit((max - 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> {
|
pub fn get_following(&self, conn: &Connection) -> Vec<User> {
|
||||||
use schema::follows::dsl::*;
|
use schema::follows::dsl::*;
|
||||||
let f = follows.filter(follower_id.eq(self.id)).select(following_id);
|
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 {
|
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::follower_id.eq(other_id))
|
||||||
.filter(follows::following_id.eq(self.id))
|
.filter(follows::following_id.eq(self.id))
|
||||||
.load::<Follow>(conn)
|
.load::<Follow>(conn)
|
||||||
.expect("Couldn't load follow relationship")
|
.expect("User::is_followed_by: loading error")
|
||||||
.len() > 0
|
.len() > 0// TODO count in database?
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_following(&self, conn: &Connection, other_id: i32) -> bool {
|
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::follower_id.eq(self.id))
|
||||||
.filter(follows::following_id.eq(other_id))
|
.filter(follows::following_id.eq(other_id))
|
||||||
.load::<Follow>(conn)
|
.load::<Follow>(conn)
|
||||||
.expect("Couldn't load follow relationship")
|
.expect("User::is_following: loading error")
|
||||||
.len() > 0
|
.len() > 0// TODO count in database?
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn has_liked(&self, conn: &Connection, post: &Post) -> bool {
|
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::post_id.eq(post.id))
|
||||||
.filter(likes::user_id.eq(self.id))
|
.filter(likes::user_id.eq(self.id))
|
||||||
.load::<Like>(conn)
|
.load::<Like>(conn)
|
||||||
.expect("Couldn't load likes")
|
.expect("User::has_liked: loading error")
|
||||||
.len() > 0
|
.len() > 0// TODO count in database?
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn has_reshared(&self, conn: &Connection, post: &Post) -> bool {
|
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::post_id.eq(post.id))
|
||||||
.filter(reshares::user_id.eq(self.id))
|
.filter(reshares::user_id.eq(self.id))
|
||||||
.load::<Reshare>(conn)
|
.load::<Reshare>(conn)
|
||||||
.expect("Couldn't load reshares")
|
.expect("User::has_reshared: loading error")
|
||||||
.len() > 0
|
.len() > 0// TODO count in database?
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_author_in(&self, conn: &Connection, blog: Blog) -> bool {
|
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))
|
blog_authors::table.filter(blog_authors::author_id.eq(self.id))
|
||||||
.filter(blog_authors::blog_id.eq(blog.id))
|
.filter(blog_authors::blog_id.eq(blog.id))
|
||||||
.load::<BlogAuthor>(conn)
|
.load::<BlogAuthor>(conn)
|
||||||
.expect("Couldn't load blog/author relationship")
|
.expect("User::is_author_in: loading error")
|
||||||
.len() > 0
|
.len() > 0// TODO count in database?
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_keypair(&self) -> PKey<Private> {
|
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 {
|
pub fn into_activity(&self, conn: &Connection) -> CustomPerson {
|
||||||
@ -514,7 +518,7 @@ impl User {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn to_json(&self, conn: &Connection) -> serde_json::Value {
|
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["fqn"] = serde_json::Value::String(self.get_fqn(conn));
|
||||||
json["name"] = if self.display_name.len() > 0 {
|
json["name"] = if self.display_name.len() > 0 {
|
||||||
json!(self.display_name)
|
json!(self.display_name)
|
||||||
@ -556,7 +560,7 @@ impl User {
|
|||||||
User::find_by_ap_url(conn, url.clone()).or_else(|| {
|
User::find_by_ap_url(conn, url.clone()).or_else(|| {
|
||||||
// The requested user was not in the DB
|
// The requested user was not in the DB
|
||||||
// We try to fetch it if it is remote
|
// 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)
|
User::fetch_from_url(conn, url)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
@ -568,7 +572,7 @@ impl User {
|
|||||||
diesel::update(self)
|
diesel::update(self)
|
||||||
.set(users::avatar_id.eq(id))
|
.set(users::avatar_id.eq(id))
|
||||||
.execute(conn)
|
.execute(conn)
|
||||||
.expect("Couldn't update user avatar");
|
.expect("User::set_avatar: update error");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn needs_update(&self) -> bool {
|
pub fn needs_update(&self) -> bool {
|
||||||
@ -584,7 +588,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for User {
|
|||||||
request.cookies()
|
request.cookies()
|
||||||
.get_private(AUTH_COOKIE)
|
.get_private(AUTH_COOKIE)
|
||||||
.and_then(|cookie| cookie.value().parse().ok())
|
.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(())
|
.or_forward(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -619,16 +623,17 @@ impl Signer for User {
|
|||||||
|
|
||||||
fn sign(&self, to_sign: String) -> Vec<u8> {
|
fn sign(&self, to_sign: String) -> Vec<u8> {
|
||||||
let key = self.get_keypair();
|
let key = self.get_keypair();
|
||||||
let mut signer = sign::Signer::new(MessageDigest::sha256(), &key).unwrap();
|
let mut signer = sign::Signer::new(MessageDigest::sha256(), &key).expect("User::sign: initialization error");
|
||||||
signer.update(to_sign.as_bytes()).unwrap();
|
signer.update(to_sign.as_bytes()).expect("User::sign: content insertion error");
|
||||||
signer.sign_to_vec().unwrap()
|
signer.sign_to_vec().expect("User::sign: finalization error")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn verify(&self, data: String, signature: Vec<u8>) -> bool {
|
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 key = PKey::from_rsa(Rsa::public_key_from_pem(self.public_key.as_ref()).expect("User::verify: pem parsing error"))
|
||||||
let mut verifier = sign::Verifier::new(MessageDigest::sha256(), &key).unwrap();
|
.expect("User::verify: deserialization error");
|
||||||
verifier.update(data.as_bytes()).unwrap();
|
let mut verifier = sign::Verifier::new(MessageDigest::sha256(), &key).expect("User::verify: initialization error");
|
||||||
verifier.verify(&signature).unwrap()
|
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),
|
hashed_password: Some(password),
|
||||||
instance_id: Instance::local_id(conn),
|
instance_id: Instance::local_id(conn),
|
||||||
ap_url: String::from(""),
|
ap_url: String::from(""),
|
||||||
public_key: String::from_utf8(pub_key).unwrap(),
|
public_key: String::from_utf8(pub_key).expect("NewUser::new_local: public key error"),
|
||||||
private_key: Some(String::from_utf8(priv_key).unwrap()),
|
private_key: Some(String::from_utf8(priv_key).expect("NewUser::new_local: private key error")),
|
||||||
shared_inbox_url: None,
|
shared_inbox_url: None,
|
||||||
followers_endpoint: String::from(""),
|
followers_endpoint: String::from(""),
|
||||||
avatar_id: None
|
avatar_id: None
|
||||||
|
@ -19,7 +19,7 @@ fn get(id: i32, conn: DbConn) -> Json<serde_json::Value> {
|
|||||||
|
|
||||||
#[get("/posts")]
|
#[get("/posts")]
|
||||||
fn list(conn: DbConn, uri: &Origin) -> Json<serde_json::Value> {
|
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);
|
let post = <Post as Provider<Connection>>::list(&*conn, query);
|
||||||
Json(json!(post))
|
Json(json!(post))
|
||||||
}
|
}
|
||||||
|
@ -16,7 +16,7 @@ use plume_models::{
|
|||||||
|
|
||||||
pub trait Inbox {
|
pub trait Inbox {
|
||||||
fn received(&self, conn: &Connection, act: serde_json::Value) -> Result<(), Error> {
|
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() {
|
match act["type"].as_str() {
|
||||||
Some(t) => {
|
Some(t) => {
|
||||||
match t {
|
match t {
|
||||||
@ -47,7 +47,7 @@ pub trait Inbox {
|
|||||||
},
|
},
|
||||||
"Undo" => {
|
"Undo" => {
|
||||||
let act: Undo = serde_json::from_value(act.clone())?;
|
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" => {
|
"Like" => {
|
||||||
likes::Like::delete_id(act.undo_props.object_object::<Like>()?.object_props.id_string()?, conn);
|
likes::Like::delete_id(act.undo_props.object_object::<Like>()?.object_props.id_string()?, conn);
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -56,7 +56,7 @@ fn init_pool() -> Option<DbPool> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let pool = init_pool().expect("Couldn't intialize database pool");
|
let pool = init_pool().expect("main: database pool initialization error");
|
||||||
rocket::ignite()
|
rocket::ignite()
|
||||||
.mount("/", routes![
|
.mount("/", routes![
|
||||||
routes::blogs::paginated_details,
|
routes::blogs::paginated_details,
|
||||||
@ -176,6 +176,6 @@ fn main() {
|
|||||||
("/login".to_owned(), "/login".to_owned(), rocket::http::Method::Post),
|
("/login".to_owned(), "/login".to_owned(), rocket::http::Method::Post),
|
||||||
("/users/new".to_owned(), "/users/new".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();
|
.launch();
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
use activitypub::collection::OrderedCollection;
|
use activitypub::collection::OrderedCollection;
|
||||||
use atom_syndication::{Entry, FeedBuilder};
|
use atom_syndication::{Entry, FeedBuilder};
|
||||||
use rocket::{
|
use rocket::{
|
||||||
|
http::ContentType,
|
||||||
request::LenientForm,
|
request::LenientForm,
|
||||||
response::{Redirect, Flash, content::Content},
|
response::{Redirect, Flash, content::Content}
|
||||||
http::ContentType
|
|
||||||
};
|
};
|
||||||
use rocket_contrib::Template;
|
use rocket_contrib::Template;
|
||||||
use serde_json;
|
use serde_json;
|
||||||
@ -49,9 +49,9 @@ fn details(name: String, conn: DbConn, user: Option<User>) -> Template {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[get("/~/<name>", rank = 1)]
|
#[get("/~/<name>", rank = 1)]
|
||||||
fn activity_details(name: String, conn: DbConn, _ap: ApRequest) -> ActivityStream<CustomGroup> {
|
fn activity_details(name: String, conn: DbConn, _ap: ApRequest) -> Option<ActivityStream<CustomGroup>> {
|
||||||
let blog = Blog::find_local(&*conn, name).unwrap();
|
let blog = Blog::find_local(&*conn, name)?;
|
||||||
ActivityStream::new(blog.into_activity(&*conn))
|
Some(ActivityStream::new(blog.into_activity(&*conn)))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/blogs/new")]
|
#[get("/blogs/new")]
|
||||||
@ -130,22 +130,23 @@ fn create(conn: DbConn, data: LenientForm<NewBlogForm>, user: User) -> Result<Re
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[get("/~/<name>/outbox")]
|
#[get("/~/<name>/outbox")]
|
||||||
fn outbox(name: String, conn: DbConn) -> ActivityStream<OrderedCollection> {
|
fn outbox(name: String, conn: DbConn) -> Option<ActivityStream<OrderedCollection>> {
|
||||||
let blog = Blog::find_local(&*conn, name).unwrap();
|
let blog = Blog::find_local(&*conn, name)?;
|
||||||
blog.outbox(&*conn)
|
Some(blog.outbox(&*conn))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/~/<name>/atom.xml")]
|
#[get("/~/<name>/atom.xml")]
|
||||||
fn atom_feed(name: String, conn: DbConn) -> Content<String> {
|
fn atom_feed(name: String, conn: DbConn) -> Option<Content<String>> {
|
||||||
let blog = Blog::find_by_fqn(&*conn, name.clone()).expect("Unable to find blog");
|
let blog = Blog::find_by_fqn(&*conn, name.clone())?;
|
||||||
let feed = FeedBuilder::default()
|
let feed = FeedBuilder::default()
|
||||||
.title(blog.title.clone())
|
.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)
|
.entries(Post::get_recents_for_blog(&*conn, &blog, 15)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|p| super::post_to_atom(p, &*conn))
|
.map(|p| super::post_to_atom(p, &*conn))
|
||||||
.collect::<Vec<Entry>>())
|
.collect::<Vec<Entry>>())
|
||||||
.build()
|
.build()
|
||||||
.expect("Error building Atom feed");
|
.expect("blogs::atom_feed: feed creation error");
|
||||||
Content(ContentType::new("application", "atom+xml"), feed.to_string())
|
Some(Content(ContentType::new("application", "atom+xml"), feed.to_string()))
|
||||||
}
|
}
|
||||||
|
@ -28,9 +28,10 @@ struct NewCommentForm {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[post("/~/<blog_name>/<slug>/comment", data = "<data>")]
|
#[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> {
|
fn create(blog_name: String, slug: String, data: LenientForm<NewCommentForm>, user: User, conn: DbConn, worker: State<Pool<ThunkWorker<()>>>)
|
||||||
let blog = Blog::find_by_fqn(&*conn, blog_name.clone()).unwrap();
|
-> Result<Redirect, Option<Template>> {
|
||||||
let post = Post::find_by_slug(&*conn, slug.clone(), blog.id).unwrap();
|
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();
|
let form = data.get();
|
||||||
form.validate()
|
form.validate()
|
||||||
.map(|_| {
|
.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 comments = Comment::list_by_post(&*conn, post.id);
|
||||||
let comms = comments.clone();
|
let comms = comments.clone();
|
||||||
|
|
||||||
Template::render("posts/details", json!({
|
Some(Template::render("posts/details", json!({
|
||||||
"author": post.get_authors(&*conn)[0].to_json(&*conn),
|
"author": post.get_authors(&*conn)[0].to_json(&*conn),
|
||||||
"post": post,
|
"post": post,
|
||||||
"blog": blog,
|
"blog": blog,
|
||||||
@ -74,10 +75,10 @@ fn create(blog_name: String, slug: String, data: LenientForm<NewCommentForm>, us
|
|||||||
"has_reshared": user.has_reshared(&*conn, &post),
|
"has_reshared": user.has_reshared(&*conn, &post),
|
||||||
"account": user.to_json(&*conn),
|
"account": user.to_json(&*conn),
|
||||||
"date": &post.creation_date.timestamp(),
|
"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),
|
"user_fqn": user.get_fqn(&*conn),
|
||||||
"errors": errors
|
"errors": errors
|
||||||
}))
|
})))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -6,21 +6,21 @@ use plume_models::users::User;
|
|||||||
|
|
||||||
#[catch(404)]
|
#[catch(404)]
|
||||||
fn not_found(req: &Request) -> Template {
|
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();
|
let user = User::from_request(req).succeeded();
|
||||||
Template::render("errors/404", json!({
|
Template::render("errors/404", json!({
|
||||||
"error_message": "Page not found",
|
"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)]
|
#[catch(500)]
|
||||||
fn server_error(req: &Request) -> Template {
|
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();
|
let user = User::from_request(req).succeeded();
|
||||||
Template::render("errors/500", json!({
|
Template::render("errors/500", json!({
|
||||||
"error_message": "Server error",
|
"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 gettextrs::gettext;
|
||||||
use rocket::{request::LenientForm, response::Redirect};
|
use rocket::{request::LenientForm, response::{status, Redirect}};
|
||||||
use rocket_contrib::{Json, Template};
|
use rocket_contrib::{Json, Template};
|
||||||
use serde_json;
|
use serde_json;
|
||||||
use validator::{Validate};
|
use validator::{Validate};
|
||||||
@ -52,7 +52,7 @@ fn index(conn: DbConn, user: Option<User>) -> Template {
|
|||||||
|
|
||||||
#[get("/local?<page>")]
|
#[get("/local?<page>")]
|
||||||
fn paginated_local(conn: DbConn, user: Option<User>, page: Page) -> Template {
|
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());
|
let articles = Post::get_instance_page(&*conn, instance.id, page.limits());
|
||||||
Template::render("instance/local", json!({
|
Template::render("instance/local", json!({
|
||||||
"account": user.map(|u| u.to_json(&*conn)),
|
"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();
|
let form = form.get();
|
||||||
form.validate()
|
form.validate()
|
||||||
.map(|_| {
|
.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,
|
instance.update(&*conn,
|
||||||
form.name.clone(),
|
form.name.clone(),
|
||||||
form.open_registrations,
|
form.open_registrations,
|
||||||
@ -196,31 +196,31 @@ fn ban(_admin: Admin, conn: DbConn, id: i32) -> Redirect {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[post("/inbox", data = "<data>")]
|
#[post("/inbox", data = "<data>")]
|
||||||
fn shared_inbox(conn: DbConn, data: String, headers: Headers) -> String {
|
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[..]).unwrap();
|
let act: serde_json::Value = serde_json::from_str(&data[..]).expect("instance::shared_inbox: deserialization error");
|
||||||
|
|
||||||
let activity = act.clone();
|
let activity = act.clone();
|
||||||
let actor_id = activity["actor"].as_str()
|
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() &&
|
if !verify_http_headers(&actor, headers.0.clone(), data).is_secure() &&
|
||||||
!act.clone().verify(&actor) {
|
!act.clone().verify(&actor) {
|
||||||
println!("Rejected invalid activity supposedly from {}, with headers {:?}", actor.username, headers.0);
|
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()) {
|
if Instance::is_blocked(&*conn, actor_id.to_string()) {
|
||||||
return String::new();
|
return Ok(String::new());
|
||||||
}
|
}
|
||||||
let instance = Instance::get_local(&*conn).unwrap();
|
let instance = Instance::get_local(&*conn).expect("instance::shared_inbox: local instance not found error");
|
||||||
match instance.received(&*conn, act) {
|
Ok(match instance.received(&*conn, act) {
|
||||||
Ok(_) => String::new(),
|
Ok(_) => String::new(),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!("Shared inbox error: {}\n{}", e.as_fail(), e.backtrace());
|
println!("Shared inbox error: {}\n{}", e.as_fail(), e.backtrace());
|
||||||
format!("Error: {}", e.as_fail())
|
format!("Error: {}", e.as_fail())
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/nodeinfo")]
|
#[get("/nodeinfo")]
|
||||||
@ -263,7 +263,7 @@ fn about(user: Option<User>, conn: DbConn) -> Template {
|
|||||||
|
|
||||||
#[get("/manifest.json")]
|
#[get("/manifest.json")]
|
||||||
fn web_manifest(conn: DbConn) -> Json<serde_json::Value> {
|
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!({
|
Json(json!({
|
||||||
"name": &instance.name,
|
"name": &instance.name,
|
||||||
"description": &instance.short_description,
|
"description": &instance.short_description,
|
||||||
|
@ -12,9 +12,9 @@ use plume_models::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
#[post("/~/<blog>/<slug>/like")]
|
#[post("/~/<blog>/<slug>/like")]
|
||||||
fn create(blog: String, slug: String, user: User, conn: DbConn, worker: State<Pool<ThunkWorker<()>>>) -> Redirect {
|
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()).unwrap();
|
let b = Blog::find_by_fqn(&*conn, blog.clone())?;
|
||||||
let post = Post::find_by_slug(&*conn, slug.clone(), b.id).unwrap();
|
let post = Post::find_by_slug(&*conn, slug.clone(), b.id)?;
|
||||||
|
|
||||||
if !user.has_liked(&*conn, &post) {
|
if !user.has_liked(&*conn, &post) {
|
||||||
let like = likes::Like::insert(&*conn, likes::NewLike {
|
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);
|
let act = like.into_activity(&*conn);
|
||||||
worker.execute(Thunk::of(move || broadcast(&user, act, dest)));
|
worker.execute(Thunk::of(move || broadcast(&user, act, dest)));
|
||||||
} else {
|
} 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 delete_act = like.delete(&*conn);
|
||||||
let dest = User::one_by_instance(&*conn);
|
let dest = User::one_by_instance(&*conn);
|
||||||
worker.execute(Thunk::of(move || broadcast(&user, delete_act, dest)));
|
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)]
|
#[post("/~/<blog>/<slug>/like", rank = 2)]
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
use guid_create::GUID;
|
use guid_create::GUID;
|
||||||
use multipart::server::{Multipart, save::{SavedData, SaveResult}};
|
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 rocket_contrib::Template;
|
||||||
use serde_json;
|
use serde_json;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
@ -25,30 +25,27 @@ fn new(user: User, conn: DbConn) -> Template {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[post("/medias/new", data = "<data>")]
|
#[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() {
|
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() {
|
match Multipart::with_body(data.open(), boundary).save().temp() {
|
||||||
SaveResult::Full(entries) => {
|
SaveResult::Full(entries) => {
|
||||||
let fields = entries.fields;
|
let fields = entries.fields;
|
||||||
|
|
||||||
let filename = fields.get(&"file".to_string()).unwrap().into_iter().next().unwrap().headers
|
let filename = fields.get(&"file".to_string()).and_then(|v| v.into_iter().next())
|
||||||
.filename.clone()
|
.ok_or_else(|| status::BadRequest(Some("No file uploaded")))?.headers
|
||||||
.unwrap_or("x.png".to_string()); // PNG by default
|
.filename.clone();
|
||||||
let ext = filename.rsplitn(2, ".")
|
let ext = filename.and_then(|f| f.rsplit('.').next().map(|ext| ext.to_owned()))
|
||||||
.next()
|
.unwrap_or("png".to_owned());
|
||||||
.unwrap();
|
|
||||||
let dest = format!("static/media/{}.{}", GUID::rand().to_string(), ext);
|
let dest = format!("static/media/{}.{}", GUID::rand().to_string(), ext);
|
||||||
|
|
||||||
if let SavedData::Bytes(ref bytes) = fields[&"file".to_string()][0].data {
|
match fields[&"file".to_string()][0].data {
|
||||||
fs::write(&dest, bytes).expect("Couldn't save upload");
|
SavedData::Bytes(ref bytes) => fs::write(&dest, bytes).expect("media::upload: Couldn't save upload"),
|
||||||
} else {
|
SavedData::File(ref path, _) => {fs::copy(path, &dest).expect("media::upload: Couldn't copy upload");},
|
||||||
if let SavedData::File(ref path, _) = fields[&"file".to_string()][0].data {
|
_ => {
|
||||||
fs::copy(path, &dest).expect("Couldn't copy temp upload");
|
println!("not a file");
|
||||||
} else {
|
return Ok(Redirect::to(uri!(new)));
|
||||||
println!("not file");
|
|
||||||
return Redirect::to(uri!(new));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -67,16 +64,16 @@ fn upload(user: User, data: Data, ct: &ContentType, conn: DbConn) -> Redirect {
|
|||||||
owner_id: user.id
|
owner_id: user.id
|
||||||
});
|
});
|
||||||
println!("ok");
|
println!("ok");
|
||||||
Redirect::to(uri!(details: id = media.id))
|
Ok(Redirect::to(uri!(details: id = media.id)))
|
||||||
},
|
},
|
||||||
SaveResult::Partial(_, _) | SaveResult::Error(_) => {
|
SaveResult::Partial(_, _) | SaveResult::Error(_) => {
|
||||||
println!("partial err");
|
println!("partial err");
|
||||||
Redirect::to(uri!(new))
|
Ok(Redirect::to(uri!(new)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
println!("not form data");
|
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")]
|
#[post("/medias/<id>/delete")]
|
||||||
fn delete(id: i32, _user: User, conn: DbConn) -> Redirect {
|
fn delete(id: i32, _user: User, conn: DbConn) -> Option<Redirect> {
|
||||||
let media = Media::get(&*conn, id).expect("Media to delete not found");
|
let media = Media::get(&*conn, id)?;
|
||||||
media.delete(&*conn);
|
media.delete(&*conn);
|
||||||
Redirect::to(uri!(list))
|
Some(Redirect::to(uri!(list)))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[post("/medias/<id>/avatar")]
|
#[post("/medias/<id>/avatar")]
|
||||||
fn set_avatar(id: i32, user: User, conn: DbConn) -> Redirect {
|
fn set_avatar(id: i32, user: User, conn: DbConn) -> Option<Redirect> {
|
||||||
let media = Media::get(&*conn, id).expect("Media to delete not found");
|
let media = Media::get(&*conn, id)?;
|
||||||
user.set_avatar(&*conn, media.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),
|
"has_reshared": user.clone().map(|u| u.has_reshared(&*conn, &post)).unwrap_or(false),
|
||||||
"account": &user.clone().map(|u| u.to_json(&*conn)),
|
"account": &user.clone().map(|u| u.to_json(&*conn)),
|
||||||
"date": &post.creation_date.timestamp(),
|
"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()),
|
"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_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)
|
"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)]
|
#[get("/~/<blog>/<slug>", rank = 3)]
|
||||||
fn activity_details(blog: String, slug: String, conn: DbConn, _ap: ApRequest) -> Result<ActivityStream<Article>, String> {
|
fn activity_details(blog: String, slug: String, conn: DbConn, _ap: ApRequest) -> Result<ActivityStream<Article>, Option<String>> {
|
||||||
let blog = Blog::find_by_fqn(&*conn, blog).unwrap();
|
let blog = Blog::find_by_fqn(&*conn, blog).ok_or(None)?;
|
||||||
let post = Post::find_by_slug(&*conn, slug, blog.id).unwrap();
|
let post = Post::find_by_slug(&*conn, slug, blog.id).ok_or(None)?;
|
||||||
if post.published {
|
if post.published {
|
||||||
Ok(ActivityStream::new(post.into_activity(&*conn)))
|
Ok(ActivityStream::new(post.into_activity(&*conn)))
|
||||||
} else {
|
} 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)]
|
#[get("/~/<blog>/new", rank = 1)]
|
||||||
fn new(blog: String, user: User, conn: DbConn) -> Template {
|
fn new(blog: String, user: User, conn: DbConn) -> Option<Template> {
|
||||||
let b = Blog::find_by_fqn(&*conn, blog.to_string()).unwrap();
|
let b = Blog::find_by_fqn(&*conn, blog.to_string())?;
|
||||||
|
|
||||||
if !user.is_author_in(&*conn, b.clone()) {
|
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."
|
"error_message": "You are not author in this blog."
|
||||||
}))
|
})))
|
||||||
} else {
|
} else {
|
||||||
Template::render("posts/new", json!({
|
Some(Template::render("posts/new", json!({
|
||||||
"account": user.to_json(&*conn),
|
"account": user.to_json(&*conn),
|
||||||
"instance": Instance::get_local(&*conn),
|
"instance": Instance::get_local(&*conn),
|
||||||
"editing": false,
|
"editing": false,
|
||||||
"errors": null,
|
"errors": null,
|
||||||
"form": null,
|
"form": null,
|
||||||
"is_draft": true,
|
"is_draft": true,
|
||||||
}))
|
})))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/~/<blog>/<slug>/edit")]
|
#[get("/~/<blog>/<slug>/edit")]
|
||||||
fn edit(blog: String, slug: String, user: User, conn: DbConn) -> Template {
|
fn edit(blog: String, slug: String, user: User, conn: DbConn) -> Option<Template> {
|
||||||
let b = Blog::find_by_fqn(&*conn, blog.to_string());
|
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");
|
let post = Post::find_by_slug(&*conn, slug, b.id)?;
|
||||||
|
|
||||||
if !user.is_author_in(&*conn, b.clone().unwrap()) {
|
if !user.is_author_in(&*conn, b) {
|
||||||
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."
|
"error_message": "You are not author in this blog."
|
||||||
}))
|
})))
|
||||||
} else {
|
} else {
|
||||||
let source = if post.source.clone().len() > 0 {
|
let source = if post.source.len() > 0 {
|
||||||
post.source.clone()
|
post.source
|
||||||
} else {
|
} 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),
|
"account": user.to_json(&*conn),
|
||||||
"instance": Instance::get_local(&*conn),
|
"instance": Instance::get_local(&*conn),
|
||||||
"editing": true,
|
"editing": true,
|
||||||
@ -145,14 +146,15 @@ fn edit(blog: String, slug: String, user: User, conn: DbConn) -> Template {
|
|||||||
draft: true,
|
draft: true,
|
||||||
},
|
},
|
||||||
"is_draft": !post.published
|
"is_draft": !post.published
|
||||||
}))
|
})))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[post("/~/<blog>/<slug>/edit", data = "<data>")]
|
#[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> {
|
fn update(blog: String, slug: String, user: User, conn: DbConn, data: LenientForm<NewPostForm>, worker: State<Pool<ThunkWorker<()>>>)
|
||||||
let b = Blog::find_by_fqn(&*conn, blog.to_string());
|
-> Result<Redirect, Option<Template>> {
|
||||||
let mut post = b.clone().and_then(|blog| Post::find_by_slug(&*conn, slug.clone(), blog.id)).expect("Post to update not found");
|
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 form = data.get();
|
||||||
let new_slug = if !post.published {
|
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 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 {
|
errors.add("title", ValidationError {
|
||||||
code: Cow::from("existing_slug"),
|
code: Cow::from("existing_slug"),
|
||||||
message: Some(Cow::from("A post with the same title already exists.")),
|
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 errors.is_empty() {
|
||||||
if !user.is_author_in(&*conn, b.clone().unwrap()) {
|
if !user.is_author_in(&*conn, b) {
|
||||||
// actually it's not "Ok"…
|
// actually it's not "Ok"…
|
||||||
Ok(Redirect::to(uri!(super::blogs::details: name = blog)))
|
Ok(Redirect::to(uri!(super::blogs::details: name = blog)))
|
||||||
} else {
|
} 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)))
|
Ok(Redirect::to(uri!(details: blog = blog, slug = new_slug)))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Err(Template::render("posts/new", json!({
|
Err(Some(Template::render("posts/new", json!({
|
||||||
"account": user.to_json(&*conn),
|
"account": user.to_json(&*conn),
|
||||||
"instance": Instance::get_local(&*conn),
|
"instance": Instance::get_local(&*conn),
|
||||||
"editing": true,
|
"editing": true,
|
||||||
"errors": errors.inner(),
|
"errors": errors.inner(),
|
||||||
"form": form,
|
"form": form,
|
||||||
"is_draft": form.draft,
|
"is_draft": form.draft,
|
||||||
})))
|
}))))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -263,8 +265,8 @@ fn valid_slug(title: &str) -> Result<(), ValidationError> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[post("/~/<blog_name>/new", data = "<data>")]
|
#[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> {
|
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()).unwrap();
|
let blog = Blog::find_by_fqn(&*conn, blog_name.to_string()).ok_or(None)?;
|
||||||
let form = data.get();
|
let form = data.get();
|
||||||
let slug = form.title.to_string().to_kebab_case();
|
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)))
|
Ok(Redirect::to(uri!(details: blog = blog_name, slug = slug)))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Err(Template::render("posts/new", json!({
|
Err(Some(Template::render("posts/new", json!({
|
||||||
"account": user.to_json(&*conn),
|
"account": user.to_json(&*conn),
|
||||||
"instance": Instance::get_local(&*conn),
|
"instance": Instance::get_local(&*conn),
|
||||||
"editing": false,
|
"editing": false,
|
||||||
"errors": errors.inner(),
|
"errors": errors.inner(),
|
||||||
"form": form,
|
"form": form,
|
||||||
"is_draft": form.draft
|
"is_draft": form.draft
|
||||||
})))
|
}))))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -12,9 +12,9 @@ use plume_models::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
#[post("/~/<blog>/<slug>/reshare")]
|
#[post("/~/<blog>/<slug>/reshare")]
|
||||||
fn create(blog: String, slug: String, user: User, conn: DbConn, worker: State<Pool<ThunkWorker<()>>>) -> Redirect {
|
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()).unwrap();
|
let b = Blog::find_by_fqn(&*conn, blog.clone())?;
|
||||||
let post = Post::find_by_slug(&*conn, slug.clone(), b.id).unwrap();
|
let post = Post::find_by_slug(&*conn, slug.clone(), b.id)?;
|
||||||
|
|
||||||
if !user.has_reshared(&*conn, &post) {
|
if !user.has_reshared(&*conn, &post) {
|
||||||
let reshare = Reshare::insert(&*conn, NewReshare {
|
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);
|
let act = reshare.into_activity(&*conn);
|
||||||
worker.execute(Thunk::of(move || broadcast(&user, act, dest)));
|
worker.execute(Thunk::of(move || broadcast(&user, act, dest)));
|
||||||
} else {
|
} 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 delete_act = reshare.delete(&*conn);
|
||||||
let dest = User::one_by_instance(&*conn);
|
let dest = User::one_by_instance(&*conn);
|
||||||
worker.execute(Thunk::of(move || broadcast(&user, delete_act, dest)));
|
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)]
|
#[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> {
|
fn create(conn: DbConn, data: LenientForm<LoginForm>, flash: Option<FlashMessage>, mut cookies: Cookies) -> Result<Redirect, Template> {
|
||||||
let form = data.get();
|
let form = data.get();
|
||||||
let user = User::find_by_email(&*conn, form.email_or_name.to_string())
|
let user = User::find_by_email(&*conn, form.email_or_name.to_string())
|
||||||
.map(|u| Ok(u))
|
.or_else(|| User::find_local(&*conn, form.email_or_name.to_string()));
|
||||||
.unwrap_or_else(|| User::find_local(&*conn, form.email_or_name.to_string()).map(|u| Ok(u)).unwrap_or(Err(())));
|
|
||||||
|
|
||||||
let mut errors = match form.validate() {
|
let mut errors = match form.validate() {
|
||||||
Ok(_) => ValidationErrors::new(),
|
Ok(_) => ValidationErrors::new(),
|
||||||
Err(e) => e
|
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
|
// Fake password verification, only to avoid different login times
|
||||||
// that could be used to see if an email adress is registered or not
|
// 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()));
|
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");
|
let mut err = ValidationError::new("invalid_login");
|
||||||
err.message = Some(Cow::from("Invalid username or password"));
|
err.message = Some(Cow::from("Invalid username or password"));
|
||||||
errors.add("email_or_name", err)
|
errors.add("email_or_name", err)
|
||||||
@ -107,7 +108,6 @@ fn create(conn: DbConn, data: LenientForm<LoginForm>, flash: Option<FlashMessage
|
|||||||
|
|
||||||
#[get("/logout")]
|
#[get("/logout")]
|
||||||
fn delete(mut cookies: Cookies) -> Redirect {
|
fn delete(mut cookies: Cookies) -> Redirect {
|
||||||
let cookie = cookies.get_private(AUTH_COOKIE).unwrap();
|
cookies.get_private(AUTH_COOKIE).map(|cookie| cookies.remove_private(cookie));
|
||||||
cookies.remove_private(cookie);
|
|
||||||
Redirect::to("/")
|
Redirect::to("/")
|
||||||
}
|
}
|
||||||
|
@ -10,19 +10,19 @@ use plume_models::{
|
|||||||
use routes::Page;
|
use routes::Page;
|
||||||
|
|
||||||
#[get("/tag/<name>")]
|
#[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())
|
paginated_tag(user, conn, name, Page::first())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/tag/<name>?<page>")]
|
#[get("/tag/<name>?<page>")]
|
||||||
fn paginated_tag(user: Option<User>, conn: DbConn, name: String, page: Page) -> Template {
|
fn paginated_tag(user: Option<User>, conn: DbConn, name: String, page: Page) -> Option<Template> {
|
||||||
let tag = Tag::find_by_name(&*conn, name).expect("Rendering tags::tag: tag not found");
|
let tag = Tag::find_by_name(&*conn, name)?;
|
||||||
let posts = Post::list_by_tag(&*conn, tag.tag.clone(), page.limits());
|
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(),
|
"tag": tag.clone(),
|
||||||
"account": user.map(|u| u.to_json(&*conn)),
|
"account": user.map(|u| u.to_json(&*conn)),
|
||||||
"articles": posts.into_iter().map(|p| p.to_json(&*conn)).collect::<Vec<serde_json::Value>>(),
|
"articles": posts.into_iter().map(|p| p.to_json(&*conn)).collect::<Vec<serde_json::Value>>(),
|
||||||
"page": page.page,
|
"page": page.page,
|
||||||
"n_pages": Page::total(Post::count_for_tag(&*conn, tag.tag) as i32)
|
"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 atom_syndication::{Entry, FeedBuilder};
|
||||||
use rocket::{
|
use rocket::{
|
||||||
request::LenientForm,
|
request::LenientForm,
|
||||||
response::{Redirect, Flash, Content},
|
response::{Content, Flash, Redirect, status},
|
||||||
http::{ContentType, Cookies}
|
http::{ContentType, Cookies}
|
||||||
};
|
};
|
||||||
use rocket_contrib::Template;
|
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 || {
|
worker.execute(Thunk::of(move || {
|
||||||
for user_id in user_clone.fetch_followers_ids() {
|
for user_id in user_clone.fetch_followers_ids() {
|
||||||
let follower = User::find_by_ap_url(&*fecth_followers_conn, user_id.clone())
|
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 {
|
follows::Follow::insert(&*fecth_followers_conn, follows::NewFollow {
|
||||||
follower_id: follower.id,
|
follower_id: follower.id,
|
||||||
following_id: user_clone.id,
|
following_id: user_clone.id,
|
||||||
@ -121,8 +121,8 @@ fn dashboard_auth() -> Flash<Redirect> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[post("/@/<name>/follow")]
|
#[post("/@/<name>/follow")]
|
||||||
fn follow(name: String, conn: DbConn, user: User, worker: Worker) -> Redirect {
|
fn follow(name: String, conn: DbConn, user: User, worker: Worker) -> Option<Redirect> {
|
||||||
let target = User::find_by_fqn(&*conn, name.clone()).unwrap();
|
let target = User::find_by_fqn(&*conn, name.clone())?;
|
||||||
if let Some(follow) = follows::Follow::find(&*conn, user.id, target.id) {
|
if let Some(follow) = follows::Follow::find(&*conn, user.id, target.id) {
|
||||||
let delete_act = follow.delete(&*conn);
|
let delete_act = follow.delete(&*conn);
|
||||||
worker.execute(Thunk::of(move || broadcast(&user, delete_act, vec![target])));
|
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);
|
let act = f.into_activity(&*conn);
|
||||||
worker.execute(Thunk::of(move || broadcast(&user, act, vec![target])));
|
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)]
|
#[post("/@/<name>/follow", rank = 2)]
|
||||||
@ -176,9 +176,9 @@ fn followers(name: String, conn: DbConn, account: Option<User>) -> Template {
|
|||||||
|
|
||||||
|
|
||||||
#[get("/@/<name>", rank = 1)]
|
#[get("/@/<name>", rank = 1)]
|
||||||
fn activity_details(name: String, conn: DbConn, _ap: ApRequest) -> ActivityStream<CustomPerson> {
|
fn activity_details(name: String, conn: DbConn, _ap: ApRequest) -> Option<ActivityStream<CustomPerson>> {
|
||||||
let user = User::find_local(&*conn, name).unwrap();
|
let user = User::find_local(&*conn, name)?;
|
||||||
ActivityStream::new(user.into_activity(&*conn))
|
Some(ActivityStream::new(user.into_activity(&*conn)))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/users/new")]
|
#[get("/users/new")]
|
||||||
@ -228,17 +228,16 @@ fn update(_name: String, conn: DbConn, user: User, data: LenientForm<UpdateUserF
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[post("/@/<name>/delete")]
|
#[post("/@/<name>/delete")]
|
||||||
fn delete(name: String, conn: DbConn, user: User, mut cookies: Cookies) -> Redirect {
|
fn delete(name: String, conn: DbConn, user: User, mut cookies: Cookies) -> Option<Redirect> {
|
||||||
let account = User::find_by_fqn(&*conn, name.clone()).unwrap();
|
let account = User::find_by_fqn(&*conn, name.clone())?;
|
||||||
if user.id == account.id {
|
if user.id == account.id {
|
||||||
account.delete(&*conn);
|
account.delete(&*conn);
|
||||||
|
|
||||||
let cookie = cookies.get_private(AUTH_COOKIE).unwrap();
|
cookies.get_private(AUTH_COOKIE).map(|cookie| cookies.remove_private(cookie));
|
||||||
cookies.remove_private(cookie);
|
|
||||||
|
|
||||||
Redirect::to(uri!(super::instance::index))
|
Some(Redirect::to(uri!(super::instance::index)))
|
||||||
} else {
|
} 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")]
|
#[get("/@/<name>/outbox")]
|
||||||
fn outbox(name: String, conn: DbConn) -> ActivityStream<OrderedCollection> {
|
fn outbox(name: String, conn: DbConn) -> Option<ActivityStream<OrderedCollection>> {
|
||||||
let user = User::find_local(&*conn, name).unwrap();
|
let user = User::find_local(&*conn, name)?;
|
||||||
user.outbox(&*conn)
|
Some(user.outbox(&*conn))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[post("/@/<name>/inbox", data = "<data>")]
|
#[post("/@/<name>/inbox", data = "<data>")]
|
||||||
fn inbox(name: String, conn: DbConn, data: String, headers: Headers) -> String {
|
fn inbox(name: String, conn: DbConn, data: String, headers: Headers) -> Result<String, Option<status::BadRequest<&'static str>>> {
|
||||||
let user = User::find_local(&*conn, name).unwrap();
|
let user = User::find_local(&*conn, name).ok_or(None)?;
|
||||||
let act: serde_json::Value = serde_json::from_str(&data[..]).unwrap();
|
let act: serde_json::Value = serde_json::from_str(&data[..]).expect("user::inbox: deserialization error");
|
||||||
|
|
||||||
let activity = act.clone();
|
let activity = act.clone();
|
||||||
let actor_id = activity["actor"].as_str()
|
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() &&
|
if !verify_http_headers(&actor, headers.0.clone(), data).is_secure() &&
|
||||||
!act.clone().verify(&actor) {
|
!act.clone().verify(&actor) {
|
||||||
println!("Rejected invalid activity supposedly from {}, with headers {:?}", actor.username, headers.0);
|
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()) {
|
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(),
|
Ok(_) => String::new(),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!("User inbox error: {}\n{}", e.as_fail(), e.backtrace());
|
println!("User inbox error: {}\n{}", e.as_fail(), e.backtrace());
|
||||||
format!("Error: {}", e.as_fail())
|
format!("Error: {}", e.as_fail())
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/@/<name>/followers")]
|
#[get("/@/<name>/followers")]
|
||||||
fn ap_followers(name: String, conn: DbConn, _ap: ApRequest) -> ActivityStream<OrderedCollection> {
|
fn ap_followers(name: String, conn: DbConn, _ap: ApRequest) -> Option<ActivityStream<OrderedCollection>> {
|
||||||
let user = User::find_local(&*conn, name).unwrap();
|
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 followers = user.get_followers(&*conn).into_iter().map(|f| Id::new(f.ap_url)).collect::<Vec<Id>>();
|
||||||
|
|
||||||
let mut coll = OrderedCollection::default();
|
let mut coll = OrderedCollection::default();
|
||||||
coll.object_props.set_id_string(user.followers_endpoint).expect("Follower collection: id error");
|
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("Follower collection: totalItems 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("Follower collection: items error");
|
coll.collection_props.set_items_link_vec(followers).expect("user::ap_followers items error");
|
||||||
ActivityStream::new(coll)
|
Some(ActivityStream::new(coll))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/@/<name>/atom.xml")]
|
#[get("/@/<name>/atom.xml")]
|
||||||
fn atom_feed(name: String, conn: DbConn) -> Content<String> {
|
fn atom_feed(name: String, conn: DbConn) -> Option<Content<String>> {
|
||||||
let author = User::find_by_fqn(&*conn, name.clone()).expect("Unable to find author");
|
let author = User::find_by_fqn(&*conn, name.clone())?;
|
||||||
let feed = FeedBuilder::default()
|
let feed = FeedBuilder::default()
|
||||||
.title(author.display_name.clone())
|
.title(author.display_name.clone())
|
||||||
.id(Instance::get_local(&*conn).unwrap().compute_box("~", name, "atom.xml"))
|
.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))
|
.map(|p| super::post_to_atom(p, &*conn))
|
||||||
.collect::<Vec<Entry>>())
|
.collect::<Vec<Entry>>())
|
||||||
.build()
|
.build()
|
||||||
.expect("Error building Atom feed");
|
.expect("user::atom_feed: Error building Atom feed");
|
||||||
Content(ContentType::new("application", "atom+xml"), feed.to_string())
|
Some(Content(ContentType::new("application", "atom+xml"), feed.to_string()))
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user