Fix block user route, send correct user struct.

Add route for fetching members.
Cargo fmt on accident.
This commit is contained in:
Paul
2021-05-14 22:29:43 +01:00
parent cc0307f702
commit 6cc92b877e
19 changed files with 184 additions and 133 deletions

View File

@@ -1 +1 @@
fn main() {} fn main() {}

View File

@@ -44,7 +44,7 @@ pub enum Channel {
owner: String, owner: String,
description: String, description: String,
recipients: Vec<String>, recipients: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
icon: Option<File>, icon: Option<File>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
@@ -93,8 +93,7 @@ impl Channel {
})?; })?;
let channel_id = self.id().to_string(); let channel_id = self.id().to_string();
ClientboundNotification::ChannelCreate(self) ClientboundNotification::ChannelCreate(self).publish(channel_id);
.publish(channel_id);
Ok(()) Ok(())
} }
@@ -104,7 +103,7 @@ impl Channel {
ClientboundNotification::ChannelUpdate { ClientboundNotification::ChannelUpdate {
id: id.clone(), id: id.clone(),
data, data,
clear: None clear: None,
} }
.publish(id); .publish(id);
@@ -188,9 +187,8 @@ impl Channel {
with: "channel", with: "channel",
})?; })?;
ClientboundNotification::ChannelDelete { id: id.to_string() } ClientboundNotification::ChannelDelete { id: id.to_string() }.publish(id.to_string());
.publish(id.to_string());
if let Channel::Group { icon, .. } = self { if let Channel::Group { icon, .. } = self {
if let Some(attachment) = icon { if let Some(attachment) = icon {
attachment.delete().await?; attachment.delete().await?;

View File

@@ -1,6 +1,9 @@
use serde::{Serialize, Deserialize}; use crate::util::{
result::{Error, Result},
variables::JANUARY_URL,
};
use linkify::{LinkFinder, LinkKind}; use linkify::{LinkFinder, LinkKind};
use crate::util::{result::{Error, Result}, variables::JANUARY_URL}; use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub enum ImageSize { pub enum ImageSize {
@@ -33,7 +36,7 @@ pub enum TwitchType {
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub enum BandcampType { pub enum BandcampType {
Album, Album,
Track Track,
} }
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
@@ -54,8 +57,8 @@ pub enum Special {
Soundcloud, Soundcloud,
Bandcamp { Bandcamp {
content_type: BandcampType, content_type: BandcampType,
id: String id: String,
} },
} }
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
@@ -98,7 +101,7 @@ impl Embed {
// Ignore quoted lines. // Ignore quoted lines.
if let Some(c) = v.chars().next() { if let Some(c) = v.chars().next() {
if c == '>' { if c == '>' {
return "" return "";
} }
} }
@@ -131,12 +134,10 @@ impl Embed {
Err(_) => return Err(Error::LabelMe), Err(_) => return Err(Error::LabelMe),
Ok(result) => match result.status() { Ok(result) => match result.status() {
reqwest::StatusCode::OK => { reqwest::StatusCode::OK => {
let res: Embed = result.json() let res: Embed = result.json().await.map_err(|_| Error::InvalidOperation)?;
.await
.map_err(|_| Error::InvalidOperation)?;
Ok(vec![ res ]) Ok(vec![res])
}, }
_ => return Err(Error::LabelMe), _ => return Err(Error::LabelMe),
}, },
} }

View File

@@ -135,9 +135,7 @@ impl Message {
self.process_embed(); self.process_embed();
let enc = serde_json::to_string(&self).unwrap(); let enc = serde_json::to_string(&self).unwrap();
ClientboundNotification::Message(self) ClientboundNotification::Message(self).publish(channel.id().to_string());
.publish(channel.id().to_string());
/* /*
Web Push Test Code Web Push Test Code
@@ -202,9 +200,11 @@ impl Message {
for subscription in subscriptions { for subscription in subscriptions {
let mut builder = WebPushMessageBuilder::new(&subscription).unwrap(); let mut builder = WebPushMessageBuilder::new(&subscription).unwrap();
let sig_builder = let sig_builder = VapidSignatureBuilder::from_pem(
VapidSignatureBuilder::from_pem(std::io::Cursor::new(&key), &subscription) std::io::Cursor::new(&key),
.unwrap(); &subscription,
)
.unwrap();
let signature = sig_builder.build().unwrap(); let signature = sig_builder.build().unwrap();
builder.set_vapid_signature(signature); builder.set_vapid_signature(signature);
builder.set_payload(ContentEncoding::AesGcm, enc.as_bytes()); builder.set_payload(ContentEncoding::AesGcm, enc.as_bytes());
@@ -250,12 +250,11 @@ impl Message {
}, },
None, None,
) )
.await { .await
{
ClientboundNotification::MessageUpdate { ClientboundNotification::MessageUpdate {
id, id,
data: json!({ data: json!({ "embeds": embeds }),
"embeds": embeds
}),
} }
.publish(channel); .publish(channel);
} }

View File

@@ -1,13 +1,13 @@
mod server;
mod autumn; mod autumn;
mod january;
mod channel; mod channel;
mod january;
mod message; mod message;
mod server;
mod user; mod user;
pub use january::*;
pub use autumn::*; pub use autumn::*;
pub use channel::*; pub use channel::*;
pub use server::*; pub use january::*;
pub use message::*; pub use message::*;
pub use server::*;
pub use user::*; pub use user::*;

View File

@@ -1,12 +1,16 @@
use mongodb::bson::doc; use futures::StreamExt;
use mongodb::options::{Collation, FindOneOptions}; use mongodb::options::{Collation, FindOneOptions};
use mongodb::{
bson::{doc, from_document},
options::FindOptions,
};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use validator::Validate;
use crate::database::permissions::user::UserPermissions; use crate::database::permissions::user::UserPermissions;
use crate::database::*; use crate::database::*;
use crate::notifications::websocket::is_online; use crate::notifications::websocket::is_online;
use crate::util::result::{Error, Result}; use crate::util::result::{Error, Result};
use validator::Validate;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum RelationshipStatus { pub enum RelationshipStatus {
@@ -160,4 +164,46 @@ impl User {
Ok(false) Ok(false)
} }
} }
/// Utility function for fetching multiple users from the perspective of one.
pub async fn fetch_multiple_users(&self, user_ids: Vec<String>) -> Result<Vec<User>> {
let mut users = vec![];
let mut cursor = get_collection("users")
.find(
doc! {
"_id": {
"$in": user_ids
}
},
FindOptions::builder()
.projection(
doc! { "_id": 1, "username": 1, "avatar": 1, "badges": 1, "status": 1 },
)
.build(),
)
.await
.map_err(|_| Error::DatabaseError {
operation: "find",
with: "users",
})?;
while let Some(result) = cursor.next().await {
if let Ok(doc) = result {
let other: User = from_document(doc).map_err(|_| Error::DatabaseError {
operation: "from_document",
with: "user",
})?;
let permissions = PermissionCalculator::new(&self)
.with_mutual_connection()
.with_user(&other)
.for_user_given()
.await?;
users.push(other.from(&self).with(permissions));
}
}
Ok(users)
}
} }

View File

@@ -15,9 +15,9 @@ extern crate ctrlc;
pub mod database; pub mod database;
pub mod notifications; pub mod notifications;
pub mod version;
pub mod routes; pub mod routes;
pub mod util; pub mod util;
pub mod version;
use async_std::task; use async_std::task;
use chrono::Duration; use chrono::Duration;
@@ -40,7 +40,10 @@ async fn main() {
dotenv::dotenv().ok(); dotenv::dotenv().ok();
env_logger::init_from_env(env_logger::Env::default().filter_or("RUST_LOG", "info")); env_logger::init_from_env(env_logger::Env::default().filter_or("RUST_LOG", "info"));
info!("Starting REVOLT server [version {}].", crate::version::VERSION); info!(
"Starting REVOLT server [version {}].",
crate::version::VERSION
);
util::variables::preflight_checks(); util::variables::preflight_checks();
database::connect().await; database::connect().await;

View File

@@ -35,12 +35,12 @@ pub enum RemoveUserField {
ProfileContent, ProfileContent,
ProfileBackground, ProfileBackground,
StatusText, StatusText,
Avatar Avatar,
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub enum RemoveChannelField { pub enum RemoveChannelField {
Icon Icon,
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
@@ -67,7 +67,7 @@ pub enum ClientboundNotification {
id: String, id: String,
data: JsonValue, data: JsonValue,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
clear: Option<RemoveChannelField> clear: Option<RemoveChannelField>,
}, },
ChannelGroupJoin { ChannelGroupJoin {
id: String, id: String,
@@ -93,7 +93,7 @@ pub enum ClientboundNotification {
id: String, id: String,
data: JsonValue, data: JsonValue,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
clear: Option<RemoveUserField> clear: Option<RemoveUserField>,
}, },
UserRelationship { UserRelationship {
id: String, id: String,
@@ -110,7 +110,9 @@ impl ClientboundNotification {
pub fn publish(self, topic: String) { pub fn publish(self, topic: String) {
async_std::task::spawn(async move { async_std::task::spawn(async move {
prehandle_hook(&self); // ! TODO: this should be moved to pubsub prehandle_hook(&self); // ! TODO: this should be moved to pubsub
hive_pubsub::backend::mongo::publish(get_hive(), &topic, self).await.ok(); hive_pubsub::backend::mongo::publish(get_hive(), &topic, self)
.await
.ok();
}); });
} }
} }

View File

@@ -6,13 +6,9 @@ use crate::{
util::result::{Error, Result}, util::result::{Error, Result},
}; };
use futures::StreamExt; use futures::StreamExt;
use mongodb::{ use mongodb::bson::{doc, from_document};
bson::{doc, from_document},
options::FindOptions,
};
pub async fn generate_ready(mut user: User) -> Result<ClientboundNotification> { pub async fn generate_ready(mut user: User) -> Result<ClientboundNotification> {
let mut users = vec![];
let mut user_ids: HashSet<String> = HashSet::new(); let mut user_ids: HashSet<String> = HashSet::new();
if let Some(relationships) = &user.relations { if let Some(relationships) = &user.relations {
@@ -68,41 +64,12 @@ pub async fn generate_ready(mut user: User) -> Result<ClientboundNotification> {
} }
user_ids.remove(&user.id); user_ids.remove(&user.id);
if user_ids.len() > 0 { let mut users = if user_ids.len() > 0 {
let mut cursor = get_collection("users") user.fetch_multiple_users(user_ids.into_iter().collect::<Vec<String>>())
.find( .await?
doc! { } else {
"_id": { vec![]
"$in": user_ids.into_iter().collect::<Vec<String>>() };
}
},
FindOptions::builder()
.projection(doc! { "_id": 1, "username": 1, "avatar": 1, "badges": 1, "status": 1 })
.build(),
)
.await
.map_err(|_| Error::DatabaseError {
operation: "find",
with: "users",
})?;
while let Some(result) = cursor.next().await {
if let Ok(doc) = result {
let other: User = from_document(doc).map_err(|_| Error::DatabaseError {
operation: "from_document",
with: "user",
})?;
let permissions = PermissionCalculator::new(&user)
.with_mutual_connection()
.with_user(&other)
.for_user_given()
.await?;
users.push(other.from(&user).with(permissions));
}
}
}
user.relationship = Some(RelationshipStatus::User); user.relationship = Some(RelationshipStatus::User);
user.online = Some(true); user.online = Some(true);

View File

@@ -1,6 +1,6 @@
use crate::{database::*, notifications::events::RemoveChannelField};
use crate::notifications::events::ClientboundNotification; use crate::notifications::events::ClientboundNotification;
use crate::util::result::{Error, Result}; use crate::util::result::{Error, Result};
use crate::{database::*, notifications::events::RemoveChannelField};
use mongodb::bson::{doc, to_document}; use mongodb::bson::{doc, to_document};
use rocket_contrib::json::Json; use rocket_contrib::json::Json;
@@ -17,7 +17,7 @@ pub struct Data {
description: Option<String>, description: Option<String>,
#[validate(length(min = 1, max = 128))] #[validate(length(min = 1, max = 128))]
icon: Option<String>, icon: Option<String>,
remove: Option<RemoveChannelField> remove: Option<RemoveChannelField>,
} }
#[patch("/<target>", data = "<data>")] #[patch("/<target>", data = "<data>")]
@@ -26,8 +26,12 @@ pub async fn req(user: User, target: Ref, data: Json<Data>) -> Result<()> {
data.validate() data.validate()
.map_err(|error| Error::FailedValidation { error })?; .map_err(|error| Error::FailedValidation { error })?;
if data.name.is_none() && data.description.is_none() && data.icon.is_none() && data.remove.is_none() { if data.name.is_none()
return Ok(()) && data.description.is_none()
&& data.icon.is_none()
&& data.remove.is_none()
{
return Ok(());
} }
let target = target.fetch_channel().await?; let target = target.fetch_channel().await?;
@@ -64,7 +68,8 @@ pub async fn req(user: User, target: Ref, data: Json<Data>) -> Result<()> {
} }
if let Some(attachment_id) = &data.icon { if let Some(attachment_id) = &data.icon {
let attachment = File::find_and_use(&attachment_id, "icons", "object", &user.id).await?; let attachment =
File::find_and_use(&attachment_id, "icons", "object", &user.id).await?;
set.insert( set.insert(
"icon", "icon",
to_document(&attachment).map_err(|_| Error::DatabaseError { to_document(&attachment).map_err(|_| Error::DatabaseError {
@@ -72,7 +77,7 @@ pub async fn req(user: User, target: Ref, data: Json<Data>) -> Result<()> {
with: "attachment", with: "attachment",
})?, })?,
); );
remove_icon = true; remove_icon = true;
} }
@@ -80,26 +85,25 @@ pub async fn req(user: User, target: Ref, data: Json<Data>) -> Result<()> {
if set.len() > 0 { if set.len() > 0 {
operations.insert("$set", &set); operations.insert("$set", &set);
} }
if unset.len() > 0 { if unset.len() > 0 {
operations.insert("$unset", unset); operations.insert("$unset", unset);
} }
if operations.len() > 0 { if operations.len() > 0 {
get_collection("channels") get_collection("channels")
.update_one( .update_one(doc! { "_id": &id }, operations, None)
doc! { "_id": &id }, .await
operations, .map_err(|_| Error::DatabaseError {
None operation: "update_one",
) with: "channel",
.await })?;
.map_err(|_| Error::DatabaseError { operation: "update_one", with: "channel" })?;
} }
ClientboundNotification::ChannelUpdate { ClientboundNotification::ChannelUpdate {
id: id.clone(), id: id.clone(),
data: json!(set), data: json!(set),
clear: data.remove clear: data.remove,
} }
.publish(id.clone()); .publish(id.clone());
@@ -107,10 +111,7 @@ pub async fn req(user: User, target: Ref, data: Json<Data>) -> Result<()> {
Message::create( Message::create(
"00000000000000000000000000".to_string(), "00000000000000000000000000".to_string(),
id.clone(), id.clone(),
Content::SystemMessage(SystemMessage::ChannelRenamed { Content::SystemMessage(SystemMessage::ChannelRenamed { name, by: user.id }),
name,
by: user.id,
}),
) )
.publish(&target) .publish(&target)
.await .await

View File

@@ -0,0 +1,23 @@
use crate::database::*;
use crate::util::result::{Error, Result};
use rocket_contrib::json::JsonValue;
#[get("/<target>/members")]
pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
let target = target.fetch_channel().await?;
let perm = permissions::PermissionCalculator::new(&user)
.with_channel(&target)
.for_channel()
.await?;
if !perm.get_view() {
Err(Error::MissingPermission)?
}
if let Channel::Group { recipients, .. } = target {
Ok(json!(user.fetch_multiple_users(recipients).await?))
} else {
Err(Error::InvalidOperation)
}
}

View File

@@ -14,7 +14,7 @@ use validator::Validate;
#[derive(Serialize, Deserialize, FromFormValue)] #[derive(Serialize, Deserialize, FromFormValue)]
pub enum Sort { pub enum Sort {
Latest, Latest,
Oldest Oldest,
} }
#[derive(Validate, Serialize, Deserialize, FromForm)] #[derive(Validate, Serialize, Deserialize, FromForm)]
@@ -25,7 +25,7 @@ pub struct Options {
before: Option<String>, before: Option<String>,
#[validate(length(min = 26, max = 26))] #[validate(length(min = 26, max = 26))]
after: Option<String>, after: Option<String>,
sort: Option<Sort> sort: Option<Sort>,
} }
#[get("/<target>/messages?<options..>")] #[get("/<target>/messages?<options..>")]
@@ -54,7 +54,11 @@ pub async fn req(user: User, target: Ref, options: Form<Options>) -> Result<Json
query.insert("_id", doc! { "$gt": after }); query.insert("_id", doc! { "$gt": after });
} }
let sort = if let Sort::Latest = options.sort.as_ref().unwrap_or_else(|| &Sort::Latest) { -1 } else { 1 }; let sort = if let Sort::Latest = options.sort.as_ref().unwrap_or_else(|| &Sort::Latest) {
-1
} else {
1
};
let mut cursor = get_collection("messages") let mut cursor = get_collection("messages")
.find( .find(
query, query,

View File

@@ -3,6 +3,7 @@ use rocket::Route;
mod delete_channel; mod delete_channel;
mod edit_channel; mod edit_channel;
mod fetch_channel; mod fetch_channel;
mod fetch_members;
mod group_add_member; mod group_add_member;
mod group_create; mod group_create;
mod group_remove_member; mod group_remove_member;
@@ -17,6 +18,7 @@ mod message_send;
pub fn routes() -> Vec<Route> { pub fn routes() -> Vec<Route> {
routes![ routes![
fetch_channel::req, fetch_channel::req,
fetch_members::req,
delete_channel::req, delete_channel::req,
edit_channel::req, edit_channel::req,
message_send::req, message_send::req,

View File

@@ -77,14 +77,14 @@ pub async fn req(user: User, username: String) -> Result<JsonValue> {
ClientboundNotification::UserRelationship { ClientboundNotification::UserRelationship {
id: user.id.clone(), id: user.id.clone(),
user: target_user, user: target_user,
status: RelationshipStatus::Friend status: RelationshipStatus::Friend,
} }
.publish(user.id.clone()); .publish(user.id.clone());
ClientboundNotification::UserRelationship { ClientboundNotification::UserRelationship {
id: target_id.to_string(), id: target_id.to_string(),
user, user,
status: RelationshipStatus::Friend status: RelationshipStatus::Friend,
} }
.publish(target_id.to_string()); .publish(target_id.to_string());
@@ -134,18 +134,18 @@ pub async fn req(user: User, username: String) -> Result<JsonValue> {
let user = user let user = user
.from_override(&target_user, RelationshipStatus::Incoming) .from_override(&target_user, RelationshipStatus::Incoming)
.await?; .await?;
ClientboundNotification::UserRelationship { ClientboundNotification::UserRelationship {
id: user.id.clone(), id: user.id.clone(),
user: target_user, user: target_user,
status: RelationshipStatus::Outgoing status: RelationshipStatus::Outgoing,
} }
.publish(user.id.clone()); .publish(user.id.clone());
ClientboundNotification::UserRelationship { ClientboundNotification::UserRelationship {
id: target_id.to_string(), id: target_id.to_string(),
user, user,
status: RelationshipStatus::Incoming status: RelationshipStatus::Incoming,
} }
.publish(target_id.to_string()); .publish(target_id.to_string());

View File

@@ -75,24 +75,24 @@ pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
) { ) {
Ok(_) => { Ok(_) => {
let target = target let target = target
.from_override(&user, RelationshipStatus::Friend) .from_override(&user, RelationshipStatus::Blocked)
.await?; .await?;
let user = user let user = user
.from_override(&target, RelationshipStatus::Friend) .from_override(&target, RelationshipStatus::BlockedOther)
.await?; .await?;
let target_id = target.id.clone(); let target_id = target.id.clone();
ClientboundNotification::UserRelationship { ClientboundNotification::UserRelationship {
id: user.id.clone(), id: user.id.clone(),
user: target, user: target,
status: RelationshipStatus::Blocked status: RelationshipStatus::Blocked,
} }
.publish(user.id.clone()); .publish(user.id.clone());
ClientboundNotification::UserRelationship { ClientboundNotification::UserRelationship {
id: target_id.clone(), id: target_id.clone(),
user, user,
status: RelationshipStatus::BlockedOther status: RelationshipStatus::BlockedOther,
} }
.publish(target_id); .publish(target_id);
@@ -145,14 +145,14 @@ pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
ClientboundNotification::UserRelationship { ClientboundNotification::UserRelationship {
id: user.id.clone(), id: user.id.clone(),
user: target, user: target,
status: RelationshipStatus::Blocked status: RelationshipStatus::Blocked,
} }
.publish(user.id.clone()); .publish(user.id.clone());
ClientboundNotification::UserRelationship { ClientboundNotification::UserRelationship {
id: target_id.clone(), id: target_id.clone(),
user, user,
status: RelationshipStatus::BlockedOther status: RelationshipStatus::BlockedOther,
} }
.publish(target_id); .publish(target_id);

View File

@@ -58,7 +58,7 @@ pub async fn req(
ClientboundNotification::UserUpdate { ClientboundNotification::UserUpdate {
id: user.id.clone(), id: user.id.clone(),
data: json!(data.0), data: json!(data.0),
clear: None clear: None,
} }
.publish(user.id.clone()); .publish(user.id.clone());

View File

@@ -1,6 +1,6 @@
use crate::{database::*, notifications::events::RemoveUserField};
use crate::notifications::events::ClientboundNotification; use crate::notifications::events::ClientboundNotification;
use crate::util::result::{Error, Result}; use crate::util::result::{Error, Result};
use crate::{database::*, notifications::events::RemoveUserField};
use mongodb::bson::{doc, to_document}; use mongodb::bson::{doc, to_document};
use rocket_contrib::json::Json; use rocket_contrib::json::Json;
@@ -25,7 +25,7 @@ pub struct Data {
profile: Option<UserProfileData>, profile: Option<UserProfileData>,
#[validate(length(min = 1, max = 128))] #[validate(length(min = 1, max = 128))]
avatar: Option<String>, avatar: Option<String>,
remove: Option<RemoveUserField> remove: Option<RemoveUserField>,
} }
#[patch("/<_ignore_id>", data = "<data>")] #[patch("/<_ignore_id>", data = "<data>")]
@@ -35,8 +35,12 @@ pub async fn req(user: User, data: Json<Data>, _ignore_id: String) -> Result<()>
data.validate() data.validate()
.map_err(|error| Error::FailedValidation { error })?; .map_err(|error| Error::FailedValidation { error })?;
if data.status.is_none() && data.profile.is_none() && data.avatar.is_none() && data.remove.is_none() { if data.status.is_none()
return Ok(()) && data.profile.is_none()
&& data.avatar.is_none()
&& data.remove.is_none()
{
return Ok(());
} }
let mut unset = doc! {}; let mut unset = doc! {};
@@ -49,14 +53,14 @@ pub async fn req(user: User, data: Json<Data>, _ignore_id: String) -> Result<()>
match remove { match remove {
RemoveUserField::ProfileContent => { RemoveUserField::ProfileContent => {
unset.insert("profile.content", 1); unset.insert("profile.content", 1);
}, }
RemoveUserField::ProfileBackground => { RemoveUserField::ProfileBackground => {
unset.insert("profile.background", 1); unset.insert("profile.background", 1);
remove_background = true; remove_background = true;
} }
RemoveUserField::StatusText => { RemoveUserField::StatusText => {
unset.insert("status.text", 1); unset.insert("status.text", 1);
}, }
RemoveUserField::Avatar => { RemoveUserField::Avatar => {
unset.insert("avatar", 1); unset.insert("avatar", 1);
remove_avatar = true; remove_avatar = true;
@@ -80,7 +84,8 @@ pub async fn req(user: User, data: Json<Data>, _ignore_id: String) -> Result<()>
} }
if let Some(attachment_id) = profile.background { if let Some(attachment_id) = profile.background {
let attachment = File::find_and_use(&attachment_id, "backgrounds", "user", &user.id).await?; let attachment =
File::find_and_use(&attachment_id, "backgrounds", "user", &user.id).await?;
set.insert( set.insert(
"profile.background", "profile.background",
to_document(&attachment).map_err(|_| Error::DatabaseError { to_document(&attachment).map_err(|_| Error::DatabaseError {
@@ -133,7 +138,7 @@ pub async fn req(user: User, data: Json<Data>, _ignore_id: String) -> Result<()>
ClientboundNotification::UserUpdate { ClientboundNotification::UserUpdate {
id: user.id.clone(), id: user.id.clone(),
data: json!({ "status": status }), data: json!({ "status": status }),
clear: None clear: None,
} }
.publish(user.id.clone()); .publish(user.id.clone());
} }
@@ -142,7 +147,7 @@ pub async fn req(user: User, data: Json<Data>, _ignore_id: String) -> Result<()>
ClientboundNotification::UserUpdate { ClientboundNotification::UserUpdate {
id: user.id.clone(), id: user.id.clone(),
data: json!({ "avatar": avatar }), data: json!({ "avatar": avatar }),
clear: None clear: None,
} }
.publish(user.id.clone()); .publish(user.id.clone());
} }
@@ -151,7 +156,7 @@ pub async fn req(user: User, data: Json<Data>, _ignore_id: String) -> Result<()>
ClientboundNotification::UserUpdate { ClientboundNotification::UserUpdate {
id: user.id.clone(), id: user.id.clone(),
data: json!({}), data: json!({}),
clear: Some(clear) clear: Some(clear),
} }
.publish(user.id.clone()); .publish(user.id.clone());
} }

View File

@@ -56,14 +56,14 @@ pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
ClientboundNotification::UserRelationship { ClientboundNotification::UserRelationship {
id: user.id.clone(), id: user.id.clone(),
user: target, user: target,
status: RelationshipStatus::None status: RelationshipStatus::None,
} }
.publish(user.id.clone()); .publish(user.id.clone());
ClientboundNotification::UserRelationship { ClientboundNotification::UserRelationship {
id: target_id.clone(), id: target_id.clone(),
user, user,
status: RelationshipStatus::None status: RelationshipStatus::None,
} }
.publish(target_id); .publish(target_id);

View File

@@ -85,14 +85,14 @@ pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
ClientboundNotification::UserRelationship { ClientboundNotification::UserRelationship {
id: user.id.clone(), id: user.id.clone(),
user: target, user: target,
status: RelationshipStatus::None status: RelationshipStatus::None,
} }
.publish(user.id.clone()); .publish(user.id.clone());
ClientboundNotification::UserRelationship { ClientboundNotification::UserRelationship {
id: target_id.clone(), id: target_id.clone(),
user: user, user: user,
status: RelationshipStatus::None status: RelationshipStatus::None,
} }
.publish(target_id); .publish(target_id);