1
0
mirror of https://gitlab.com/comunic/comunicapiv3 synced 2024-11-25 06:49:22 +00:00

Update dependencies

This commit is contained in:
Pierre HUBERT 2023-05-31 19:10:05 +02:00
parent c3f6c44abf
commit 3a38859544
206 changed files with 5160 additions and 2733 deletions

2296
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -8,20 +8,20 @@ edition = "2018"
[dependencies]
yaml-rust = "0.4.5"
mysql = "22.2.0"
mysql = "24.0.0"
actix = "0.13.0"
actix-web = "4.1.0"
actix-web = "4.3.1"
actix-files = "0.6.2"
actix-multipart = "0.4.0"
actix-web-actors = "4.1.0"
actix-http = "3.0.4"
serde = { version = "1.0.123", features = ["derive"] }
serde_json = "1.0.82"
futures = "0.3.21"
encoding_rs = "0.8.31"
percent-encoding = "2.1.0"
mailchecker = "5.0.0"
sha1 = "0.10.1"
actix-multipart = "0.6.0"
actix-web-actors = "4.2.0"
actix-http = "3.3.1"
serde = { version = "1.0.163", features = ["derive"] }
serde_json = "1.0.96"
futures = "0.3.28"
encoding_rs = "0.8.32"
percent-encoding = "2.2.0"
mailchecker = "5.0.9"
sha1 = "0.10.5"
rand = "0.8.5"
chrono = "0.4.19"
bytes = "1.2.1"
@ -29,14 +29,14 @@ image = "0.24.3"
kamadak-exif = "0.5.4"
lazy_static = "1.4.0"
mime_guess = "2.0.4"
pdf = "0.7.2"
pdf = "0.8.1"
regex = "1.6.0"
dashmap = "5.3.4"
reqwest = { version = "0.11.11", features = ["json"] }
webrtc-sdp = "0.3.9"
bcrypt = "0.13.0"
bcrypt = "0.14.0"
mp3-metadata = "0.3.4"
mp4 = "0.12.0"
mp4 = "0.13.0"
zip = "0.6.2"
webpage = "1.4.0"
gouth = "0.2.1"

View File

@ -13,7 +13,7 @@ use crate::api_data::friend_api::FriendAPI;
use crate::api_data::group_api::GroupApi;
use crate::api_data::post_api::PostAPI;
use crate::api_data::survey_response_api::SurveyResponseAPI;
use crate::api_data::user_info::{APIUserInfo, APIAdvancedInfo};
use crate::api_data::user_info::{APIAdvancedInfo, APIUserInfo};
use crate::api_data::user_like_api::UserLikeAPI;
use crate::data::account_export::AccountExport;
use crate::data::error::ResultBoxError;
@ -49,32 +49,34 @@ impl AccountExportAPI {
comments: CommentAPI::for_list(&export.comments, &curr_user_id.as_option())?,
likes: UserLikeAPI::for_list(&export.likes),
survey_responses: SurveyResponseAPI::for_list(&export.survey_responses),
all_conversation_messages: ConversationMessageAPI::for_list(&export.all_conversation_messages),
all_conversation_messages: ConversationMessageAPI::for_list(
&export.all_conversation_messages,
),
conversations_list: ConversationAPI::for_list(&export.conversations),
conversations_messages: export.conversation_messages
conversations_messages: export
.conversation_messages
.iter()
.map(|r| (r.0.id(), ConversationMessageAPI::for_list(r.1)))
.collect(),
friends_list: FriendAPI::from_list(&export.friends_list),
groups: export.groups
groups: export
.groups
.iter()
.map(groups_helper::get_info)
.collect::<Result<Vec<Group>, _>>()?
.iter()
.map(|g| GroupApi::new(g, curr_user_id.as_option()))
.collect::<Result<Vec<GroupApi>, _>>()?,
users_info: export.get_related_users_ids()?
users_info: export
.get_related_users_ids()?
.iter()
.map(user_helper::find_user_by_id)
.collect::<Result<Vec<User>, _>>()?
.iter()
.map(|u| {
APIUserInfo::new(&curr_user_id.as_option(), u)
.map(|r| (u.id.id(), r))
})
.map(|u| APIUserInfo::new(&curr_user_id.as_option(), u).map(|r| (u.id.id(), r)))
.collect::<Result<HashMap<u64, APIUserInfo>, _>>()?,
};
Ok(export)
}
}
}

View File

@ -8,22 +8,22 @@ use crate::utils::user_data_utils::user_data_url;
#[derive(Serialize)]
#[allow(non_snake_case)]
pub struct AccountImageSettingsAPI
{
pub struct AccountImageSettingsAPI {
has_image: bool,
image_url: String,
visibility: String,
}
impl AccountImageSettingsAPI {
pub fn new(user: &User) -> AccountImageSettingsAPI
{
AccountImageSettingsAPI
{
pub fn new(user: &User) -> AccountImageSettingsAPI {
AccountImageSettingsAPI {
has_image: user.has_account_image(),
image_url: user_data_url(user.account_image_path
.as_ref().unwrap_or(&DEFAULT_ACCOUNT_IMAGE.to_string())),
image_url: user_data_url(
user.account_image_path
.as_ref()
.unwrap_or(&DEFAULT_ACCOUNT_IMAGE.to_string()),
),
visibility: user.account_image_visibility.to_api(),
}
}
}
}

View File

@ -23,7 +23,14 @@ impl AdminAuthOptions {
pub fn new(admin: &Admin, keys: &[AdminKey]) -> Self {
Self {
reset_token: admin.reset_token.is_some(),
keys: keys.iter().map(|k| AuthKey { id: k.id, name: k.name.to_string(), password: k.password.is_some() }).collect(),
keys: keys
.iter()
.map(|k| AuthKey {
id: k.id,
name: k.name.to_string(),
password: k.password.is_some(),
})
.collect(),
}
}
}
}

View File

@ -8,11 +8,11 @@ use serde::Serialize;
#[derive(Serialize)]
pub struct AdminAuthSuccess {
token: String
token: String,
}
impl AdminAuthSuccess {
pub fn new(t: String) -> Self {
Self { token: t }
}
}
}

View File

@ -11,4 +11,4 @@ impl AdminCreatedPasswordResetLinkApi {
pub fn new(url: String) -> Self {
Self { url }
}
}
}

View File

@ -15,4 +15,4 @@ impl AdminIDAPI {
pub fn new(id: AdminID) -> Self {
Self { id: id.id() }
}
}
}

View File

@ -25,4 +25,4 @@ impl AdminInfoAPI {
roles: a.roles.iter().map(|r| r.to_id()).collect(),
}
}
}
}

View File

@ -22,4 +22,4 @@ impl AdminKeyAPI {
has_password: key.password.is_some(),
}
}
}
}

View File

@ -25,4 +25,4 @@ impl AdminLogAPI {
format: log.action.format_string(),
}
}
}
}

View File

@ -8,13 +8,11 @@ use crate::data::admin::AdminID;
#[derive(Serialize)]
pub struct AdminResCreateAccount {
id: u64
id: u64,
}
impl AdminResCreateAccount {
pub fn new(id: AdminID) -> Self {
Self {
id: id.id()
}
Self { id: id.id() }
}
}
}

View File

@ -18,4 +18,4 @@ impl AdminResCreateResetToken {
expire: token.expire,
}
}
}
}

View File

@ -21,4 +21,4 @@ impl AdminRoleDetailsAPI {
description: r.description,
}
}
}
}

View File

@ -10,7 +10,7 @@ pub struct AdminSearchUserResult {
first_name: String,
last_name: String,
email: String,
account_image: Option<String>
account_image: Option<String>,
}
impl AdminSearchUserResult {
@ -23,4 +23,4 @@ impl AdminSearchUserResult {
email: user.email,
}
}
}
}

View File

@ -53,4 +53,4 @@ impl AdminUserInfoAPI {
lang: user.lang,
}
}
}
}

View File

@ -4,13 +4,13 @@
pub mod admin_auth_options;
pub mod admin_auth_success;
pub mod admin_create_password_reset_link_api;
pub mod admin_id_api;
pub mod admin_info_api;
pub mod admin_keys_api;
pub mod admin_log_api;
pub mod admin_res_create_account;
pub mod admin_res_create_reset_token;
pub mod admin_role_api;
pub mod admin_res_create_account;
pub mod admin_log_api;
pub mod admin_search_user_result_api;
pub mod admin_user_info_api;
pub mod admin_create_password_reset_link_api;

View File

@ -9,8 +9,8 @@ use crate::data::config::conf;
use crate::data::error::ResultBoxError;
use crate::data::group::Group;
use crate::data::user::UserID;
use crate::helpers::{conversations_helper, groups_helper, likes_helper};
use crate::helpers::likes_helper::LikeType;
use crate::helpers::{conversations_helper, groups_helper, likes_helper};
#[derive(Serialize)]
pub struct AdvancedGroupApi {
@ -44,9 +44,13 @@ impl AdvancedGroupApi {
description: g.description.clone().unwrap_or("null".to_string()),
url: g.url.clone().unwrap_or("null".to_string()),
number_likes: likes_helper::count(g.id.id(), LikeType::GROUP)? as u64,
is_liking: likes_helper::is_liking(&user_id.unwrap_or(UserID::invalid()), g.id.id(), LikeType::GROUP)?,
is_liking: likes_helper::is_liking(
&user_id.unwrap_or(UserID::invalid()),
g.id.id(),
LikeType::GROUP,
)?,
conversations: ConversationAPI::for_list(&conversations),
is_forez_group: conf().forez_groups.contains(&g.id),
})
}
}
}

View File

@ -20,4 +20,4 @@ impl CallMemberInfo {
ready: call.ready,
}
}
}
}

View File

@ -21,4 +21,4 @@ impl CallPeerInterruptedStreamingAPI {
peerID: peer_id.id(),
}
}
}
}

View File

@ -20,4 +20,4 @@ impl CallPeerReadyAPI {
peerID: user_id.id(),
}
}
}
}

View File

@ -49,7 +49,10 @@ impl CommentAPI {
Ok(c_api)
}
pub fn for_list(l: &[Comment], curr_user_id: &Option<UserID>) -> ResultBoxError<Vec<CommentAPI>> {
pub fn for_list(
l: &[Comment],
curr_user_id: &Option<UserID>,
) -> ResultBoxError<Vec<CommentAPI>> {
l.iter().map(|c| Self::new(c, curr_user_id)).collect()
}
}
}

View File

@ -52,13 +52,19 @@ impl ConversationAPI {
id: conv.id.id(),
last_activity: conv.last_activity,
name: conv.name.clone(),
members: conv.members.iter().map(ConversationMembersAPI::new).collect(),
members: conv
.members
.iter()
.map(ConversationMembersAPI::new)
.collect(),
can_everyone_add_members: conv.can_everyone_add_members,
color: conv.color.clone(),
logo: conv.logo.as_ref().map(|s| user_data_url(s)),
group_id: conv.group_id.as_ref().map(|i| i.id()),
group_min_membership_level: conv.min_group_membership_level.as_ref()
group_min_membership_level: conv
.min_group_membership_level
.as_ref()
.map(|f| f.to_api()),
can_have_call: calls_helper::can_have_call(conv),
@ -70,4 +76,4 @@ impl ConversationAPI {
pub fn for_list(l: &Vec<Conversation>) -> Vec<Self> {
l.iter().map(Self::new).collect()
}
}
}

View File

@ -39,9 +39,9 @@ impl ConversationMessageAPI {
url: user_data_url(&file.path.clone()),
size: file.size,
name: file.name.clone(),
thumbnail: file.thumbnail.as_ref().map(|u|user_data_url(u)),
thumbnail: file.thumbnail.as_ref().map(|u| user_data_url(u)),
r#type: file.r#type.clone(),
})
}),
};
let server_message = match &msg.server_message {
@ -57,7 +57,10 @@ impl ConversationMessageAPI {
ConversationServerMessageType::UserAddedAnotherUserToConversation(msg) => {
value.insert("type".to_string(), Value::from("user_added_another"));
value.insert("user_who_added".to_string(), Value::from(msg.user_who_added.id()));
value.insert(
"user_who_added".to_string(),
Value::from(msg.user_who_added.id()),
);
value.insert("user_added".to_string(), Value::from(msg.user_added.id()));
}
@ -68,8 +71,14 @@ impl ConversationMessageAPI {
ConversationServerMessageType::UserRemovedFromConversation(msg) => {
value.insert("type".to_string(), Value::from("user_removed_another"));
value.insert("user_who_removed".to_string(), Value::from(msg.user_who_removed.id()));
value.insert("user_removed".to_string(), Value::from(msg.user_removed.id()));
value.insert(
"user_who_removed".to_string(),
Value::from(msg.user_who_removed.id()),
);
value.insert(
"user_removed".to_string(),
Value::from(msg.user_removed.id()),
);
}
}
@ -90,8 +99,6 @@ impl ConversationMessageAPI {
/// Turn a list of conversation messages into API entries
pub fn for_list(l: &Vec<ConversationMessage>) -> Vec<ConversationMessageAPI> {
l.iter()
.map(|m| ConversationMessageAPI::new(m))
.collect()
l.iter().map(|m| ConversationMessageAPI::new(m)).collect()
}
}
}

View File

@ -6,13 +6,11 @@ use crate::data::user::UserID;
#[derive(Serialize, Deserialize)]
#[allow(non_snake_case)]
pub struct CurrentUserID {
userID: u64
userID: u64,
}
impl CurrentUserID {
pub fn new(id: &UserID) -> CurrentUserID {
CurrentUserID {
userID: id.id()
}
CurrentUserID { userID: id.id() }
}
}
}

View File

@ -25,4 +25,4 @@ impl CustomEmojiAPI {
url: user_data_url(&custom_emoji.path),
}
}
}
}

View File

@ -1,5 +1,5 @@
//! # Data conservation settings API object
//!
//!
//! @author Pierre Hubert
use serde::Serialize;
@ -26,4 +26,4 @@ impl DataConservationSettingsAPI {
likes_lifetime: user.delete_likes_after,
}
}
}
}

View File

@ -10,7 +10,9 @@ pub trait EntitiesConstructor {
/// Parse a list of it
fn for_list(l: &[Self::Item]) -> Vec<Self>
where Self: std::marker::Sized {
where
Self: std::marker::Sized,
{
l.iter().map(Self::new).collect()
}
}
}

View File

@ -32,4 +32,4 @@ impl FriendAPI {
pub fn from_list(l: &Vec<Friend>) -> Vec<FriendAPI> {
l.iter().map(Self::new).collect()
}
}
}

View File

@ -24,4 +24,4 @@ impl FriendshipStatusAPI {
following: status.following,
}
}
}
}

View File

@ -46,4 +46,4 @@ impl GeneralSettingsAPI {
location: user.location.clone(),
}
}
}
}

View File

@ -29,8 +29,6 @@ impl GlobalSearchResultAPI {
/// Construct a list of results
pub fn for_list(l: &Vec<GlobalSearchResult>) -> Vec<GlobalSearchResultAPI> {
l.iter()
.map(|f| Self::new(f))
.collect()
l.iter().map(|f| Self::new(f)).collect()
}
}
}

View File

@ -47,4 +47,4 @@ impl GroupApi {
following: membership.following,
})
}
}
}

View File

@ -29,4 +29,4 @@ impl GroupMemberAPI {
pub fn for_list(l: &Vec<GroupMember>) -> Vec<GroupMemberAPI> {
l.iter().map(Self::new).collect()
}
}
}

View File

@ -11,7 +11,7 @@ pub struct InnerHTTPError {
#[derive(Serialize)]
pub struct HttpError {
pub error: InnerHTTPError
pub error: InnerHTTPError,
}
impl HttpError {
@ -21,7 +21,7 @@ impl HttpError {
error: InnerHTTPError {
code,
message: message.to_string(),
}
},
}
}
@ -44,4 +44,4 @@ impl HttpError {
pub fn forbidden(message: &str) -> HttpError {
HttpError::new(401, message)
}
}
}

View File

@ -22,4 +22,4 @@ impl JoinedCallMessage {
userID: user_id.id(),
}
}
}
}

View File

@ -15,7 +15,7 @@ pub struct LanguageSettingsAPI {
impl LanguageSettingsAPI {
pub fn new(user: &User) -> LanguageSettingsAPI {
LanguageSettingsAPI {
lang: user.lang.clone()
lang: user.lang.clone(),
}
}
}
}

View File

@ -22,4 +22,4 @@ impl LeftCallMessage {
userID: user_id.id(),
}
}
}
}

View File

@ -3,18 +3,19 @@
//! true => 1
//! false => 0
use serde::{Serialize, Serializer};
/// Special implementation of conversation name (false if none / the name otherwise)
pub struct LegacyBool(pub bool);
impl Serialize for LegacyBool {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where
S: Serializer {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where
S: Serializer,
{
match &self.0 {
true => serializer.serialize_i8(1),
false => serializer.serialize_i8(0),
}
}
}
}

View File

@ -27,8 +27,6 @@ impl UnreadConversationAPI {
/// Turn a list of unread conversation into API conversations
pub fn for_list(l: &Vec<ConvID>) -> Res<Vec<UnreadConversationAPI>> {
l.iter()
.map(|row| Self::new(row.clone()))
.collect()
l.iter().map(|row| Self::new(row.clone())).collect()
}
}
}

View File

@ -11,7 +11,7 @@ struct LoginTokens {
#[derive(Serialize, Deserialize)]
pub struct LoginSuccess {
token: String
token: String,
}
impl LoginSuccess {
@ -20,4 +20,4 @@ impl LoginSuccess {
token: token.to_string(),
}
}
}
}

View File

@ -9,68 +9,68 @@
pub mod admin;
pub mod server_config;
pub mod http_error;
pub mod login_success;
pub mod current_user_id;
pub mod user_mail_address;
pub mod user_info;
pub mod custom_emoji;
pub mod res_find_user_by_virtual_directory;
pub mod res_find_virtual_directory;
pub mod res_create_conversation;
pub mod conversation_api;
mod legacy_api_bool;
pub mod res_find_private_conversations;
pub mod conversation_message_api;
pub mod res_count_unread_conversations;
pub mod list_unread_conversations_api;
pub mod global_search_result_api;
pub mod res_create_group;
pub mod group_api;
pub mod account_export_api;
pub mod account_image_settings_api;
pub mod advanced_group_api;
pub mod res_change_group_logo;
pub mod group_member_api;
pub mod call_member_info;
pub mod call_peer_interrupted_streaming;
pub mod call_peer_ready;
pub mod comment_api;
pub mod conversation_api;
pub mod conversation_message_api;
pub mod current_user_id;
pub mod custom_emoji;
pub mod data_conservation_settings_api;
pub mod entities_constructor;
pub mod friend_api;
pub mod friendship_status_api;
pub mod post_api;
pub mod survey_choice_api;
pub mod survey_api;
pub mod comment_api;
pub mod res_create_post;
pub mod posts_targets_api;
pub mod res_create_comment;
pub mod res_number_unread_notifications;
pub mod res_count_all_unreads;
pub mod notification_api;
pub mod user_membership_api;
mod type_container_api;
pub mod res_check_email_exists;
pub mod res_check_security_questions_exists;
pub mod res_get_security_questions;
pub mod res_check_security_answers;
pub mod account_export_api;
pub mod user_like_api;
pub mod survey_response_api;
pub mod entities_constructor;
pub mod general_settings_api;
pub mod language_settings_api;
pub mod security_settings_api;
pub mod account_image_settings_api;
pub mod data_conservation_settings_api;
pub mod res_create_custom_emoji;
pub mod res_get_ws_token;
pub mod user_calls_config;
pub mod global_search_result_api;
pub mod group_api;
pub mod group_member_api;
pub mod http_error;
pub mod joined_call_message;
pub mod call_member_info;
pub mod language_settings_api;
pub mod left_call_message;
mod legacy_api_bool;
pub mod list_unread_conversations_api;
pub mod login_success;
pub mod new_call_signal;
pub mod call_peer_ready;
pub mod call_peer_interrupted_streaming;
pub mod res_check_password_token;
pub mod removed_user_from_conv_message;
pub mod user_is_writing_message_in_conversation;
pub mod res_create_conversation_for_group;
pub mod notification_api;
pub mod notification_settings_api;
pub mod post_api;
pub mod posts_targets_api;
pub mod push_notifications_status_api;
pub mod submit_report_result_api;
pub mod removed_user_from_conv_message;
pub mod res_change_group_logo;
pub mod res_check_email_exists;
pub mod res_check_password_token;
pub mod res_check_security_answers;
pub mod res_check_security_questions_exists;
pub mod res_count_all_unreads;
pub mod res_count_unread_conversations;
pub mod res_create_comment;
pub mod res_create_conversation;
pub mod res_create_conversation_for_group;
pub mod res_create_custom_emoji;
pub mod res_create_group;
pub mod res_create_post;
pub mod res_find_private_conversations;
pub mod res_find_user_by_virtual_directory;
pub mod res_find_virtual_directory;
pub mod res_get_security_questions;
pub mod res_get_ws_token;
pub mod res_number_unread_notifications;
pub mod security_settings_api;
pub mod server_config;
pub mod submit_report_result_api;
pub mod survey_api;
pub mod survey_choice_api;
pub mod survey_response_api;
mod type_container_api;
pub mod user_calls_config;
pub mod user_info;
pub mod user_is_writing_message_in_conversation;
pub mod user_like_api;
pub mod user_mail_address;
pub mod user_membership_api;

View File

@ -24,4 +24,4 @@ impl NewCallSignalAPI {
data: serde_json::from_str(data)?,
})
}
}
}

View File

@ -43,4 +43,4 @@ impl NotificationAPI {
pub fn for_list(l: &[Notification]) -> Vec<NotificationAPI> {
l.iter().map(Self::new).collect()
}
}
}

View File

@ -19,4 +19,4 @@ impl NotificationSettingsAPI {
allow_notifications_sound: user.allow_notif_sound,
}
}
}
}

View File

@ -8,8 +8,8 @@ use crate::api_data::survey_api::SurveyAPI;
use crate::data::error::ResultBoxError;
use crate::data::post::{Post, PostKind};
use crate::data::user::UserID;
use crate::helpers::{comments_helper, likes_helper, posts_helper, survey_helper};
use crate::helpers::likes_helper::LikeType;
use crate::helpers::{comments_helper, likes_helper, posts_helper, survey_helper};
use crate::utils::user_data_utils::user_data_url;
#[derive(Serialize)]
@ -113,8 +113,9 @@ impl PostAPI {
PostKind::POST_KIND_COUNTDOWN(time_end) => post.time_end = Some(*time_end),
PostKind::POST_KIND_SURVEY =>
post.data_survey = Some(SurveyAPI::new(&survey_helper::get_info(p.id)?, *user)?),
PostKind::POST_KIND_SURVEY => {
post.data_survey = Some(SurveyAPI::new(&survey_helper::get_info(p.id)?, *user)?)
}
PostKind::POST_KIND_YOUTUBE(id) => {
post.file_path = Some(id.clone());
@ -133,4 +134,4 @@ impl PostAPI {
pub fn for_list(l: &[Post], user_id: Option<UserID>) -> ResultBoxError<Vec<PostAPI>> {
l.iter().map(|p| Self::new(p, &user_id)).collect()
}
}
}

View File

@ -19,4 +19,4 @@ impl PostsTargets {
groups: g.iter().map(|f| f.id()).collect(),
}
}
}
}

View File

@ -19,13 +19,15 @@ impl PushNotificationsStatusAPI {
PushNotificationToken::NONE => "disabled",
PushNotificationToken::INDEPENDENT(_) => "independent",
PushNotificationToken::FIREBASE(_) => "firebase",
}.to_string(),
}
.to_string(),
independent_push_url: match (t, &conf().independent_push_service) {
(PushNotificationToken::INDEPENDENT(i), Some(conf)) =>
Some(conf.public_url.replace("{TOKEN_URL}", i)),
(PushNotificationToken::INDEPENDENT(i), Some(conf)) => {
Some(conf.public_url.replace("{TOKEN_URL}", i))
}
_ => None,
},
}
}
}
}

View File

@ -20,4 +20,4 @@ impl RemovedUserFromConversationMessage {
conv_id: conv_id.id(),
}
}
}
}

View File

@ -19,4 +19,4 @@ impl ResChangeGroupLogo {
url: user_data_url(path),
}
}
}
}

View File

@ -5,11 +5,11 @@ use serde::Serialize;
#[derive(Serialize)]
pub struct ResCheckEmailExists {
exists: bool
exists: bool,
}
impl ResCheckEmailExists {
pub fn new(exists: bool) -> ResCheckEmailExists {
ResCheckEmailExists { exists }
}
}
}

View File

@ -21,4 +21,4 @@ impl ResCheckPasswordToken {
mail: user.email.to_string(),
}
}
}
}

View File

@ -7,11 +7,11 @@ use serde::Serialize;
#[derive(Serialize)]
pub struct ResCheckSecurityAnswers {
reset_token: String
reset_token: String,
}
impl ResCheckSecurityAnswers {
pub fn new(reset_token: String) -> ResCheckSecurityAnswers {
ResCheckSecurityAnswers { reset_token }
}
}
}

View File

@ -5,11 +5,11 @@ use serde::Serialize;
#[derive(Serialize)]
pub struct ResCheckSecurityQuestionsExists {
defined: bool
defined: bool,
}
impl ResCheckSecurityQuestionsExists {
pub fn new(defined: bool) -> ResCheckSecurityQuestionsExists {
ResCheckSecurityQuestionsExists { defined }
}
}
}

View File

@ -20,11 +20,17 @@ pub struct ResCountAllUnread {
}
impl ResCountAllUnread {
pub fn new(notifications: u64, conversations: u64, friends_requests: Option<u64>) -> ResCountAllUnread {
pub fn new(
notifications: u64,
conversations: u64,
friends_requests: Option<u64>,
) -> ResCountAllUnread {
ResCountAllUnread {
notifications,
conversations,
friends: friends_requests.map(|n| CountFriendsRequests { friends_requests: n }),
friends: friends_requests.map(|n| CountFriendsRequests {
friends_requests: n,
}),
}
}
}
}

View File

@ -5,14 +5,12 @@ use serde::Serialize;
#[derive(Serialize)]
pub struct ResultCountUnreadConversations {
nb_unread: usize
nb_unread: usize,
}
impl ResultCountUnreadConversations {
/// Generate an new instance
pub fn new(count: usize) -> ResultCountUnreadConversations {
ResultCountUnreadConversations {
nb_unread: count
}
ResultCountUnreadConversations { nb_unread: count }
}
}
}

View File

@ -17,4 +17,4 @@ impl ResCreateComment {
commentID: comment_id,
}
}
}
}

View File

@ -2,8 +2,8 @@
//!
//! @author Pierre Hubert
use serde::{Serialize};
use crate::data::conversation::ConvID;
use serde::Serialize;
#[derive(Serialize)]
#[allow(non_snake_case)]
@ -20,4 +20,4 @@ impl ResCreateConversation {
success: "The conversation was successfully created!".to_string(),
}
}
}
}

View File

@ -8,13 +8,13 @@ use crate::data::conversation::ConvID;
#[derive(Serialize)]
pub struct ResCreateConversationForGroup {
conv_id: u64
conv_id: u64,
}
impl ResCreateConversationForGroup {
pub fn new(conv_id: ConvID) -> Self {
Self {
conv_id: conv_id.id()
conv_id: conv_id.id(),
}
}
}
}

View File

@ -7,11 +7,11 @@ use serde::Serialize;
#[allow(non_snake_case)]
#[derive(Serialize)]
pub struct ResCreateCustomEmoji {
emojiID: u64
emojiID: u64,
}
impl ResCreateCustomEmoji {
pub fn new(emoji_id: u64) -> ResCreateCustomEmoji {
ResCreateCustomEmoji { emojiID: emoji_id }
}
}
}

View File

@ -20,4 +20,4 @@ impl GroupCreationResult {
id: id.id(),
}
}
}
}

View File

@ -9,14 +9,14 @@ use crate::data::conversation::ConvID;
#[derive(Serialize)]
#[allow(non_snake_case)]
pub struct ResFindPrivateConversations {
conversationsID: Vec<u64>
conversationsID: Vec<u64>,
}
impl ResFindPrivateConversations {
/// Construct a new instance of this structure
pub fn new(list: Vec<ConvID>) -> ResFindPrivateConversations {
ResFindPrivateConversations {
conversationsID: list.iter().map(|i| i.id()).collect()
conversationsID: list.iter().map(|i| i.id()).collect(),
}
}
}
}

View File

@ -5,18 +5,17 @@
use crate::data::user::UserID;
use serde::Serialize;
#[derive(Serialize)]
#[allow(non_snake_case)]
pub struct FindUserByVirtualDirectoryAPIResult {
userID: u64
userID: u64,
}
impl FindUserByVirtualDirectoryAPIResult {
/// Construct a new `FindUserByVirtualDirectoryAPIResult` instance
pub fn new(user_id: UserID) -> FindUserByVirtualDirectoryAPIResult {
FindUserByVirtualDirectoryAPIResult {
userID: user_id.id()
userID: user_id.id(),
}
}
}
}

View File

@ -2,10 +2,10 @@
//!
//! @author Pierre Hubert
use serde::{Serialize};
use crate::data::error::ResultBoxError;
use crate::data::user::User;
use crate::data::group_id::GroupID;
use crate::data::user::User;
use serde::Serialize;
#[derive(Serialize)]
pub struct ResultFindVirtualDirectory {
@ -15,16 +15,24 @@ pub struct ResultFindVirtualDirectory {
impl ResultFindVirtualDirectory {
/// Construct a new instance
pub fn new(user: ResultBoxError<User>, group: ResultBoxError<GroupID>) -> ResultFindVirtualDirectory {
pub fn new(
user: ResultBoxError<User>,
group: ResultBoxError<GroupID>,
) -> ResultFindVirtualDirectory {
match (user, group) {
// User
(Ok(u), _) => ResultFindVirtualDirectory { kind: "user".to_string(), id: u.id.id() },
(Ok(u), _) => ResultFindVirtualDirectory {
kind: "user".to_string(),
id: u.id.id(),
},
// Group
(_, Ok(g)) => ResultFindVirtualDirectory { kind: "group".to_string(), id: g.id() },
(_, Ok(g)) => ResultFindVirtualDirectory {
kind: "group".to_string(),
id: g.id(),
},
_ => unreachable!()
_ => unreachable!(),
}
}
}
}

View File

@ -19,4 +19,4 @@ impl ResGetSecurityQuestions {
ResGetSecurityQuestions { questions }
}
}
}

View File

@ -12,4 +12,4 @@ impl ResGetWsToken {
pub fn new(token: String) -> Self {
ResGetWsToken { token }
}
}
}

View File

@ -6,11 +6,11 @@ use serde::Serialize;
#[derive(Serialize)]
pub struct ResNumberUnreadNotifications {
number: u64
number: u64,
}
impl ResNumberUnreadNotifications {
pub fn new(number: u64) -> ResNumberUnreadNotifications {
ResNumberUnreadNotifications { number }
}
}
}

View File

@ -26,4 +26,4 @@ impl SecuritySettingsAPI {
security_answer_2: user.security_answer_2.clone().unwrap_or_default(),
}
}
}
}

View File

@ -5,12 +5,23 @@ use std::collections::HashMap;
use serde::Serialize;
use crate::constants::{conservation_policy, MIN_SUPPORTED_MOBILE_VERSION, password_policy, reports};
use crate::constants::accounts_info_policy::{MAX_FIRST_NAME_LENGTH, MAX_LAST_NAME_LENGTH, MAX_LOCATION_LENGTH, MIN_FIRST_NAME_LENGTH, MIN_LAST_NAME_LENGTH};
use crate::constants::conversations::{ALLOWED_CONVERSATION_FILES_TYPES, CONVERSATION_FILES_MAX_SIZE, CONVERSATION_WRITING_EVENT_INTERVAL, CONVERSATION_WRITING_EVENT_LIFETIME, MAX_CONV_IMAGE_MESSAGE_WIDTH, MAX_CONV_LOGO_HEIGHT, MAX_CONV_LOGO_WIDTH, MAX_CONV_MESSAGE_THUMBNAIL_HEIGHT, MAX_CONV_MESSAGE_THUMBNAIL_WIDTH, MAX_CONVERSATION_MESSAGE_LENGTH, MAX_CONVERSATION_NAME_LENGTH, MIN_CONVERSATION_MESSAGE_LENGTH};
use crate::constants::accounts_info_policy::{
MAX_FIRST_NAME_LENGTH, MAX_LAST_NAME_LENGTH, MAX_LOCATION_LENGTH, MIN_FIRST_NAME_LENGTH,
MIN_LAST_NAME_LENGTH,
};
use crate::constants::conversations::{
ALLOWED_CONVERSATION_FILES_TYPES, CONVERSATION_FILES_MAX_SIZE,
CONVERSATION_WRITING_EVENT_INTERVAL, CONVERSATION_WRITING_EVENT_LIFETIME,
MAX_CONVERSATION_MESSAGE_LENGTH, MAX_CONVERSATION_NAME_LENGTH, MAX_CONV_IMAGE_MESSAGE_WIDTH,
MAX_CONV_LOGO_HEIGHT, MAX_CONV_LOGO_WIDTH, MAX_CONV_MESSAGE_THUMBNAIL_HEIGHT,
MAX_CONV_MESSAGE_THUMBNAIL_WIDTH, MIN_CONVERSATION_MESSAGE_LENGTH,
};
use crate::constants::reports::CAN_USER_REPORT_ITS_OWN_CONTENT;
use crate::constants::{
conservation_policy, password_policy, reports, MIN_SUPPORTED_MOBILE_VERSION,
};
use crate::data::api_client::APIClient;
use crate::data::config::{Banner, conf};
use crate::data::config::{conf, Banner};
use crate::data::report::REPORT_CAUSES;
#[derive(Serialize)]
@ -108,7 +119,12 @@ impl ServerConfig {
play_store_url: &conf().play_store_url,
android_direct_download_url: conf().android_direct_download_url.clone(),
banner: match conf().banner.as_ref().map(|b| b.is_visible()).unwrap_or(false) {
banner: match conf()
.banner
.as_ref()
.map(|b| b.is_visible())
.unwrap_or(false)
{
true => conf().banner.as_ref(),
false => None,
},
@ -130,11 +146,14 @@ impl ServerConfig {
},
data_conservation_policy: DataConservationPolicy {
min_inactive_account_lifetime: conservation_policy::MIN_INACTIVE_ACCOUNT_LIFETIME.as_secs(),
min_notification_lifetime: conservation_policy::MIN_NOTIFICATIONS_LIFETIME.as_secs(),
min_inactive_account_lifetime: conservation_policy::MIN_INACTIVE_ACCOUNT_LIFETIME
.as_secs(),
min_notification_lifetime: conservation_policy::MIN_NOTIFICATIONS_LIFETIME
.as_secs(),
min_comments_lifetime: conservation_policy::MIN_COMMENTS_LIFETIME.as_secs(),
min_posts_lifetime: conservation_policy::MIN_POSTS_LIFETIME.as_secs(),
min_conversation_messages_lifetime: conservation_policy::MIN_CONVERSATION_MESSAGES_LIFETIME.as_secs(),
min_conversation_messages_lifetime:
conservation_policy::MIN_CONVERSATION_MESSAGES_LIFETIME.as_secs(),
min_likes_lifetime: conservation_policy::MIN_LIKES_LIFETIME.as_secs(),
},
@ -164,17 +183,17 @@ impl ServerConfig {
report_policy: match conf().allow_reporting {
true => Some(ReportPolicy {
causes: REPORT_CAUSES.iter().map(|r| ReportCause {
id: r.id().id(),
label: HashMap::from([
("fr", r.label_fr),
("en", r.label_en)
]),
}).collect(),
causes: REPORT_CAUSES
.iter()
.map(|r| ReportCause {
id: r.id().id(),
label: HashMap::from([("fr", r.label_fr), ("en", r.label_en)]),
})
.collect(),
max_comment_length: reports::MAX_COMMENT_LENGTH,
can_user_report_his_own_content: CAN_USER_REPORT_ITS_OWN_CONTENT,
}),
false => None
false => None,
},
}
}

View File

@ -9,4 +9,4 @@ impl SubmitReportResultApi {
pub fn new(r: ReportID) -> Self {
Self { report_id: r.0 }
}
}
}

View File

@ -44,4 +44,4 @@ impl SurveyAPI {
allowNewChoices: s.allow_new_choices,
})
}
}
}

View File

@ -27,7 +27,9 @@ impl SurveyChoiceAPI {
pub fn for_list(c: &[SurveyChoice]) -> HashMap<u64, SurveyChoiceAPI> {
let mut map = HashMap::with_capacity(c.len());
c.iter().for_each(|c| { map.insert(c.id, Self::new(c)); });
c.iter().for_each(|c| {
map.insert(c.id, Self::new(c));
});
map
}
}
}

View File

@ -28,4 +28,4 @@ impl EntitiesConstructor for SurveyResponseAPI {
choiceID: r.choice_id,
}
}
}
}

View File

@ -1,8 +1,8 @@
//! Use this structure for all structures that needs a "type" field
//!
//! @author Pierre Hubert
use serde::{Serialize, Serializer};
use serde::ser::SerializeMap;
use serde::{Serialize, Serializer};
pub struct TypeContainerAPI {
t: String,
@ -15,10 +15,12 @@ impl TypeContainerAPI {
}
impl Serialize for TypeContainerAPI {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where
S: Serializer {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(Some(1))?;
map.serialize_entry("type", &self.t)?;
map.end()
}
}
}

View File

@ -14,6 +14,8 @@ pub struct UserCallsConfig {
impl UserCallsConfig {
pub fn new(conf: &RtcRelayConfig) -> Self {
Self { iceServers: conf.ice_servers.clone() }
Self {
iceServers: conf.ice_servers.clone(),
}
}
}
}

View File

@ -5,10 +5,12 @@ use serde::Serialize;
use crate::api_data::custom_emoji::CustomEmojiAPI;
use crate::data::error::ResultBoxError;
use crate::data::user::{User, UserID, UserPageVisibility};
use crate::data::user::AccountImageVisibility::{COMUNIC_USERS, EVERYONE};
use crate::helpers::{background_image_helper, custom_emojies_helper, friends_helper, likes_helper, user_helper};
use crate::data::user::{User, UserID, UserPageVisibility};
use crate::helpers::likes_helper::LikeType;
use crate::helpers::{
background_image_helper, custom_emojies_helper, friends_helper, likes_helper, user_helper,
};
use crate::utils::user_data_utils::user_data_url;
#[derive(Serialize)]
@ -65,7 +67,10 @@ impl APIUserInfo {
}
/// Get advanced user information
pub fn new_advanced_info(user_id: &Option<UserID>, info: &User) -> ResultBoxError<APIAdvancedInfo> {
pub fn new_advanced_info(
user_id: &Option<UserID>,
info: &User,
) -> ResultBoxError<APIAdvancedInfo> {
let user = APIUserInfo::new(&user_id, info)?;
let curr_user_id = user_id.clone().unwrap_or(UserID::new(0));
let signed_in = user_id.is_some();
@ -73,11 +78,15 @@ impl APIUserInfo {
// Check if we can return the number of friends of the user
let number_friends = if info.public_friends_list || curr_user_id == info.id {
friends_helper::count_friends(&info.id)?
} else { 0 };
} else {
0
};
let likes_page = if signed_in {
likes_helper::is_liking(&curr_user_id, info.id.id(), LikeType::USER)?
} else { false };
} else {
false
};
// Set advanced user information
Ok(APIAdvancedInfo {
@ -113,16 +122,17 @@ impl APIUserInfo {
return user_account_image;
}
if user_id.is_none() { // User is not signed in
if user_id.is_none() {
// User is not signed in
return Ok(User::error_account_image_url());
}
if user.account_image_visibility == COMUNIC_USERS ||
friends_helper::are_friend(&user_id.clone().unwrap(), &user.id)? {
if user.account_image_visibility == COMUNIC_USERS
|| friends_helper::are_friend(&user_id.clone().unwrap(), &user.id)?
{
return user_account_image;
}
Ok(User::error_account_image_url())
}
}
}

View File

@ -19,4 +19,4 @@ impl UserIsWritingMessageInConversation {
conv_id: conv_id.id(),
}
}
}
}

View File

@ -30,4 +30,4 @@ impl UserLikeAPI {
pub fn for_list(l: &[UserLike]) -> Vec<Self> {
l.iter().map(Self::new).collect()
}
}
}

View File

@ -14,7 +14,7 @@ pub struct UserMailAddressAPI {
impl UserMailAddressAPI {
pub fn new(user: &User) -> Self {
Self {
mail: user.email.to_string()
mail: user.email.to_string(),
}
}
}
}

View File

@ -44,11 +44,11 @@ impl UserMembershipAPI {
friend: None,
last_activity: None,
conv: Some(ConversationAPI::new(conversation)),
}
},
}
}
pub fn for_list(l: &[UserMembership]) -> Vec<UserMembershipAPI> {
l.iter().map(Self::new).collect()
}
}
}

View File

@ -37,13 +37,11 @@ fn clean_up_thread_handler() {
/// Do the cleanup
async fn do_clean() -> Res {
// Clean old login tokens
account_helper::clean_up_old_access_tokens().await?;
// Automatic account cleanup
for user in user_helper::get_all_users()? {
// Clean old likes
likes_helper::clean_old_user_likes(&user)?;
@ -67,4 +65,4 @@ async fn do_clean() -> Res {
admin_log_helper::clean_old_logs()?;
Ok(())
}
}

View File

@ -209,25 +209,27 @@ pub mod conversations {
/// Allowed files type in conversations
pub const ALLOWED_CONVERSATION_FILES_TYPES: [&str; 18] = [
"image/png", "image/jpeg", "image/gif", "image/bmp",
"image/png",
"image/jpeg",
"image/gif",
"image/bmp",
"application/pdf",
"audio/mpeg",
"video/mp4",
"video/quicktime",
"application/zip",
// MS Office docs
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
// Open Office docs
"application/vnd.oasis.opendocument.text",
"application/vnd.oasis.opendocument.presentation",
"application/vnd.oasis.opendocument.spreadsheet",
// Source code docs (UTF-8 encoded)
"text/x-csrc", "text/plain", "text/x-c++src"
"text/x-csrc",
"text/plain",
"text/x-c++src",
];
/// File maximum size in conversations (10 Mb)
@ -267,7 +269,8 @@ pub mod accounts_info_policy {
}
/// Url where Firebase push notifications can be sent
pub const FIREBASE_PUSH_MESSAGE_URL: &str = "https://fcm.googleapis.com/v1/projects/{PROJECT_ID}/messages:send";
pub const FIREBASE_PUSH_MESSAGE_URL: &str =
"https://fcm.googleapis.com/v1/projects/{PROJECT_ID}/messages:send";
/// Reports constants
pub mod reports {
@ -313,6 +316,6 @@ pub mod admin {
id: "access_all_admins_logs",
name: "Access all admins logs",
description: "Allow the admin to access the action history (log) of all admins",
}
},
];
}
}

View File

@ -35,7 +35,10 @@ impl HttpRequestHandler {
}
/// Get the ID of the user associated with a password reset token
pub fn post_user_id_from_password_reset_token(&mut self, field: &str) -> ResultBoxError<UserID> {
pub fn post_user_id_from_password_reset_token(
&mut self,
field: &str,
) -> ResultBoxError<UserID> {
let token = self.post_string_opt(field, PASSWORD_RESET_TOKEN_LENGTH, true)?;
let user_id = self.ok_or_forbidden(
account_helper::get_user_id_from_password_reset_token(&token),
@ -48,7 +51,6 @@ impl HttpRequestHandler {
/// Create a new account
pub async fn create(r: &mut HttpRequestHandler) -> RequestResult {
// Get & check email
let email = r.post_email("emailAddress")?;
if account_helper::exists_mail(&email)? {
@ -77,13 +79,10 @@ pub async fn login_user(request: &mut HttpRequestHandler) -> RequestResult {
}
// Authenticate user
let token = account_helper::login_user(
&email, &password, request.api_client());
let token = account_helper::login_user(&email, &password, request.api_client());
match token {
Ok(t) => {
request.set_response(LoginSuccess::new(&t))
}
Ok(t) => request.set_response(LoginSuccess::new(&t)),
Err(e) => {
println!("Error on login: {}", e);
request.forbidden("Invalid email address / password!".to_string())
@ -122,14 +121,18 @@ pub async fn get_mail(r: &mut HttpRequestHandler) -> RequestResult {
pub async fn exists_mail(r: &mut HttpRequestHandler) -> RequestResult {
let email = r.post_email("email")?;
r.set_response(ResCheckEmailExists::new(account_helper::exists_mail(&email)?))
r.set_response(ResCheckEmailExists::new(account_helper::exists_mail(
&email,
)?))
}
/// Check out whether a given user has set security questions or not
pub async fn has_security_questions(r: &mut HttpRequestHandler) -> RequestResult {
let user = r.post_user_info_from_email("email")?;
r.set_response(ResCheckSecurityQuestionsExists::new(user.has_security_questions()))
r.set_response(ResCheckSecurityQuestionsExists::new(
user.has_security_questions(),
))
}
/// Get the security questions of a user
@ -151,17 +154,25 @@ pub async fn check_security_answers(r: &mut HttpRequestHandler) -> RequestResult
r.forbidden("Specified user has not setup security questions !".to_string())?;
}
let answers: Vec<String> = r.post_string_opt("answers", 3, true)?
let answers: Vec<String> = r
.post_string_opt("answers", 3, true)?
.split("&")
.map(|s| percent_decode_str(s).decode_utf8_lossy().to_lowercase().trim().to_string())
.map(|s| {
percent_decode_str(s)
.decode_utf8_lossy()
.to_lowercase()
.trim()
.to_string()
})
.collect::<Vec<String>>();
if answers.len() != 2 {
r.forbidden("Please specify two answers!".to_string())?;
}
if answers[0] != user.security_answer_1.unwrap().to_lowercase().trim() ||
answers[1] != user.security_answer_2.unwrap().to_lowercase().trim() {
if answers[0] != user.security_answer_1.unwrap().to_lowercase().trim()
|| answers[1] != user.security_answer_2.unwrap().to_lowercase().trim()
{
r.forbidden("Invalid security answers!".to_string())?;
}
@ -211,4 +222,4 @@ pub async fn delete_account(r: &mut HttpRequestHandler) -> RequestResult {
account_helper::delete(r.user_id_ref()?).await?;
r.success("Account deleted.")
}
}

View File

@ -2,7 +2,6 @@
//!
//! @author Pierre Hubert
use crate::api_data::admin::admin_auth_options::AdminAuthOptions;
use crate::api_data::admin::admin_auth_success::AdminAuthSuccess;
use crate::api_data::admin::admin_id_api::AdminIDAPI;
@ -14,8 +13,8 @@ use crate::data::admin::{NewAdmin, NewAdminGeneralSettings};
use crate::data::admin_action_log::AdminAction;
use crate::data::base_request_handler::BaseRequestHandler;
use crate::data::http_request_handler::HttpRequestHandler;
use crate::helpers::{admin_access_token_helper, admin_account_helper, admin_account_key_helper};
use crate::helpers::admin_log_helper::log_admin_action;
use crate::helpers::{admin_access_token_helper, admin_account_helper, admin_account_key_helper};
use crate::routes::RequestResult;
use crate::utils::date_utils::time;
@ -27,8 +26,15 @@ pub async fn create(r: &mut HttpRequestHandler) -> RequestResult {
let new_admin = NewAdmin { name, email };
let admin_id = admin_account_helper::create(&new_admin)?;
log_admin_action(r.admin_id()?, &r.remote_ip(),
AdminAction::CreatedAdmin { id: admin_id, name: new_admin.name, email: new_admin.email })?;
log_admin_action(
r.admin_id()?,
&r.remote_ip(),
AdminAction::CreatedAdmin {
id: admin_id,
name: new_admin.name,
email: new_admin.email,
},
)?;
r.set_response(AdminResCreateAccount::new(admin_id))
}
@ -58,8 +64,7 @@ pub async fn auth_with_reset_token(r: &mut HttpRequestHandler) -> RequestResult
let token = admin_access_token_helper::create(admin.id)?;
log_admin_action(admin.id, &r.remote_ip(),
AdminAction::AuthWithResetToken)?;
log_admin_action(admin.id, &r.remote_ip(), AdminAction::AuthWithResetToken)?;
r.set_response(AdminAuthSuccess::new(token))
}
@ -115,8 +120,15 @@ pub async fn update_general_settings(r: &mut HttpRequestHandler) -> RequestResul
email: new_email.to_string(),
})?;
log_admin_action(r.admin_id()?, &r.remote_ip(),
AdminAction::UpdatedAdminGeneralSettings { target: admin_id, new_name, new_email })?;
log_admin_action(
r.admin_id()?,
&r.remote_ip(),
AdminAction::UpdatedAdminGeneralSettings {
target: admin_id,
new_name,
new_email,
},
)?;
r.ok()
}
@ -131,8 +143,11 @@ pub async fn generate_reset_token(r: &mut HttpRequestHandler) -> RequestResult {
let token = admin_account_helper::create_new_reset_token(admin_id)?;
log_admin_action(r.admin_id()?, &r.remote_ip(),
AdminAction::GeneratedAdminResetToken { target: admin_id })?;
log_admin_action(
r.admin_id()?,
&r.remote_ip(),
AdminAction::GeneratedAdminResetToken { target: admin_id },
)?;
r.set_response(AdminResCreateResetToken::new(token))
}
}

View File

@ -2,7 +2,6 @@
//!
//! @author Pierre Hubert
use bcrypt::verify;
use webauthn_rs::prelude::Uuid;
@ -15,8 +14,11 @@ use crate::data::base_request_handler::BaseRequestHandler;
use crate::data::error::Res;
use crate::data::http_request_handler::HttpRequestHandler;
use crate::data::webauthn_config::get_wan;
use crate::helpers::{admin_access_token_helper, admin_account_helper, admin_account_key_helper, admin_key_authentication_challenges_helper, admin_key_registration_challenges_helper};
use crate::helpers::admin_log_helper::log_admin_action;
use crate::helpers::{
admin_access_token_helper, admin_account_helper, admin_account_key_helper,
admin_key_authentication_challenges_helper, admin_key_registration_challenges_helper,
};
use crate::routes::RequestResult;
impl HttpRequestHandler {
@ -27,12 +29,13 @@ impl HttpRequestHandler {
let admin = admin_account_helper::find_admin_by_email(&mail)?;
let keys = admin_account_key_helper::get_admin_keys(admin.id)?;
let key = keys.into_iter()
.find(|k| k.id == key_id);
let key = keys.into_iter().find(|k| k.id == key_id);
match key {
Some(key) => Ok(key),
None => Err(self.bad_request("The key is not associated with this account!".to_string()).unwrap_err())
None => Err(self
.bad_request("The key is not associated with this account!".to_string())
.unwrap_err()),
}
}
}
@ -47,21 +50,21 @@ pub async fn get_keys_list(r: &mut HttpRequestHandler) -> RequestResult {
let keys = admin_account_key_helper::get_admin_keys(admin_id)?;
r.set_response(keys.iter().map(AdminKeyAPI::new).collect::<Vec<AdminKeyAPI>>())
r.set_response(
keys.iter()
.map(AdminKeyAPI::new)
.collect::<Vec<AdminKeyAPI>>(),
)
}
/// Generate a challenge to register a new key
pub async fn challenge_register_key(r: &mut HttpRequestHandler) -> RequestResult {
let wan = get_wan();
let user_info = admin_account_helper::find_admin_by_id(r.admin_id()?)?;
let (res, state) = wan.start_passkey_registration(
Uuid::new_v4(),
&user_info.name,
&user_info.name,
None)?;
let (res, state) =
wan.start_passkey_registration(Uuid::new_v4(), &user_info.name, &user_info.name, None)?;
admin_key_registration_challenges_helper::set(r.admin_id()?, state)?;
@ -84,12 +87,15 @@ pub async fn register_key(r: &mut HttpRequestHandler) -> RequestResult {
let key_id = admin_account_key_helper::add_key(r.admin_id()?, &key_name, key, key_password)?;
log_admin_action(r.admin_id()?, &r.remote_ip(),
AdminAction::RegisteredAdminKey {
key_id,
key_name,
target: r.admin_id()?,
})?;
log_admin_action(
r.admin_id()?,
&r.remote_ip(),
AdminAction::RegisteredAdminKey {
key_id,
key_name,
target: r.admin_id()?,
},
)?;
r.ok()
}
@ -105,12 +111,15 @@ pub async fn delete_auth_key(r: &mut HttpRequestHandler) -> RequestResult {
for key in admin_account_key_helper::get_admin_keys(admin_id)? {
if key.id == key_id {
log_admin_action(r.admin_id()?, &r.remote_ip(),
AdminAction::DeletedAdminKey {
key_id,
key_name: key.name.to_string(),
target: admin_id,
})?;
log_admin_action(
r.admin_id()?,
&r.remote_ip(),
AdminAction::DeletedAdminKey {
key_id,
key_name: key.name.to_string(),
target: admin_id,
},
)?;
admin_account_key_helper::delete_key(key)?;
@ -125,8 +134,7 @@ pub async fn delete_auth_key(r: &mut HttpRequestHandler) -> RequestResult {
pub async fn challenge_auth_with_key(r: &mut HttpRequestHandler) -> RequestResult {
let key = r.post_admin_auth_key("mail", "key_id")?;
let (challenge_response, auth_state) =
get_wan().start_passkey_authentication(&[key.key])?;
let (challenge_response, auth_state) = get_wan().start_passkey_authentication(&[key.key])?;
admin_key_authentication_challenges_helper::set(key.id, auth_state)?;
@ -158,8 +166,14 @@ pub async fn auth_with_key(r: &mut HttpRequestHandler) -> RequestResult {
// Generate access token
let token = admin_access_token_helper::create(key.admin_id)?;
log_admin_action(key.admin_id, &r.remote_ip(),
AdminAction::AuthWithAccessKey { key: key.name, key_id: key.id })?;
log_admin_action(
key.admin_id,
&r.remote_ip(),
AdminAction::AuthWithAccessKey {
key: key.name,
key_id: key.id,
},
)?;
r.set_response(AdminAuthSuccess::new(token))
}
}

View File

@ -2,19 +2,20 @@
//!
//! @author Pierre Hubert
use crate::routes::RequestResult;
use crate::data::http_request_handler::HttpRequestHandler;
use crate::data::base_request_handler::BaseRequestHandler;
use crate::helpers::{admin_roles_helper, admin_log_helper};
use crate::constants::admin::AdminRole;
use crate::api_data::admin::admin_log_api::AdminLogAPI;
use crate::constants::admin::AdminRole;
use crate::data::base_request_handler::BaseRequestHandler;
use crate::data::http_request_handler::HttpRequestHandler;
use crate::helpers::{admin_log_helper, admin_roles_helper};
use crate::routes::RequestResult;
/// Get the list of logs of the user
pub async fn get_list(r: &mut HttpRequestHandler) -> RequestResult {
let logs = match admin_roles_helper::has_role(r.admin_id()?, AdminRole::ACCESS_ALL_ADMINS_LOGS)? {
let logs = match admin_roles_helper::has_role(r.admin_id()?, AdminRole::ACCESS_ALL_ADMINS_LOGS)?
{
true => admin_log_helper::get_all_admin_logs(),
false => admin_log_helper::get_admin_logs(r.admin_id()?)
false => admin_log_helper::get_admin_logs(r.admin_id()?),
}?;
r.set_response(logs.iter().map(AdminLogAPI::new).collect::<Vec<_>>())
}
}

View File

@ -3,7 +3,7 @@
//! @author Pierre Hubert
use crate::api_data::admin::admin_role_api::AdminRoleDetailsAPI;
use crate::constants::admin::{ADMIN_ROLES_LIST, AdminRole};
use crate::constants::admin::{AdminRole, ADMIN_ROLES_LIST};
use crate::data::admin_action_log::AdminAction;
use crate::data::base_request_handler::BaseRequestHandler;
use crate::data::http_request_handler::HttpRequestHandler;
@ -13,7 +13,8 @@ use crate::routes::RequestResult;
/// Get the list of roles embedded in the code
pub async fn get_list(r: &mut HttpRequestHandler) -> RequestResult {
let res = ADMIN_ROLES_LIST.iter()
let res = ADMIN_ROLES_LIST
.iter()
.map(AdminRoleDetailsAPI::new)
.collect::<Vec<AdminRoleDetailsAPI>>();
@ -32,14 +33,26 @@ pub async fn toggle(r: &mut HttpRequestHandler) -> RequestResult {
if !enable {
admin_roles_helper::remove_role(admin_id, role)?;
log_admin_action(r.admin_id()?, &r.remote_ip(),
AdminAction::RemoveAdminRole { target: admin_id, role: role_str })?;
log_admin_action(
r.admin_id()?,
&r.remote_ip(),
AdminAction::RemoveAdminRole {
target: admin_id,
role: role_str,
},
)?;
} else if !admin_roles_helper::has_role(admin_id, role)? {
admin_roles_helper::add_role(admin_id, role)?;
log_admin_action(r.admin_id()?, &r.remote_ip(),
AdminAction::AddAdminRole { target: admin_id, role: role_str })?;
log_admin_action(
r.admin_id()?,
&r.remote_ip(),
AdminAction::AddAdminRole {
target: admin_id,
role: role_str,
},
)?;
}
r.ok()
}
}

View File

@ -10,8 +10,8 @@ use crate::data::admin_action_log::AdminAction;
use crate::data::base_request_handler::BaseRequestHandler;
use crate::data::config::conf;
use crate::data::http_request_handler::HttpRequestHandler;
use crate::helpers::{account_helper, user_helper};
use crate::helpers::admin_log_helper::log_admin_action;
use crate::helpers::{account_helper, user_helper};
use crate::routes::RequestResult;
/// Search for user
@ -23,7 +23,12 @@ pub async fn search(r: &mut HttpRequestHandler) -> RequestResult {
let results = user_helper::search_user_admin(&name, &email, 50)?;
r.set_response(results.into_iter().map(AdminSearchUserResult::new).collect::<Vec<_>>())
r.set_response(
results
.into_iter()
.map(AdminSearchUserResult::new)
.collect::<Vec<_>>(),
)
}
/// Get information about a single user
@ -33,8 +38,14 @@ pub async fn get_single(r: &mut HttpRequestHandler) -> RequestResult {
let user_id = r.post_user_id("user_id")?;
let user = user_helper::find_user_by_id(&user_id)?;
log_admin_action(r.admin_id()?, &r.remote_ip(),
AdminAction::AccessUserPage { user_id, user_name: user.full_name() })?;
log_admin_action(
r.admin_id()?,
&r.remote_ip(),
AdminAction::AccessUserPage {
user_id,
user_name: user.full_name(),
},
)?;
r.set_response(AdminUserInfoAPI::new(user))
}
@ -49,19 +60,25 @@ pub async fn change_email_address(r: &mut HttpRequestHandler) -> RequestResult {
// We check if the email address is already used
if user_helper::find_user_by_email(&new_mail).is_ok() {
r.bad_request(format!("The email address {} is already attributed!", new_mail))?;
r.bad_request(format!(
"The email address {} is already attributed!",
new_mail
))?;
}
// Do the update
account_helper::set_email(user_id, &new_mail)?;
log_admin_action(r.admin_id()?, &r.remote_ip(),
AdminAction::ChangedEmailAddress {
user_id,
user_name: user.full_name(),
old_mail: user.email,
new_mail,
})?;
log_admin_action(
r.admin_id()?,
&r.remote_ip(),
AdminAction::ChangedEmailAddress {
user_id,
user_name: user.full_name(),
old_mail: user.email,
new_mail,
},
)?;
r.ok()
}
@ -76,8 +93,14 @@ pub async fn create_password_reset_link(r: &mut HttpRequestHandler) -> RequestRe
let token = account_helper::generate_password_reset_token(&user_id)?;
let reset_link = conf().password_reset_url.replace("{TOKEN}", &token);
log_admin_action(r.admin_id()?, &r.remote_ip(),
AdminAction::CreatePasswordRecoveryLink { user_id, user_name: user.full_name() })?;
log_admin_action(
r.admin_id()?,
&r.remote_ip(),
AdminAction::CreatePasswordRecoveryLink {
user_id,
user_name: user.full_name(),
},
)?;
r.set_response(AdminCreatedPasswordResetLinkApi::new(reset_link))
}
}

View File

@ -4,6 +4,6 @@
pub mod admin_account_controller;
pub mod admin_keys_controller;
pub mod admin_roles_controller;
pub mod admin_logs_controller;
pub mod admin_users_controller;
pub mod admin_roles_controller;
pub mod admin_users_controller;

View File

@ -13,7 +13,9 @@ use crate::api_data::new_call_signal::NewCallSignalAPI;
use crate::api_data::user_calls_config::UserCallsConfig;
use crate::controllers::user_ws_controller;
use crate::data::base_request_handler::BaseRequestHandler;
use crate::data::call_signal::{CallSignal, CloseCallStream, IceCandidate, NewUserCallSignal, SdpType, UserCallOfferRequest};
use crate::data::call_signal::{
CallSignal, CloseCallStream, IceCandidate, NewUserCallSignal, SdpType, UserCallOfferRequest,
};
use crate::data::config::conf;
use crate::data::conversation::ConvID;
use crate::data::error::{ExecError, Res};
@ -21,8 +23,8 @@ use crate::data::user::UserID;
use crate::data::user_ws_connection::{ActiveCall, UserWsConnection};
use crate::data::user_ws_message::UserWsMessage;
use crate::data::user_ws_request_handler::UserWsRequestHandler;
use crate::helpers::{calls_helper, conversations_helper, events_helper};
use crate::helpers::events_helper::Event;
use crate::helpers::{calls_helper, conversations_helper, events_helper};
use crate::routes::RequestResult;
impl UserWsRequestHandler {
@ -63,7 +65,8 @@ impl UserWsRequestHandler {
/// Get call information, if available
fn call_info(&mut self, call_id: &ConvID) -> Res<ActiveCall> {
let call = self.get_conn()
let call = self
.get_conn()
.active_call
.clone()
.ok_or(ExecError::new("No call found !"))?;
@ -76,7 +79,10 @@ impl UserWsRequestHandler {
}
/// Update call information
fn update_call<F>(&mut self, update: F) -> Res where F: FnOnce(&mut ActiveCall) {
fn update_call<F>(&mut self, update: F) -> Res
where
F: FnOnce(&mut ActiveCall),
{
self.update_conn(|conn| {
if let Some(call) = &mut conn.active_call {
update(call);
@ -95,8 +101,7 @@ pub async fn get_config(r: &mut UserWsRequestHandler) -> RequestResult {
}
if conf().is_rtc_relay_enabled() {
if let Some(conf) = conf().rtc_relay.as_ref()
{
if let Some(conf) = conf().rtc_relay.as_ref() {
return r.set_response(UserCallsConfig::new(conf));
}
}
@ -117,7 +122,11 @@ pub fn is_conversation_having_call(conv_id: &ConvID) -> bool {
});
if let Err(e) = res {
eprintln!("Failed to check if a conversation is having call! Conversation: {} / Error: {:#?}", conv_id.id(), e);
eprintln!(
"Failed to check if a conversation is having call! Conversation: {} / Error: {:#?}",
conv_id.id(),
e
);
}
found
@ -149,12 +158,14 @@ pub async fn join_call(r: &mut UserWsRequestHandler) -> RequestResult {
make_user_leave_call(&call.conv_id, &conn).await?;
}
}
};
}
r.update_conn(|r| r.active_call = Some(ActiveCall {
conv_id,
ready: false,
}))?;
r.update_conn(|r| {
r.active_call = Some(ActiveCall {
conv_id,
ready: false,
})
})?;
// Propagate event
events_helper::propagate_event(Event::UserJoinedCall(conv_id, r.user_id()?)).await?;
@ -187,7 +198,10 @@ pub async fn get_members_list(r: &mut UserWsRequestHandler) -> RequestResult {
user_ws_controller::foreach_connection(|conn| {
if conn.is_having_call_with_conversation(&conv_id) {
list.push(CallMemberInfo::new(conn.user_id(), &conn.active_call.as_ref().unwrap()));
list.push(CallMemberInfo::new(
conn.user_id(),
&conn.active_call.as_ref().unwrap(),
));
}
Ok(())
@ -215,10 +229,11 @@ pub async fn on_client_signal(r: &mut UserWsRequestHandler) -> RequestResult {
let signal = match sig_type.as_str() {
"SDP" => {
// Get SDP type
let sdp_type = SdpType::from_str(data.get("type")
.unwrap_or(&serde_json::Value::Null)
.as_str()
.ok_or(ExecError::boxed_new("Missing SDP type !"))?
let sdp_type = SdpType::from_str(
data.get("type")
.unwrap_or(&serde_json::Value::Null)
.as_str()
.ok_or(ExecError::boxed_new("Missing SDP type !"))?,
)?;
let sdp = data
@ -237,7 +252,9 @@ pub async fn on_client_signal(r: &mut UserWsRequestHandler) -> RequestResult {
.get("candidate")
.unwrap_or(&serde_json::Value::Null)
.as_str()
.ok_or(ExecError::boxed_new("Failed to get candidate message data!"))?
.ok_or(ExecError::boxed_new(
"Failed to get candidate message data!",
))?
.to_string();
let sdp_m_line_index = data
@ -253,14 +270,16 @@ pub async fn on_client_signal(r: &mut UserWsRequestHandler) -> RequestResult {
.ok_or(ExecError::boxed_new("Failed to get sdpMid message data!"))?
.to_string();
let parsed_candidate: SdpAttribute = candidate.trim().parse()?;
CallSignal::Candidate(IceCandidate {
candidate,
sdp_m_line_index,
sdp_mid,
}, parsed_candidate)
CallSignal::Candidate(
IceCandidate {
candidate,
sdp_m_line_index,
sdp_mid,
},
parsed_candidate,
)
}
_ => {
@ -271,10 +290,15 @@ pub async fn on_client_signal(r: &mut UserWsRequestHandler) -> RequestResult {
events_helper::propagate_event(Event::NewUserCallSignal(NewUserCallSignal {
call_hash: gen_call_hash(&call_id, &peer_id),
user_id: if r.user_id_ref()? == &peer_id { None } else { Some(r.user_id()?) },
user_id: if r.user_id_ref()? == &peer_id {
None
} else {
Some(r.user_id()?)
},
signal,
raw_data: r.post_string("data")?,
})).await?;
}))
.await?;
r.success("Signal sent")
}
@ -288,7 +312,12 @@ pub async fn mark_user_ready(r: &mut UserWsRequestHandler) -> Res {
user_ws_controller::send_message_to_specific_connections(
|c| c.user_id() != &user_id && c.is_having_call_with_conversation(&call_id),
|_| UserWsMessage::no_id_message("call_peer_ready", CallPeerReadyAPI::new(&call_id, r.user_id_ref()?)),
|_| {
UserWsMessage::no_id_message(
"call_peer_ready",
CallPeerReadyAPI::new(&call_id, r.user_id_ref()?),
)
},
)?;
r.success("Information propagated.")
@ -308,7 +337,8 @@ pub async fn request_offer(r: &mut UserWsRequestHandler) -> Res {
events_helper::propagate_event(Event::UserRequestedCallOffer(UserCallOfferRequest {
call_hash: gen_call_hash(&call_id, &peer_id),
user_id: r.user_id()?,
})).await?;
}))
.await?;
r.success("Request sent")
}
@ -325,7 +355,12 @@ pub async fn stop_streaming(r: &mut UserWsRequestHandler) -> Res {
// Notify all other users
user_ws_controller::send_message_to_specific_connections(
|c| c.is_having_call_with_conversation(&call_id) && c.user_id() != &user_id,
|_| UserWsMessage::no_id_message("call_peer_interrupted_streaming", CallPeerInterruptedStreamingAPI::new(&call_id, &user_id)),
|_| {
UserWsMessage::no_id_message(
"call_peer_interrupted_streaming",
CallPeerInterruptedStreamingAPI::new(&call_id, &user_id),
)
},
)?;
}
@ -333,42 +368,50 @@ pub async fn stop_streaming(r: &mut UserWsRequestHandler) -> Res {
events_helper::propagate_event(Event::CloseCallStream(CloseCallStream {
call_hash: gen_call_hash(&call_id, &user_id),
peer_id: None,
})).await?;
}))
.await?;
r.success("ok")
}
/// Make the user leave the call
pub async fn make_user_leave_call(conv_id: &ConvID, connection: &UserWsConnection) -> Res {
connection.clone().replace(|c| c.active_call = None);
// Notify user (if possible)
if connection.session.connected() {
user_ws_controller::send_to_client(connection, &UserWsMessage::no_id_message("call_closed", conv_id.id())?)?;
user_ws_controller::send_to_client(
connection,
&UserWsMessage::no_id_message("call_closed", conv_id.id())?,
)?;
}
// Close main stream (sender)
events_helper::propagate_event(Event::CloseCallStream(CloseCallStream {
call_hash: gen_call_hash(&conv_id, connection.user_id()),
peer_id: None,
})).await?;
}))
.await?;
// Close receiver streams (other users streams)
for peer_conn in user_ws_controller::get_all_connections()? {
if peer_conn.is_having_call_with_conversation(conv_id) && peer_conn.user_id() != connection.user_id() {
if peer_conn.is_having_call_with_conversation(conv_id)
&& peer_conn.user_id() != connection.user_id()
{
events_helper::propagate_event(Event::CloseCallStream(CloseCallStream {
call_hash: gen_call_hash(&conv_id, peer_conn.user_id()),
peer_id: Some(connection.user_id().clone()),
})).await?;
}))
.await?;
}
};
}
// Create a notification
events_helper::propagate_event(Event::UserLeftCall(
conv_id.clone(),
connection.user_id().clone(),
)).await?;
))
.await?;
Ok(())
}
@ -379,14 +422,24 @@ pub async fn handle_event(e: &events_helper::Event) -> Res {
Event::UserJoinedCall(conv_id, user_id) => {
user_ws_controller::send_message_to_specific_connections(
|c| c.is_having_call_with_conversation(conv_id) && c.user_id() != user_id,
|_| UserWsMessage::no_id_message("user_joined_call", JoinedCallMessage::new(conv_id, user_id)),
|_| {
UserWsMessage::no_id_message(
"user_joined_call",
JoinedCallMessage::new(conv_id, user_id),
)
},
)?;
}
Event::UserLeftCall(conv_id, user_id) => {
user_ws_controller::send_message_to_specific_connections(
|c| c.is_having_call_with_conversation(conv_id),
|_| UserWsMessage::no_id_message("user_left_call", LeftCallMessage::new(conv_id, user_id)),
|_| {
UserWsMessage::no_id_message(
"user_left_call",
LeftCallMessage::new(conv_id, user_id),
)
},
)?;
}
@ -409,13 +462,17 @@ pub async fn handle_event(e: &events_helper::Event) -> Res {
let target_user = UserID::new(msg.peer_id.parse::<u64>()?);
let target_user = match target_user.is_valid() {
true => target_user,
false => peer_id.clone()
false => peer_id.clone(),
};
user_ws_controller::send_message_to_specific_connections(
|c| c.user_id() == target_user && c.is_having_call_with_conversation(&call_id),
|_| UserWsMessage::no_id_message("new_call_signal", NewCallSignalAPI::new(&call_id, &peer_id, &msg.data)?),
|_| {
UserWsMessage::no_id_message(
"new_call_signal",
NewCallSignalAPI::new(&call_id, &peer_id, &msg.data)?,
)
},
)?;
}
@ -426,7 +483,7 @@ pub async fn handle_event(e: &events_helper::Event) -> Res {
if let Some(call) = &f.active_call {
make_user_leave_call(&call.conv_id, &f).await?;
}
};
}
}
// Call active call of user (if any)
@ -463,4 +520,4 @@ pub async fn handle_event(e: &events_helper::Event) -> Res {
}
Ok(())
}
}

View File

@ -5,7 +5,6 @@
use crate::api_data::comment_api::CommentAPI;
use crate::api_data::res_create_comment::ResCreateComment;
use crate::constants::PATH_COMMENTS_IMAGES;
use crate::routes::RequestResult;
use crate::controllers::user_ws_controller;
use crate::data::base_request_handler::BaseRequestHandler;
use crate::data::comment::Comment;
@ -14,8 +13,9 @@ use crate::data::http_request_handler::HttpRequestHandler;
use crate::data::notification::NotifEventType;
use crate::data::post::PostAccessLevel;
use crate::data::user_ws_message::UserWsMessage;
use crate::helpers::{comments_helper, events_helper, notifications_helper, posts_helper};
use crate::helpers::events_helper::Event;
use crate::helpers::{comments_helper, events_helper, notifications_helper, posts_helper};
use crate::routes::RequestResult;
use crate::utils::date_utils::time;
use crate::utils::string_utils::remove_html_nodes;
@ -30,16 +30,12 @@ pub async fn create(r: &mut HttpRequestHandler) -> RequestResult {
let (content, image) = if r.has_file("image") {
(
remove_html_nodes(&r.post_string_opt("content", 0, false)?),
Some(r.save_post_image("image", PATH_COMMENTS_IMAGES, 700, 700)?)
Some(r.save_post_image("image", PATH_COMMENTS_IMAGES, 700, 700)?),
)
} else {
(
r.post_content("content", 2, true)?,
None
)
(r.post_content("content", 2, true)?, None)
};
let comment = Comment {
id: 0,
time_sent: time(),
@ -52,10 +48,16 @@ pub async fn create(r: &mut HttpRequestHandler) -> RequestResult {
let comment_id = comments_helper::create(&comment).await?;
// Create notifications
notifications_helper::create_post_notification(&r.user_id()?, post.id, NotifEventType::COMMENT_CREATED).await?;
notifications_helper::create_post_notification(
&r.user_id()?,
post.id,
NotifEventType::COMMENT_CREATED,
)
.await?;
// Remove notifications targeting current user about the post
notifications_helper::delete_all_post_notifications_targeting_user(r.user_id_ref()?, post.id).await?;
notifications_helper::delete_all_post_notifications_targeting_user(r.user_id_ref()?, post.id)
.await?;
r.set_response(ResCreateComment::new(comment_id))
}
@ -92,30 +94,31 @@ pub async fn handle_event(e: &events_helper::Event) -> Res {
Event::NewComment(comment) => {
user_ws_controller::send_message_to_specific_connections(
|c| c.posts.contains(&comment.post_id),
|c| UserWsMessage::no_id_message(
"new_comment",
CommentAPI::new(comment, &Some(c.user_id().clone()))?,
)
|c| {
UserWsMessage::no_id_message(
"new_comment",
CommentAPI::new(comment, &Some(c.user_id().clone()))?,
)
},
)?;
}
Event::UpdatedComment(comment) => {
user_ws_controller::send_message_to_specific_connections(
|c| c.posts.contains(&comment.post_id),
|c| UserWsMessage::no_id_message(
"comment_updated",
CommentAPI::new(comment, &Some(c.user_id().clone()))?,
)
|c| {
UserWsMessage::no_id_message(
"comment_updated",
CommentAPI::new(comment, &Some(c.user_id().clone()))?,
)
},
)?;
}
Event::DeletedComment(comment) => {
user_ws_controller::send_message_to_specific_connections(
|c| c.posts.contains(&comment.post_id),
|_| UserWsMessage::no_id_message(
"comment_deleted",
comment.id.clone(),
),
|_| UserWsMessage::no_id_message("comment_deleted", comment.id.clone()),
)?;
}
@ -123,4 +126,4 @@ pub async fn handle_event(e: &events_helper::Event) -> Res {
}
Ok(())
}
}

View File

@ -12,7 +12,12 @@ use crate::api_data::res_count_unread_conversations::ResultCountUnreadConversati
use crate::api_data::res_create_conversation::ResCreateConversation;
use crate::api_data::res_find_private_conversations::ResFindPrivateConversations;
use crate::api_data::user_is_writing_message_in_conversation::UserIsWritingMessageInConversation;
use crate::constants::conversations::{ALLOWED_CONVERSATION_FILES_TYPES, CONVERSATION_FILES_MAX_SIZE, MAX_CONV_IMAGE_MESSAGE_HEIGHT, MAX_CONV_IMAGE_MESSAGE_WIDTH, MAX_CONV_LOGO_HEIGHT, MAX_CONV_LOGO_WIDTH, MAX_CONV_MESSAGE_THUMBNAIL_HEIGHT, MAX_CONV_MESSAGE_THUMBNAIL_WIDTH, MAX_CONVERSATION_MESSAGE_LENGTH, MIN_CONVERSATION_MESSAGE_LENGTH};
use crate::constants::conversations::{
ALLOWED_CONVERSATION_FILES_TYPES, CONVERSATION_FILES_MAX_SIZE, MAX_CONVERSATION_MESSAGE_LENGTH,
MAX_CONV_IMAGE_MESSAGE_HEIGHT, MAX_CONV_IMAGE_MESSAGE_WIDTH, MAX_CONV_LOGO_HEIGHT,
MAX_CONV_LOGO_WIDTH, MAX_CONV_MESSAGE_THUMBNAIL_HEIGHT, MAX_CONV_MESSAGE_THUMBNAIL_WIDTH,
MIN_CONVERSATION_MESSAGE_LENGTH,
};
use crate::controllers::user_ws_controller;
use crate::data::base_request_handler::{BaseRequestHandler, RequestValue};
use crate::data::conversation::NewConversationSettings;
@ -23,8 +28,8 @@ use crate::data::new_conversation::NewConversation;
use crate::data::new_conversation_message::NewConversationMessage;
use crate::data::user_ws_message::UserWsMessage;
use crate::data::user_ws_request_handler::UserWsRequestHandler;
use crate::helpers::{conversations_helper, events_helper};
use crate::helpers::events_helper::Event;
use crate::helpers::{conversations_helper, events_helper};
use crate::routes::RequestResult;
use crate::utils::string_utils::remove_html_nodes;
use crate::utils::user_data_utils::{delete_user_data_file_if_exists, user_data_path};
@ -57,7 +62,11 @@ pub async fn create(r: &mut HttpRequestHandler) -> RequestResult {
pub async fn get_list(r: &mut HttpRequestHandler) -> RequestResult {
let list = conversations_helper::get_list_user(&r.user_id()?)?;
r.set_response(list.iter().map(|c| ConversationAPI::new(c)).collect::<Vec<ConversationAPI>>())
r.set_response(
list.iter()
.map(|c| ConversationAPI::new(c))
.collect::<Vec<ConversationAPI>>(),
)
}
/// Get information about a single conversation
@ -84,15 +93,19 @@ pub async fn update_settings(r: &mut HttpRequestHandler) -> RequestResult {
// Change moderator settings
if r.has_post_parameter("name")
&& r.has_post_parameter("canEveryoneAddMembers")
&& r.has_post_parameter("color") {
&& r.has_post_parameter("color")
{
if !conv_membership.is_admin {
r.forbidden("You are not allowed to perform changes on this conversation!".to_string())?;
r.forbidden(
"You are not allowed to perform changes on this conversation!".to_string(),
)?;
}
let new_settings = NewConversationSettings {
conv_id: conv_membership.conv_id,
name: r.post_string_optional("name").map(|s| remove_html_nodes(&s)),
name: r
.post_string_optional("name")
.map(|s| remove_html_nodes(&s)),
color: r.post_color_opt("color")?,
can_everyone_add_members: r.post_bool("canEveryoneAddMembers")?,
};
@ -108,7 +121,12 @@ pub async fn change_image(r: &mut HttpRequestHandler) -> RequestResult {
let conv_membership = r.post_conv_admin("convID")?;
let conv = conversations_helper::get_single(conv_membership.conv_id)?;
let new_image = r.save_post_image("file", "conv-image", MAX_CONV_LOGO_WIDTH, MAX_CONV_LOGO_HEIGHT)?;
let new_image = r.save_post_image(
"file",
"conv-image",
MAX_CONV_LOGO_WIDTH,
MAX_CONV_LOGO_HEIGHT,
)?;
conversations_helper::remove_conversation_image(&conv)?;
@ -135,7 +153,9 @@ pub async fn add_member(r: &mut HttpRequestHandler) -> RequestResult {
let user_to_add = r.post_user_id("userID")?;
if conv.is_managed() {
r.bad_request("This conversation is managed, you can not manually change its members!".to_string())?;
r.bad_request(
"This conversation is managed, you can not manually change its members!".to_string(),
)?;
}
if !conv.can_user_add_members(r.user_id_ref()?) {
@ -146,7 +166,8 @@ pub async fn add_member(r: &mut HttpRequestHandler) -> RequestResult {
r.bad_request("This user is already a member of this conversation!".to_string())?;
}
conversations_helper::add_member(conv.id, &user_to_add, true, false, Some(r.user_id_ref()?)).await?;
conversations_helper::add_member(conv.id, &user_to_add, true, false, Some(r.user_id_ref()?))
.await?;
r.success("The user was added to the conversation!")
}
@ -159,7 +180,9 @@ pub async fn set_admin(r: &mut HttpRequestHandler) -> RequestResult {
let set_admin = r.post_bool("setAdmin")?;
if conv.is_managed() {
r.bad_request("This conversation is managed, you can not manually change its members!".to_string())?;
r.bad_request(
"This conversation is managed, you can not manually change its members!".to_string(),
)?;
}
if !conv.can_mark_other_users_admin(r.user_id_ref()?) {
@ -183,7 +206,9 @@ pub async fn remove_member(r: &mut HttpRequestHandler) -> RequestResult {
let user_to_remove = r.post_user_id("userID")?;
if conv.is_managed() {
r.bad_request("This conversation is managed, you can not manually change its members!".to_string())?;
r.bad_request(
"This conversation is managed, you can not manually change its members!".to_string(),
)?;
}
if !conv.can_user_remove_members(r.user_id_ref()?) {
@ -254,7 +279,8 @@ pub async fn refresh_single(r: &mut HttpRequestHandler) -> RequestResult {
conv.conv_id,
r.user_id_ref()?,
&messages.last().unwrap(),
).await?;
)
.await?;
}
r.set_response(ConversationMessageAPI::for_list(&messages))
@ -270,7 +296,7 @@ pub async fn get_older_messages(r: &mut HttpRequestHandler) -> RequestResult {
let limit = match limit {
0 => 1,
1..=60 => limit,
_ => 60
_ => 60,
};
let messages = conversations_helper::get_older_messages(conv.conv_id, max_id, limit)?;
@ -285,7 +311,6 @@ pub async fn send_message(r: &mut HttpRequestHandler) -> RequestResult {
// Get associated file
let file = match r.post_parameter_opt("file") {
Some(RequestValue::File(file)) => {
// File name
let mut name = file.name.to_string();
@ -299,7 +324,7 @@ pub async fn send_message(r: &mut HttpRequestHandler) -> RequestResult {
// Check for thumbnail
let mut thumbnail = match r.has_file("thumbnail") {
false => None,
true => Some("thumbnail".to_string())
true => Some("thumbnail".to_string()),
};
let path;
@ -314,56 +339,58 @@ pub async fn send_message(r: &mut HttpRequestHandler) -> RequestResult {
thumbnail = Some("file".to_string());
}
path = r.save_post_image("file", "conversation", MAX_CONV_IMAGE_MESSAGE_WIDTH, MAX_CONV_IMAGE_MESSAGE_HEIGHT)?;
path = r.save_post_image(
"file",
"conversation",
MAX_CONV_IMAGE_MESSAGE_WIDTH,
MAX_CONV_IMAGE_MESSAGE_HEIGHT,
)?;
mime_type = "image/png".to_string();
name = "picture.png".to_string();
}
// PDF
else if mime_type.eq("application/pdf") {
path = r.save_post_pdf("file", "conversation")?;
}
// MP3
else if mime_type.eq("audio/mpeg") {
path = r.save_post_mp3("file", "conversation")?;
}
// MP4
else if mime_type.eq("video/mp4") || mime_type.eq("video/quicktime") {
path = r.save_post_mp4("file", "conversation")?;
}
// ZIP archive
else if mime_type.eq("application/zip") {
path = r.save_post_zip("file", "conversation")?;
}
// Office document
else if mime_type.starts_with("application/") {
path = r.save_post_office_doc("file", "conversation")?;
}
// Text files
else {
path = r.save_post_txt_doc("file", "conversation")?;
}
// Attempt to save thumbnail, if it fails we can not save message
let thumbnail = match thumbnail {
None => None,
Some(f) => Some(match r.save_post_image(&f, "conversations-thumb", MAX_CONV_MESSAGE_THUMBNAIL_WIDTH, MAX_CONV_MESSAGE_THUMBNAIL_HEIGHT) {
Some(f) => Some(match r.save_post_image(
&f,
"conversations-thumb",
MAX_CONV_MESSAGE_THUMBNAIL_WIDTH,
MAX_CONV_MESSAGE_THUMBNAIL_HEIGHT,
) {
Ok(s) => Ok(s),
Err(e) => {
eprintln!("Failed to save conversation thumbnail! {:#?}", e);
delete_user_data_file_if_exists(&path).unwrap();
Err(e)
}
}?)
}?),
};
Some(ConversationMessageFile {
path: path.clone(),
size: std::fs::metadata(user_data_path(path.as_ref()))?.len(),
@ -394,7 +421,8 @@ pub async fn send_message(r: &mut HttpRequestHandler) -> RequestResult {
message,
file,
server_message: None,
}).await?;
})
.await?;
r.success("Conversation message was successfully sent!")
}
@ -419,10 +447,13 @@ pub async fn delete_conversation(r: &mut HttpRequestHandler) -> RequestResult {
let conv = conversations_helper::get_single(conv_membership.conv_id)?;
if conv.is_managed() {
r.bad_request("This conversation is managed, it can not be deleted by this way!".to_string())?;
r.bad_request(
"This conversation is managed, it can not be deleted by this way!".to_string(),
)?;
}
conversations_helper::remove_user_from_conversation(&r.user_id()?, &conv, r.user_id_ref()?).await?;
conversations_helper::remove_user_from_conversation(&r.user_id()?, &conv, r.user_id_ref()?)
.await?;
r.success("The conversation has been deleted")
}
@ -469,9 +500,11 @@ pub async fn member_is_writing(r: &mut UserWsRequestHandler) -> RequestResult {
let conv_id = r.post_registered_conv_id("convID")?;
// Propagate event
events_helper::propagate_event(
Event::UserIsWritingMessageInConversation(r.user_id()?, conv_id)
).await?;
events_helper::propagate_event(Event::UserIsWritingMessageInConversation(
r.user_id()?,
conv_id,
))
.await?;
r.ok()
}
@ -496,14 +529,24 @@ pub async fn handle_event(e: &events_helper::Event) -> Res {
Event::UserIsWritingMessageInConversation(user_id, conv_id) => {
user_ws_controller::send_message_to_specific_connections(
|s| s.conversations.contains(conv_id) && s.user_id() != user_id,
|_| UserWsMessage::no_id_message("writing_message_in_conv", UserIsWritingMessageInConversation::new(user_id, *conv_id)),
|_| {
UserWsMessage::no_id_message(
"writing_message_in_conv",
UserIsWritingMessageInConversation::new(user_id, *conv_id),
)
},
)?;
}
Event::NewConversationMessage(msg) => {
for conn in user_ws_controller::send_message_to_specific_connections(
|f| f.conversations.contains(&msg.conv_id),
|_| UserWsMessage::no_id_message("new_conv_message", ConversationMessageAPI::new(msg)),
|_| {
UserWsMessage::no_id_message(
"new_conv_message",
ConversationMessageAPI::new(msg),
)
},
)? {
conversations_helper::mark_user_seen(msg.conv_id, conn.user_id(), msg).await?;
}
@ -512,14 +555,24 @@ pub async fn handle_event(e: &events_helper::Event) -> Res {
Event::UpdatedConversationMessage(msg) => {
user_ws_controller::send_message_to_specific_connections(
|f| f.conversations.contains(&msg.conv_id),
|_| UserWsMessage::no_id_message("updated_conv_message", ConversationMessageAPI::new(msg)),
|_| {
UserWsMessage::no_id_message(
"updated_conv_message",
ConversationMessageAPI::new(msg),
)
},
)?;
}
Event::DeleteConversationMessage(msg) => {
user_ws_controller::send_message_to_specific_connections(
|f| f.conversations.contains(&msg.conv_id),
|_| UserWsMessage::no_id_message("deleted_conv_message", ConversationMessageAPI::new(msg)),
|_| {
UserWsMessage::no_id_message(
"deleted_conv_message",
ConversationMessageAPI::new(msg),
)
},
)?;
}
@ -527,7 +580,12 @@ pub async fn handle_event(e: &events_helper::Event) -> Res {
// Notify users
user_ws_controller::send_message_to_specific_connections(
|f| f.conversations.contains(conv_id),
|_| UserWsMessage::no_id_message("removed_user_from_conv", RemovedUserFromConversationMessage::new(user_id, *conv_id)),
|_| {
UserWsMessage::no_id_message(
"removed_user_from_conv",
RemovedUserFromConversationMessage::new(user_id, *conv_id),
)
},
)?;
// Disconnect user from conversation
@ -565,4 +623,4 @@ pub async fn handle_event(e: &events_helper::Event) -> Res {
}
Ok(())
}
}

View File

@ -20,7 +20,10 @@ pub async fn get_list_groups(r: &mut HttpRequestHandler) -> RequestResult {
let mut list = vec![];
for group in &conf().forez_groups {
list.push(GroupApi::new(&groups_helper::get_info(group)?, r.user_id_opt())?);
list.push(GroupApi::new(
&groups_helper::get_info(group)?,
r.user_id_opt(),
)?);
}
r.set_response(list)
@ -150,4 +153,4 @@ pub fn del_day<H: BaseRequestHandler>(r: &mut H) -> RequestResult {
forez_presence_helper::update(&group, &r.user_id()?, list)?;
r.success("Updated presences.")
}
}

View File

@ -21,13 +21,9 @@ pub async fn get_list(r: &mut HttpRequestHandler) -> RequestResult {
pub async fn get_single_friendship_info(r: &mut HttpRequestHandler) -> RequestResult {
let friend_id = r.post_user_id("friendID")?;
let info = friends_helper::GetFriendsQuery::new(&r.user_id()?)
.get_single_friend(&friend_id);
let info = friends_helper::GetFriendsQuery::new(&r.user_id()?).get_single_friend(&friend_id);
let info = r.ok_or_not_found(
info,
"The friendship was not found!",
)?;
let info = r.ok_or_not_found(info, "The friendship was not found!")?;
r.set_response(FriendAPI::new(&info))
}
@ -48,7 +44,12 @@ pub async fn get_other_user_list(r: &mut HttpRequestHandler) -> RequestResult {
.set_only_accepted(true)
.exec()?;
r.set_response(friends.iter().map(|f| f.friend_id.id()).collect::<Vec<u64>>())
r.set_response(
friends
.iter()
.map(|f| f.friend_id.id())
.collect::<Vec<u64>>(),
)
}
/// Get the status of a friendship
@ -85,7 +86,9 @@ pub async fn send_request(r: &mut HttpRequestHandler) -> RequestResult {
notifications_helper::create_friends_notification(
r.user_id_ref()?,
&friend_id,
NotifEventType::SENT_FRIEND_REQUEST).await?;
NotifEventType::SENT_FRIEND_REQUEST,
)
.await?;
r.success("The friendship request was successfully sent!")
}
@ -101,7 +104,8 @@ pub async fn cancel_request(r: &mut HttpRequestHandler) -> RequestResult {
friends_helper::remove_request(&r.user_id()?, &friend_id)?;
// Delete related notifications
notifications_helper::delete_all_related_with_friendship_request(r.user_id_ref()?, &friend_id).await?;
notifications_helper::delete_all_related_with_friendship_request(r.user_id_ref()?, &friend_id)
.await?;
r.success("Friendship request removed!")
}
@ -123,9 +127,10 @@ pub async fn respond_request(r: &mut HttpRequestHandler) -> RequestResult {
&friend_id,
match accept {
true => NotifEventType::ACCEPTED_FRIEND_REQUEST,
false => NotifEventType::REJECTED_FRIEND_REQUEST
false => NotifEventType::REJECTED_FRIEND_REQUEST,
},
).await?;
)
.await?;
r.set_response("Response to the friendship request successfully saved!")
}
@ -137,7 +142,8 @@ pub async fn remove_friend(r: &mut HttpRequestHandler) -> RequestResult {
friends_helper::remove_friendship(r.user_id_ref()?, &friend_id)?;
// Delete any related notification
notifications_helper::delete_all_related_with_friendship_request(r.user_id_ref()?, &friend_id).await?;
notifications_helper::delete_all_related_with_friendship_request(r.user_id_ref()?, &friend_id)
.await?;
r.success("The friend was removed from the list!")
}
@ -160,4 +166,4 @@ pub async fn set_can_post_texts(r: &mut HttpRequestHandler) -> RequestResult {
friends_helper::set_can_post_texts(r.user_id_ref()?, &friend_id, allow)?;
r.success("Updated status!")
}
}

View File

@ -12,22 +12,29 @@ use crate::api_data::res_create_conversation_for_group::ResCreateConversationFor
use crate::api_data::res_create_group::GroupCreationResult;
use crate::constants::{DEFAULT_GROUP_LOGO, PATH_GROUPS_LOGOS};
use crate::data::base_request_handler::BaseRequestHandler;
use crate::data::conversation::Conversation;
use crate::data::error::Res;
use crate::data::group::{Group, GroupAccessLevel, GroupPostsCreationLevel, GroupRegistrationLevel, GroupVisibilityLevel};
use crate::data::group::{
Group, GroupAccessLevel, GroupPostsCreationLevel, GroupRegistrationLevel, GroupVisibilityLevel,
};
use crate::data::group_id::GroupID;
use crate::data::group_member::{GroupMember, GroupMembershipLevel};
use crate::data::http_request_handler::HttpRequestHandler;
use crate::data::new_group::NewGroup;
use crate::data::notification::NotifEventType;
use crate::helpers::{conversations_helper, groups_helper, notifications_helper, virtual_directory_helper};
use crate::helpers::virtual_directory_helper::VirtualDirType;
use crate::helpers::{
conversations_helper, groups_helper, notifications_helper, virtual_directory_helper,
};
use crate::routes::RequestResult;
use crate::utils::date_utils::time;
use crate::data::conversation::Conversation;
impl HttpRequestHandler {
/// Get membership level for a conversation
pub fn post_group_membership_level_for_conversation(&mut self, name: &str) -> Res<GroupMembershipLevel> {
pub fn post_group_membership_level_for_conversation(
&mut self,
name: &str,
) -> Res<GroupMembershipLevel> {
let level = GroupMembershipLevel::from_api(&self.post_string(name)?);
if !level.is_at_least_member() {
@ -43,7 +50,10 @@ impl HttpRequestHandler {
let conv = conversations_helper::get_single(conv_membership.conv_id)?;
if !conv.is_linked_to_group() {
self.bad_request("This conversation is not linked to a group, it can not be updated this way!".to_string())?;
self.bad_request(
"This conversation is not linked to a group, it can not be updated this way!"
.to_string(),
)?;
}
Ok(conv)
@ -89,8 +99,10 @@ pub async fn get_info_multiple(r: &mut HttpRequestHandler) -> RequestResult {
for id in groups_id {
let id = GroupID::new(id as u64);
if !groups_helper::exists(&id)? ||
groups_helper::get_access_level(&id, r.user_id_opt())? < GroupAccessLevel::LIMITED_ACCESS {
if !groups_helper::exists(&id)?
|| groups_helper::get_access_level(&id, r.user_id_opt())?
< GroupAccessLevel::LIMITED_ACCESS
{
r.not_found(format!("Group {} not found!", id.id()))?;
}
@ -132,7 +144,11 @@ pub async fn set_settings(r: &mut HttpRequestHandler) -> RequestResult {
posts_creation_level: GroupPostsCreationLevel::from_api(&r.post_string("posts_level")?),
is_members_list_public: r.post_bool("is_members_list_public")?,
logo: None,
virtual_directory: r.post_checked_virtual_directory_opt("virtual_directory", group_id.id(), VirtualDirType::GROUP)?,
virtual_directory: r.post_checked_virtual_directory_opt(
"virtual_directory",
group_id.id(),
VirtualDirType::GROUP,
)?,
time_create: 0,
description: r.post_string_without_html_opt("description", 0)?,
url: r.post_url_opt("url", false)?,
@ -184,10 +200,13 @@ pub async fn delete_logo(r: &mut HttpRequestHandler) -> RequestResult {
/// Create a new group's conversation
pub async fn create_conversation(r: &mut HttpRequestHandler) -> RequestResult {
let group = r.post_group_id_with_access("group_id", GroupAccessLevel::ADMIN_ACCESS)?;
let min_membership_level = r.post_group_membership_level_for_conversation("min_membership_level")?;
let min_membership_level =
r.post_group_membership_level_for_conversation("min_membership_level")?;
let name = r.post_string("name")?;
let conv_id = conversations_helper::create_conversation_for_group(group, min_membership_level, &name).await?;
let conv_id =
conversations_helper::create_conversation_for_group(group, min_membership_level, &name)
.await?;
r.set_response(ResCreateConversationForGroup::new(conv_id))
}
@ -218,7 +237,9 @@ pub async fn get_members(r: &mut HttpRequestHandler) -> RequestResult {
let group = groups_helper::get_info(&group_id)?;
if group_access_level < GroupAccessLevel::VIEW_ACCESS
|| (!group.is_members_list_public && group_access_level < GroupAccessLevel::MODERATOR_ACCESS) {
|| (!group.is_members_list_public
&& group_access_level < GroupAccessLevel::MODERATOR_ACCESS)
{
r.forbidden("You can not access the list of members of this group!".to_string())?;
}
@ -232,14 +253,17 @@ pub async fn cancel_invitation(r: &mut HttpRequestHandler) -> RequestResult {
let group_id = r.post_group_id_with_access("groupID", GroupAccessLevel::MODERATOR_ACCESS)?;
let user_id = r.post_user_id("userID")?;
if groups_helper::get_membership_level(&group_id, Some(user_id.clone()))? != GroupMembershipLevel::INVITED {
if groups_helper::get_membership_level(&group_id, Some(user_id.clone()))?
!= GroupMembershipLevel::INVITED
{
r.forbidden("This user has not been invited to join this group!".to_string())?;
}
groups_helper::delete_member(&group_id, &user_id).await?;
// Delete related notifications
notifications_helper::delete_all_related_to_group_membership_notifications(&user_id, &group_id).await?;
notifications_helper::delete_all_related_to_group_membership_notifications(&user_id, &group_id)
.await?;
r.success("Membership invitation has been cancelled!")
}
@ -249,7 +273,9 @@ pub async fn invite_user(r: &mut HttpRequestHandler) -> RequestResult {
let group_id = r.post_group_id_with_access("group_id", GroupAccessLevel::MODERATOR_ACCESS)?;
let user_id = r.post_user_id("userID")?;
if groups_helper::get_membership_level(&group_id, Some(user_id.clone()))? != GroupMembershipLevel::VISITOR {
if groups_helper::get_membership_level(&group_id, Some(user_id.clone()))?
!= GroupMembershipLevel::VISITOR
{
r.bad_request("The user is not a visitor of the group!".to_string())?;
}
@ -257,7 +283,12 @@ pub async fn invite_user(r: &mut HttpRequestHandler) -> RequestResult {
// Send a notification
notifications_helper::create_group_membership_notification(
&user_id, Some(r.user_id_ref()?), &group_id, NotifEventType::SENT_GROUP_MEMBERSHIP_INVITATION).await?;
&user_id,
Some(r.user_id_ref()?),
&group_id,
NotifEventType::SENT_GROUP_MEMBERSHIP_INVITATION,
)
.await?;
r.success("The user has been successfully invited to join the group!")
}
@ -278,10 +309,16 @@ pub async fn respond_invitation(r: &mut HttpRequestHandler) -> RequestResult {
}
// Create a notification
notifications_helper::create_group_membership_notification(r.user_id_ref()?, None, &group_id, match accept {
true => NotifEventType::ACCEPTED_GROUP_MEMBERSHIP_INVITATION,
false => NotifEventType::REJECTED_GROUP_MEMBERSHIP_INVITATION
}).await?;
notifications_helper::create_group_membership_notification(
r.user_id_ref()?,
None,
&group_id,
match accept {
true => NotifEventType::ACCEPTED_GROUP_MEMBERSHIP_INVITATION,
false => NotifEventType::REJECTED_GROUP_MEMBERSHIP_INVITATION,
},
)
.await?;
r.success("Response to the invitation was successfully saved!")
}
@ -290,7 +327,9 @@ pub async fn respond_invitation(r: &mut HttpRequestHandler) -> RequestResult {
pub async fn send_request(r: &mut HttpRequestHandler) -> RequestResult {
let group_id = r.post_group_id_with_access("id", GroupAccessLevel::LIMITED_ACCESS)?;
if groups_helper::get_membership_level(&group_id, r.user_id_opt())? != GroupMembershipLevel::VISITOR {
if groups_helper::get_membership_level(&group_id, r.user_id_opt())?
!= GroupMembershipLevel::VISITOR
{
r.forbidden("You are not currently a visitor of the group!".to_string())?;
}
@ -300,7 +339,9 @@ pub async fn send_request(r: &mut HttpRequestHandler) -> RequestResult {
GroupRegistrationLevel::OPEN_REGISTRATION => GroupMembershipLevel::MEMBER,
GroupRegistrationLevel::MODERATED_REGISTRATION => GroupMembershipLevel::PENDING,
GroupRegistrationLevel::CLOSED_REGISTRATION => {
r.forbidden("You are not authorized to send a registration request for this group!".to_string())?;
r.forbidden(
"You are not authorized to send a registration request for this group!".to_string(),
)?;
unreachable!();
}
};
@ -312,15 +353,23 @@ pub async fn send_request(r: &mut HttpRequestHandler) -> RequestResult {
time_create: time(),
level,
following: true,
}).await?;
})
.await?;
// Send a notification, if required
if matches!(group.registration_level, GroupRegistrationLevel::MODERATED_REGISTRATION) {
notifications_helper::create_group_membership_notification(r.user_id_ref()?, None,
&group_id, NotifEventType::SENT_GROUP_MEMBERSHIP_REQUEST).await?;
if matches!(
group.registration_level,
GroupRegistrationLevel::MODERATED_REGISTRATION
) {
notifications_helper::create_group_membership_notification(
r.user_id_ref()?,
None,
&group_id,
NotifEventType::SENT_GROUP_MEMBERSHIP_REQUEST,
)
.await?;
}
r.success("The membership has been successfully saved!")
}
@ -328,14 +377,20 @@ pub async fn send_request(r: &mut HttpRequestHandler) -> RequestResult {
pub async fn cancel_request(r: &mut HttpRequestHandler) -> RequestResult {
let group_id = r.post_group_id_with_access("id", GroupAccessLevel::LIMITED_ACCESS)?;
if groups_helper::get_membership_level(&group_id, r.user_id_opt())? != GroupMembershipLevel::PENDING {
if groups_helper::get_membership_level(&group_id, r.user_id_opt())?
!= GroupMembershipLevel::PENDING
{
r.forbidden("You did not send a membership request to this group!".to_string())?;
}
groups_helper::delete_member(&group_id, &r.user_id()?).await?;
// Delete any related notification
notifications_helper::delete_all_related_to_group_membership_notifications(r.user_id_ref()?, &group_id).await?;
notifications_helper::delete_all_related_to_group_membership_notifications(
r.user_id_ref()?,
&group_id,
)
.await?;
r.success("The request has been successfully cancelled!")
}
@ -356,14 +411,17 @@ pub async fn delete_member(r: &mut HttpRequestHandler) -> RequestResult {
}
// Only administrator can delete members that are more than members (moderators & administrators)
if membership.level < GroupMembershipLevel::MEMBER && curr_user_membership.level != GroupMembershipLevel::ADMINISTRATOR {
if membership.level < GroupMembershipLevel::MEMBER
&& curr_user_membership.level != GroupMembershipLevel::ADMINISTRATOR
{
r.forbidden("Only administrators can delete this membership!".to_string())?;
}
groups_helper::delete_member(&group_id, &user_id).await?;
// Delete related notifications
notifications_helper::delete_all_related_to_group_membership_notifications(&user_id, &group_id).await?;
notifications_helper::delete_all_related_to_group_membership_notifications(&user_id, &group_id)
.await?;
r.success("Membership of the user has been successfully deleted!")
}
@ -400,17 +458,25 @@ pub async fn respond_request(r: &mut HttpRequestHandler) -> RequestResult {
let user_id = r.post_user_id("userID")?;
let accept = r.post_bool("accept")?;
if groups_helper::get_membership_level(&group_id, Some(user_id.clone()))? != GroupMembershipLevel::PENDING {
if groups_helper::get_membership_level(&group_id, Some(user_id.clone()))?
!= GroupMembershipLevel::PENDING
{
r.forbidden("This user has not requested a membership for this group!".to_string())?;
}
groups_helper::respond_request(&group_id, &user_id, accept).await?;
// Create a notification
notifications_helper::create_group_membership_notification(&user_id, Some(r.user_id_ref()?), &group_id, match accept {
true => NotifEventType::ACCEPTED_GROUP_MEMBERSHIP_REQUEST,
false => NotifEventType::REJECTED_GROUP_MEMBERSHIP_REQUEST
}).await?;
notifications_helper::create_group_membership_notification(
&user_id,
Some(r.user_id_ref()?),
&group_id,
match accept {
true => NotifEventType::ACCEPTED_GROUP_MEMBERSHIP_REQUEST,
false => NotifEventType::REJECTED_GROUP_MEMBERSHIP_REQUEST,
},
)
.await?;
r.success("The response to the request has been successfully saved!")
}
@ -436,7 +502,11 @@ pub async fn remove_membership(r: &mut HttpRequestHandler) -> RequestResult {
groups_helper::delete_member(&group_id, &r.user_id()?).await?;
// Delete group membership notifications
notifications_helper::delete_all_related_to_group_membership_notifications(r.user_id_ref()?, &group_id).await?;
notifications_helper::delete_all_related_to_group_membership_notifications(
r.user_id_ref()?,
&group_id,
)
.await?;
r.success("Your membership has been successfully deleted!")
}
@ -459,4 +529,4 @@ pub async fn delete_group(r: &mut HttpRequestHandler) -> RequestResult {
groups_helper::delete(&group_id).await?;
r.success("Group deleted.")
}
}

View File

@ -6,8 +6,8 @@ use crate::data::base_request_handler::BaseRequestHandler;
use crate::data::error::ExecError;
use crate::data::group::GroupAccessLevel;
use crate::data::post::PostAccessLevel;
use crate::helpers::{likes_helper, notifications_helper, user_helper};
use crate::helpers::likes_helper::LikeType;
use crate::helpers::{likes_helper, notifications_helper, user_helper};
use crate::routes::RequestResult;
struct LikeTarget(u64, LikeType);
@ -18,7 +18,6 @@ pub async fn update<H: BaseRequestHandler>(r: &mut H) -> RequestResult {
let is_liking = r.post_bool("like")?;
let target = match req_type.as_str() {
// In case of user
"user" => {
let user_id = r.post_user_id("id")?;
@ -30,13 +29,16 @@ pub async fn update<H: BaseRequestHandler>(r: &mut H) -> RequestResult {
LikeTarget(user_id.id(), LikeType::USER)
}
// In case of post
"post" => {
let post = r.post_post_with_access("id", PostAccessLevel::BASIC_ACCESS)?;
// Delete any notification targeting this user about the post
notifications_helper::delete_all_post_notifications_targeting_user(r.user_id_ref()?, post.id).await?;
notifications_helper::delete_all_post_notifications_targeting_user(
r.user_id_ref()?,
post.id,
)
.await?;
LikeTarget(post.id, LikeType::POST)
}
@ -46,7 +48,11 @@ pub async fn update<H: BaseRequestHandler>(r: &mut H) -> RequestResult {
let comment = r.post_comment_with_access("id")?;
// Delete any notification targeting this user about the post
notifications_helper::delete_all_post_notifications_targeting_user(r.user_id_ref()?, comment.post_id).await?;
notifications_helper::delete_all_post_notifications_targeting_user(
r.user_id_ref()?,
comment.post_id,
)
.await?;
LikeTarget(comment.id, LikeType::COMMENT)
}
@ -66,4 +72,4 @@ pub async fn update<H: BaseRequestHandler>(r: &mut H) -> RequestResult {
likes_helper::update(r.user_id_ref()?, is_liking, target.0, target.1)?;
r.success("")
}
}

View File

@ -1,24 +1,24 @@
pub mod admin;
pub mod server_controller;
pub mod user_ws_controller;
pub mod rtc_relay_controller;
pub mod account_controller;
pub mod user_controller;
pub mod settings_controller;
pub mod friends_controller;
pub mod conversations_controller;
pub mod search_controller;
pub mod groups_controller;
pub mod posts_controller;
pub mod comments_controller;
pub mod likes_controller;
pub mod surveys_controller;
pub mod notifications_controller;
pub mod virtual_directory_controller;
pub mod web_app_controller;
pub mod calls_controller;
pub mod user_ws_actions;
pub mod comments_controller;
pub mod conversations_controller;
pub mod forez_controller;
pub mod friends_controller;
pub mod groups_controller;
pub mod likes_controller;
pub mod notifications_controller;
pub mod posts_controller;
pub mod push_notifications_controller;
pub mod report_controller;
pub mod forez_controller;
pub mod rtc_relay_controller;
pub mod search_controller;
pub mod server_controller;
pub mod settings_controller;
pub mod surveys_controller;
pub mod user_controller;
pub mod user_ws_actions;
pub mod user_ws_controller;
pub mod virtual_directory_controller;
pub mod web_app_controller;

View File

@ -5,7 +5,6 @@
use crate::api_data::notification_api::NotificationAPI;
use crate::api_data::res_count_all_unreads::ResCountAllUnread;
use crate::api_data::res_number_unread_notifications::ResNumberUnreadNotifications;
use crate::routes::RequestResult;
use crate::controllers::user_ws_controller;
use crate::data::base_request_handler::BaseRequestHandler;
use crate::data::error::{Res, ResultBoxError};
@ -13,8 +12,9 @@ use crate::data::http_request_handler::HttpRequestHandler;
use crate::data::notification::Notification;
use crate::data::user::UserID;
use crate::data::user_ws_message::UserWsMessage;
use crate::helpers::{conversations_helper, events_helper, friends_helper, notifications_helper};
use crate::helpers::events_helper::Event;
use crate::helpers::{conversations_helper, events_helper, friends_helper, notifications_helper};
use crate::routes::RequestResult;
impl HttpRequestHandler {
/// Get the id of a notification included in the request
@ -46,10 +46,14 @@ pub async fn count_all_news(r: &mut HttpRequestHandler) -> RequestResult {
let conversations = conversations_helper::count_unread_for_user(r.user_id_ref()?)?;
let friends_requests = match r.post_bool_opt("friends_request", false) {
true => Some(friends_helper::count_requests(r.user_id_ref()?)?),
false => None
false => None,
};
r.set_response(ResCountAllUnread::new(notifications, conversations as u64, friends_requests))
r.set_response(ResCountAllUnread::new(
notifications,
conversations as u64,
friends_requests,
))
}
/// Get the list of unread notifications
@ -92,7 +96,10 @@ pub fn send_new_notifications_number(user_id: &UserID) -> Res {
}
user_ws_controller::send_message_to_user(
&UserWsMessage::no_id_message("number_notifs", notifications_helper::count_unread(user_id)?)?,
&UserWsMessage::no_id_message(
"number_notifs",
notifications_helper::count_unread(user_id)?,
)?,
user_id,
)
}
@ -109,4 +116,4 @@ pub fn handle_event(e: &events_helper::Event) -> Res {
}
Ok(())
}
}

View File

@ -12,8 +12,12 @@ use crate::data::group::GroupAccessLevel;
use crate::data::http_request_handler::HttpRequestHandler;
use crate::data::new_survey::NewSurvey;
use crate::data::notification::NotifEventType;
use crate::data::post::{Post, PostAccessLevel, PostFile, PostKind, PostPageKind, PostVisibilityLevel, PostWebLink};
use crate::helpers::{friends_helper, groups_helper, notifications_helper, posts_helper, survey_helper, user_helper};
use crate::data::post::{
Post, PostAccessLevel, PostFile, PostKind, PostPageKind, PostVisibilityLevel, PostWebLink,
};
use crate::helpers::{
friends_helper, groups_helper, notifications_helper, posts_helper, survey_helper, user_helper,
};
use crate::routes::RequestResult;
use crate::utils::date_utils::time;
use crate::utils::string_utils::{check_string_before_insert, check_youtube_id};
@ -96,7 +100,8 @@ pub async fn create_post(r: &mut HttpRequestHandler) -> RequestResult {
}
"group" => {
let group_id = r.post_group_id_with_access("kind-id", GroupAccessLevel::MEMBER_ACCESS)?;
let group_id =
r.post_group_id_with_access("kind-id", GroupAccessLevel::MEMBER_ACCESS)?;
if !groups_helper::can_user_create_posts(&group_id, r.user_id_ref()?)? {
r.forbidden("You are not allowed to create posts on this group!".to_string())?;
@ -126,7 +131,6 @@ pub async fn create_post(r: &mut HttpRequestHandler) -> RequestResult {
// Handle different post types
post.kind = match r.post_string("kind")?.as_str() {
// Text posts
"text" => {
if !check_string_before_insert(post.content.as_ref().unwrap_or(&String::new())) {
@ -136,7 +140,6 @@ pub async fn create_post(r: &mut HttpRequestHandler) -> RequestResult {
PostKind::POST_KIND_TEXT
}
// Image post
"image" => {
if !r.has_file("image") {
@ -161,7 +164,8 @@ pub async fn create_post(r: &mut HttpRequestHandler) -> RequestResult {
// Weblink posts
"weblink" => {
let url = r.post_url_opt("url", true)?
let url = r
.post_url_opt("url", true)?
.ok_or(ExecError::new("Missing url!"))?;
match get_post_web_link(&url) {
@ -203,7 +207,8 @@ pub async fn create_post(r: &mut HttpRequestHandler) -> RequestResult {
post_id: 0,
user_id: r.user_id()?,
question: r.post_string("question")?,
choices: r.post_string("answers")?
choices: r
.post_string("answers")?
.split("<>")
.filter(|a| a.len() > 0)
.map(|a| a.to_string())
@ -235,7 +240,12 @@ pub async fn create_post(r: &mut HttpRequestHandler) -> RequestResult {
}
// Create a notification
notifications_helper::create_post_notification(r.user_id_ref()?, post_id, NotifEventType::ELEM_CREATED).await?;
notifications_helper::create_post_notification(
r.user_id_ref()?,
post_id,
NotifEventType::ELEM_CREATED,
)
.await?;
r.set_response(ResCreatePost::new(post_id))
}
@ -263,7 +273,8 @@ pub async fn update_content(r: &mut HttpRequestHandler) -> RequestResult {
posts_helper::set_content(post.id, &new_content)?;
// Delete the notifications targeting the current user about this post
notifications_helper::delete_all_post_notifications_targeting_user(r.user_id_ref()?, post.id).await?;
notifications_helper::delete_all_post_notifications_targeting_user(r.user_id_ref()?, post.id)
.await?;
r.success("Content updated")
}
@ -283,4 +294,4 @@ pub async fn get_targets(r: &mut HttpRequestHandler) -> RequestResult {
let groups = groups_helper::get_list_where_user_can_create_posts(r.user_id_ref()?)?;
r.set_response(PostsTargets::new(&friends, &groups))
}
}

View File

@ -12,7 +12,11 @@ use crate::routes::RequestResult;
/// Get current push notifications status for a connection
pub async fn get_status(r: &mut HttpRequestHandler) -> RequestResult {
let status = &r.user_access_token().unwrap().push_notifications_token.clone();
let status = &r
.user_access_token()
.unwrap()
.push_notifications_token
.clone();
r.set_response(PushNotificationsStatusAPI::new(status))
}
@ -50,4 +54,4 @@ pub async fn configure(r: &mut HttpRequestHandler) -> RequestResult {
account_helper::set_push_notification_token(r.user_access_token().unwrap(), status).await?;
r.ok()
}
}

Some files were not shown because too many files have changed in this diff Show More