1
0
mirror of https://gitlab.com/comunic/comunicapiv3 synced 2024-12-27 22:18:51 +00:00

Upgrade UserID to a structure

This commit is contained in:
Pierre HUBERT 2020-06-25 10:08:34 +02:00
parent 444cad6e09
commit 96f3217db4
25 changed files with 180 additions and 153 deletions

View File

@ -40,12 +40,12 @@ impl ConversationAPI {
pub fn new(conv: &Conversation) -> ConversationAPI {
ConversationAPI {
ID: conv.id,
ID_owner: conv.owner_id as u64,
ID_owner: conv.owner_id.id(),
last_active: conv.last_active,
name: ConvName(conv.name.clone()),
following: LegacyBool(conv.following),
saw_last_message: LegacyBool(conv.saw_last_message),
members: conv.members.iter().map(|x| x.clone() as u64).collect(),
members: conv.members.iter().map(|x| x.id()).collect(),
canEveryoneAddMembers: conv.can_everyone_add_members,
// TODO : update when call system is implemented

View File

@ -26,7 +26,7 @@ impl ConversationMessageAPI {
ConversationMessageAPI {
ID: msg.id,
convID: msg.conv_id,
ID_user: msg.user_id as u64,
ID_user: msg.user_id.id(),
time_insert: msg.time_sent,
message: msg.message.clone().unwrap_or(String::new()),
image_path: msg.image_path.as_ref().map(|f| user_data_url(f)),

View File

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

View File

@ -2,6 +2,7 @@
//!
//! @author Pierre Hubert
use serde::Serialize;
use crate::data::custom_emoji::CustomEmoji;
use crate::utils::user_data_utils::user_data_url;
@ -9,21 +10,19 @@ use crate::utils::user_data_utils::user_data_url;
#[allow(non_snake_case)]
pub struct CustomEmojiAPI {
id: u64,
userID: i64,
userID: u64,
shortcut: String,
url: String
url: String,
}
impl CustomEmojiAPI {
/// Create a new Custom Emoji API entry
pub fn new(custom_emoji: &CustomEmoji) -> CustomEmojiAPI {
CustomEmojiAPI {
id: custom_emoji.id,
userID: custom_emoji.user_id,
userID: custom_emoji.user_id.id(),
shortcut: custom_emoji.shortcut.to_string(),
url: user_data_url(&custom_emoji.path),
}
}
}

View File

@ -18,7 +18,7 @@ impl GlobalSearchResultAPI {
match res {
GlobalSearchResult::User(user_id) => GlobalSearchResultAPI {
kind: "user".to_string(),
id: user_id.clone() as u64,
id: user_id.id(),
},
GlobalSearchResult::Group(group_id) => GlobalSearchResultAPI {
kind: "group".to_string(),

View File

@ -19,7 +19,7 @@ impl UnreadConversationAPI {
id: conv.id,
conv_name: conv.name.clone().unwrap_or(String::new()),
last_active: conv.last_active,
userID: conv.user_id as u64,
userID: conv.user_id.id(),
message: conv.message.clone()
}
}

View File

@ -16,7 +16,7 @@ impl FindUserByVirtualDirectoryAPIResult {
/// Construct a new `FindUserByVirtualDirectoryAPIResult` instance
pub fn new(user_id: UserID) -> FindUserByVirtualDirectoryAPIResult {
FindUserByVirtualDirectoryAPIResult {
userID: user_id as u64
userID: user_id.id()
}
}
}

View File

@ -19,7 +19,7 @@ impl ResultFindVirtualDirectory {
match (user, group) {
// User
(Ok(u), _) => ResultFindVirtualDirectory { kind: "user".to_string(), id: u.id as u64 },
(Ok(u), _) => ResultFindVirtualDirectory { kind: "user".to_string(), id: u.id.id() },
// Group
(_, Ok(g)) => ResultFindVirtualDirectory { kind: "group".to_string(), id: g.id() },

View File

@ -3,18 +3,18 @@
//! @author Pierre Hubert
use serde::Serialize;
use crate::data::user::{User, UserPageStatus, UserID};
use crate::helpers::{friends_helper, custom_emojies_helper, background_image_helper, likes_helper, user_helper};
use crate::data::error::ResultBoxError;
use crate::utils::user_data_utils::user_data_url;
use crate::data::user::AccountImageVisibility::{EVERYONE, COMUNIC_USERS};
use crate::api_data::custom_emoji::CustomEmojiAPI;
use crate::data::error::ResultBoxError;
use crate::data::user::{User, UserID, UserPageStatus};
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::helpers::likes_helper::LikeType;
use crate::utils::user_data_utils::user_data_url;
#[derive(Serialize)]
#[allow(non_snake_case)]
pub struct APIUserInfo {
userID: i64,
userID: u64,
firstName: String,
lastName: String,
publicPage: bool,
@ -46,16 +46,16 @@ struct APIAdvancedInfo {
impl APIUserInfo {
/// Construct a new API user instance. Note: `user_id` is the ID of the user who makes the
/// requests, not the user whose we return information about!
pub fn new(user_id: Option<UserID>, info: &User) -> ResultBoxError<APIUserInfo> {
pub fn new(user_id: &Option<UserID>, info: &User) -> ResultBoxError<APIUserInfo> {
Ok(APIUserInfo {
userID: info.id,
userID: info.id.id(),
firstName: info.first_name.to_string(),
lastName: info.last_name.to_string(),
publicPage: info.status != UserPageStatus::PRIVATE,
openPage: info.status == UserPageStatus::OPEN,
virtualDirectory: info.virtual_directory.clone().unwrap_or(String::new()),
accountImage: APIUserInfo::get_account_image_url(user_id, info)?,
customEmojis: custom_emojies_helper::get_list_user(info.id)?
customEmojis: custom_emojies_helper::get_list_user(&info.id)?
.iter()
.map(|f| CustomEmojiAPI::new(f))
.collect(),
@ -64,18 +64,18 @@ impl APIUserInfo {
}
/// Get advanced user information
pub fn new_advanced_info(user_id: Option<UserID>, info: &User) -> ResultBoxError<APIUserInfo> {
let mut user = APIUserInfo::new(user_id, info)?;
let curr_user_id = user_id.unwrap_or(0);
pub fn new_advanced_info(user_id: &Option<UserID>, info: &User) -> ResultBoxError<APIUserInfo> {
let mut 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();
// 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)?
friends_helper::count_friends(&info.id)?
} else { 0 };
let likes_page = if signed_in {
likes_helper::is_liking(curr_user_id, info.id as u64, LikeType::USER)?
likes_helper::is_liking(&curr_user_id, info.id.id(), LikeType::USER)?
} else { false };
// Set advanced user information
@ -86,25 +86,25 @@ impl APIUserInfo {
noCommentOnHisPage: info.block_comments_on_his_page,
allowPostFromFriendOnHisPage: info.allow_posts_from_friends,
account_creation_time: info.account_creation_time,
backgroundImage: background_image_helper::get_url(info.id),
backgroundImage: background_image_helper::get_url(&info.id),
number_friends,
pageLikes: likes_helper::count(info.id as u64, LikeType::USER)?,
pageLikes: likes_helper::count(info.id.id(), LikeType::USER)?,
user_page_like: likes_page,
can_post_texts: user_helper::can_create_posts(curr_user_id, info.id)?
can_post_texts: user_helper::can_create_posts(&curr_user_id, &info.id)?,
});
Ok(user)
}
/// Get the URL of a specific user account image
pub fn get_account_image_url(user_id: Option<UserID>, user: &User) -> ResultBoxError<String> {
pub fn get_account_image_url(user_id: &Option<UserID>, user: &User) -> ResultBoxError<String> {
if !user.has_account_image() {
return Ok(User::default_account_image_url());
}
let user_account_image = Ok(user_data_url(user.account_image_path.as_ref().unwrap()));
if user.account_image_visibility == EVERYONE || user_id == Some(user.id) {
if user.account_image_visibility == EVERYONE || user_id == &Some(user.id.clone()) {
return user_account_image;
}
@ -113,7 +113,7 @@ impl APIUserInfo {
}
if user.account_image_visibility == COMUNIC_USERS ||
friends_helper::are_friend(user_id.unwrap(), user.id)? {
friends_helper::are_friend(&user_id.clone().unwrap(), &user.id)? {
return user_account_image;
}

View File

@ -34,7 +34,7 @@ pub fn login_user(request: &mut HttpRequestHandler) -> RequestResult {
/// Sign out user
pub fn logout_user(request: &mut HttpRequestHandler) -> RequestResult {
account_helper::destroy_login_tokens(
request.user_id()?,
&request.user_id()?,
request.api_client()
)?;
@ -43,5 +43,5 @@ pub fn logout_user(request: &mut HttpRequestHandler) -> RequestResult {
/// Get current user ID
pub fn user_id(request: &mut HttpRequestHandler) -> RequestResult {
request.set_response(CurrentUserID::new(request.user_id()?))
request.set_response(CurrentUserID::new(&request.user_id()?))
}

View File

@ -15,13 +15,17 @@ use crate::controllers::routes::RequestResult;
use crate::data::http_request_handler::HttpRequestHandler;
use crate::data::new_conversation::NewConversation;
use crate::data::new_conversation_message::NewConversationMessage;
use crate::data::user::UserID;
use crate::helpers::{conversations_helper, user_helper};
use crate::utils::string_utils::remove_html_nodes;
/// Create a new conversation
pub fn create(r: &mut HttpRequestHandler) -> RequestResult {
let name = r.post_string("name")?;
let mut members = r.post_numbers_list("users", 1)?;
let mut members = r.post_numbers_list("users", 1)?
.iter()
.map(|f| UserID::new(f.clone()))
.collect::<Vec<UserID>>();
// Adapt name
let name = match name.as_str() {
@ -31,13 +35,13 @@ pub fn create(r: &mut HttpRequestHandler) -> RequestResult {
// Check if members exists
for user in &members {
if !user_helper::exists(user.clone())? {
r.not_found(format!("User {} not found!", user))?;
if !user_helper::exists(user)? {
r.not_found(format!("User {} not found!", user.id()))?;
}
}
// Add current user ID if required
let curr_user_id = r.user_id()? as i64;
let curr_user_id = r.user_id()?;
if !members.contains(&curr_user_id) {
members.push(curr_user_id);
}
@ -57,7 +61,7 @@ pub fn create(r: &mut HttpRequestHandler) -> RequestResult {
/// Get the list of conversations of a user
pub fn get_list(r: &mut HttpRequestHandler) -> RequestResult {
let list = conversations_helper::get_list_user(r.user_id()?)?;
let list = conversations_helper::get_list_user(&r.user_id()?)?;
r.set_response(list.iter().map(|c| ConversationAPI::new(c)).collect::<Vec<ConversationAPI>>())
}
@ -65,7 +69,7 @@ pub fn get_list(r: &mut HttpRequestHandler) -> RequestResult {
/// Get information about a single conversation
pub fn get_single(r: &mut HttpRequestHandler) -> RequestResult {
let conversation_id = r.post_conv_id("conversationID")?;
let conv = conversations_helper::get_single(conversation_id, r.user_id()?)?;
let conv = conversations_helper::get_single(conversation_id, &r.user_id()?)?;
r.set_response(ConversationAPI::new(&conv))
}
@ -73,12 +77,12 @@ pub fn get_single(r: &mut HttpRequestHandler) -> RequestResult {
/// Update the settings of a conversation
pub fn update_settings(r: &mut HttpRequestHandler) -> RequestResult {
let conv_id = r.post_conv_id("conversationID")?;
let is_moderator = conversations_helper::is_user_moderator(r.user_id()?, conv_id)?;
let is_moderator = conversations_helper::is_user_moderator(&r.user_id()?, conv_id)?;
// Update following state, if required
if r.has_post_parameter("following") {
conversations_helper::set_following(
r.user_id()?,
&r.user_id()?,
conv_id,
r.post_bool("following")?,
)?;
@ -86,7 +90,11 @@ pub fn update_settings(r: &mut HttpRequestHandler) -> RequestResult {
// Update members list
if r.has_post_parameter("members") {
let mut members = r.post_numbers_list("members", 1)?;
let mut members = r.post_numbers_list("members", 1)?
.iter()
.map(|f| UserID::new(f.clone()))
.collect::<Vec<UserID>>();
let can_everyone_add_members = conversations_helper::can_everyone_add_members(conv_id)?;
if !is_moderator && !can_everyone_add_members {
@ -95,8 +103,8 @@ pub fn update_settings(r: &mut HttpRequestHandler) -> RequestResult {
// Check if the members of the conversation really exists
for member in &members {
if !user_helper::exists(member.clone())? {
r.not_found(format!("User {} not found!", member))?;
if !user_helper::exists(member)? {
r.not_found(format!("User {} not found!", member.id()))?;
}
}
@ -142,7 +150,7 @@ pub fn find_private(r: &mut HttpRequestHandler) -> RequestResult {
let allow_create = r.post_bool_opt("allowCreate", false);
// Query the database
let mut list = conversations_helper::find_private(r.user_id()?, other_user)?;
let mut list = conversations_helper::find_private(&r.user_id()?, &other_user)?;
if list.is_empty() {
if !allow_create {
@ -172,14 +180,14 @@ pub fn refresh_list(r: &mut HttpRequestHandler) -> RequestResult {
// Check for new conversations
if r.has_post_parameter("newConversations") {
for conv_id in r.post_numbers_list("newConversations", 0)? {
if !conversations_helper::does_user_belongs_to(r.user_id()?, conv_id as u64)? {
if !conversations_helper::does_user_belongs_to(&r.user_id()?, conv_id)? {
r.forbidden(format!("Your do not belongs to conversation {} !", conv_id))?;
}
let list_conv = conversations_helper::get_last_messages(conv_id as u64, 10)?;
let list_conv = conversations_helper::get_last_messages(conv_id , 10)?;
list.insert(conv_id as u64, list_conv);
conversations_helper::mark_user_seen(conv_id as u64, r.user_id()?)?;
conversations_helper::mark_user_seen(conv_id as u64, &r.user_id()?)?;
}
}
@ -202,14 +210,14 @@ pub fn refresh_list(r: &mut HttpRequestHandler) -> RequestResult {
let last_message_id = v["last_message_id"].as_u64().unwrap_or(0);
// Check user rights
if !conversations_helper::does_user_belongs_to(r.user_id()?, conv_id)? {
if !conversations_helper::does_user_belongs_to(&r.user_id()?, conv_id)? {
return r.forbidden(format!("You do not belong to conversation {}!", conv_id));
}
let list_conv = conversations_helper::get_new_messages(conv_id, last_message_id)?;
list.insert(conv_id, list_conv);
conversations_helper::mark_user_seen(conv_id as u64, r.user_id()?)?;
conversations_helper::mark_user_seen(conv_id as u64, &r.user_id()?)?;
}
}
@ -229,7 +237,7 @@ pub fn refresh_single(r: &mut HttpRequestHandler) -> RequestResult {
_ => conversations_helper::get_new_messages(conv_id, last_message_id)?,
};
conversations_helper::mark_user_seen(conv_id, r.user_id()?)?;
conversations_helper::mark_user_seen(conv_id, &r.user_id()?)?;
r.set_response(ConversationMessageAPI::for_list(&messages))
}
@ -279,14 +287,14 @@ pub fn send_message(r: &mut HttpRequestHandler) -> RequestResult {
/// Count the number of unread conversation of the user
pub fn count_unread(r: &mut HttpRequestHandler) -> RequestResult {
let num = conversations_helper::count_unread_for_user(r.user_id()?)?;
let num = conversations_helper::count_unread_for_user(&r.user_id()?)?;
r.set_response(ResultCountUnreadConversations::new(num))
}
/// Get the list of unread conversations of a user
pub fn list_unread(r: &mut HttpRequestHandler) -> RequestResult {
let list = conversations_helper::get_list_unread(r.user_id()?)?;
let list = conversations_helper::get_list_unread(&r.user_id()?)?;
r.set_response(UnreadConversationAPI::for_list(&list))
}
@ -295,7 +303,7 @@ pub fn list_unread(r: &mut HttpRequestHandler) -> RequestResult {
pub fn delete_conversation(r: &mut HttpRequestHandler) -> RequestResult {
let conv_id = r.post_conv_id("conversationID")?;
conversations_helper::remove_user_from_conversation(r.user_id()?, conv_id)?;
conversations_helper::remove_user_from_conversation(&r.user_id()?, conv_id)?;
r.success("The conversation has been deleted")
}
@ -305,7 +313,7 @@ pub fn update_message(r: &mut HttpRequestHandler) -> RequestResult {
let msg_id = r.post_u64("messageID")?;
let new_content = r.post_string_opt("content", 3, true)?;
if !conversations_helper::is_message_owner(r.user_id()?, msg_id)? {
if !conversations_helper::is_message_owner(&r.user_id()?, msg_id)? {
r.forbidden("You are not the owner of this message!".to_string())?;
}
@ -318,7 +326,7 @@ pub fn update_message(r: &mut HttpRequestHandler) -> RequestResult {
pub fn delete_message(r: &mut HttpRequestHandler) -> RequestResult {
let msg_id = r.post_u64("messageID")?;
if !conversations_helper::is_message_owner(r.user_id()?, msg_id)? {
if !conversations_helper::is_message_owner(&r.user_id()?, msg_id)? {
r.forbidden("You are not the owner of this message!".to_string())?;
}

View File

@ -13,7 +13,10 @@ pub fn search_user(r: &mut HttpRequestHandler) -> RequestResult {
let query = r.post_string_opt("query", 1, true)?;
let limit = r.post_u64_opt("searchLimit", 5)?;
let list = user_helper::search_user(&query, limit)?;
let list = user_helper::search_user(&query, limit)?
.iter()
.map(|f| f.id())
.collect::<Vec<u64>>();
r.set_response(list)
}

View File

@ -15,8 +15,8 @@ use crate::helpers::user_helper::find_user_by_id;
/// Get information about a single user
pub fn get_single(request: &mut HttpRequestHandler) -> RequestResult {
let user_id = request.post_i64("userID")?;
let user = match user_helper::find_user_by_id(user_id) {
let user_id = UserID::new(request.post_u64("userID")?);
let user = match user_helper::find_user_by_id(&user_id) {
Ok(user) => user,
Err(e) => {
println!("Error while getting user info: {}", e);
@ -25,22 +25,23 @@ pub fn get_single(request: &mut HttpRequestHandler) -> RequestResult {
}
};
request.set_response(APIUserInfo::new(request.user_id_opt(), &user)?)
request.set_response(APIUserInfo::new(&request.user_id_opt(), &user)?)
}
/// Get information about several users
pub fn get_multiple(request: &mut HttpRequestHandler) -> RequestResult {
let user_ids = request.post_numbers_list("usersID", 1)?;
let mut map: HashMap<UserID, APIUserInfo> = HashMap::new();
let mut map: HashMap<u64, APIUserInfo> = HashMap::new();
for user_id in user_ids {
let user_id = UserID::new(user_id);
let user = request.ok_or_not_found(
find_user_by_id(user_id),
find_user_by_id(&user_id),
"At least one user was not found!",
)?;
map.insert(user_id, APIUserInfo::new(request.user_id_opt(), &user)?);
map.insert(user_id.id(), APIUserInfo::new(&request.user_id_opt(), &user)?);
}
request.set_response(map)
@ -50,10 +51,10 @@ pub fn get_multiple(request: &mut HttpRequestHandler) -> RequestResult {
pub fn get_advanced_info(request: &mut HttpRequestHandler) -> RequestResult {
let user_id = request.post_user_id("userID")?;
if !user_helper::can_see_user_page(request.user_id_opt().unwrap_or(0), user_id)? {
if !user_helper::can_see_user_page(&request.user_id_opt().unwrap_or(UserID::new(0)), &user_id)? {
request.forbidden("You are not allowed to see this user page!".to_string())?;
}
let user = user_helper::find_user_by_id(user_id)?;
request.set_response(APIUserInfo::new_advanced_info(request.user_id_opt(), &user)?)
let user = user_helper::find_user_by_id(&user_id)?;
request.set_response(APIUserInfo::new_advanced_info(&request.user_id_opt(), &user)?)
}

View File

@ -367,7 +367,7 @@ impl HttpRequestHandler {
/// Get user ID. This function assess that a user ID is available to continue
pub fn user_id(&self) -> ResultBoxError<UserID> {
match self.curr_user_id {
match self.curr_user_id.clone() {
Some(s) => Ok(s),
None => Err(ExecError::boxed_new("Could not get required user ID!"))
}
@ -375,7 +375,7 @@ impl HttpRequestHandler {
/// Get a user ID, if available
pub fn user_id_opt(&self) -> Option<UserID> {
self.curr_user_id
self.curr_user_id.clone()
}
/// Get an email included in the request
@ -390,7 +390,7 @@ impl HttpRequestHandler {
}
/// Get a list of integers included in the request
pub fn post_numbers_list(&mut self, name: &str, min_len: usize) -> ResultBoxError<Vec<i64>> {
pub fn post_numbers_list(&mut self, name: &str, min_len: usize) -> ResultBoxError<Vec<u64>> {
let param = self.post_string_opt(name, min_len, min_len != 0)?;
let mut list = vec![];
@ -399,7 +399,7 @@ impl HttpRequestHandler {
continue;
}
list.push(split.parse::<i64>()?);
list.push(split.parse::<u64>()?);
}
if list.len() < min_len {
@ -411,14 +411,14 @@ impl HttpRequestHandler {
/// Get the ID of a user included in a POST request
pub fn post_user_id(&mut self, name: &str) -> ResultBoxError<UserID> {
let user_id = self.post_i64(name)?;
let user_id = UserID::new(self.post_u64(name)?);
if user_id < 1 {
if user_id.id() < 1 {
self.bad_request(format!("Invalid user specified in '{}'!", name))?;
}
if !user_helper::exists(user_id)? {
self.not_found(format!("User with ID {} not found!", user_id))?;
if !user_helper::exists(&user_id)? {
self.not_found(format!("User with ID {} not found!", user_id.id()))?;
}
Ok(user_id)
@ -444,7 +444,7 @@ impl HttpRequestHandler {
pub fn post_conv_id(&mut self, name: &str) -> ResultBoxError<u64> {
let conv_id = self.post_u64(name)?;
if !conversations_helper::does_user_belongs_to(self.user_id()?, conv_id)? {
if !conversations_helper::does_user_belongs_to(&self.user_id()?, conv_id)? {
self.forbidden(format!("You do not belong to conversation {} !", conv_id))?;
}

View File

@ -3,14 +3,31 @@ use crate::utils::user_data_utils::user_data_url;
///! User information
///!
///! @author Pierre Hubert
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct UserID(u64);
pub type UserID = i64;
impl UserID {
/// Initialize a new user ID object
pub fn new(id: u64) -> UserID {
UserID(id)
}
/// Get the current ID stored in this structure
pub fn id(&self) -> u64 {
self.0
}
/// Check if the ID currently stored in this structure is valid or not
pub fn is_valid(&self) -> bool {
self.0 > 0
}
}
#[derive(Debug, PartialEq)]
pub enum UserPageStatus {
OPEN,
PUBLIC,
PRIVATE
PRIVATE,
}
#[derive(Debug, PartialEq)]
@ -18,7 +35,7 @@ pub enum UserPageStatus {
pub enum AccountImageVisibility {
FRIENDS,
COMUNIC_USERS,
EVERYONE
EVERYONE,
}
#[derive(Debug)]
@ -41,7 +58,6 @@ pub struct User {
}
impl User {
/// Get the URL pointing to the default account image
pub fn default_account_image_url() -> String {
user_data_url(crate::constants::DEFAULT_ACCOUNT_IMAGE)

View File

@ -25,14 +25,14 @@ pub fn login_user(email: &str, password: &str, client: &APIClient) -> ResultBoxE
}
// Check if we already have a login token for this user
if let Ok(token) = get_client_tokens(user.id, client) {
if let Ok(token) = get_client_tokens(&user.id, client) {
return Ok(token.token);
}
// Create new login tokens
let new_token = UserAccessToken {
user_id: user.id,
user_id: user.id.clone(),
client_id: client.id,
token: rand_str(150),
};
@ -40,7 +40,7 @@ pub fn login_user(email: &str, password: &str, client: &APIClient) -> ResultBoxE
// Save it
database::insert(
InsertQuery::new(USER_ACCESS_TOKENS_TABLE)
.add_i64("user_id", new_token.user_id)
.add_user_id("user_id", &new_token.user_id)
.add_u32("service_id", client.id)
.add_str("token1", &new_token.token)
.add_str("token2", "dummy_data")
@ -50,14 +50,14 @@ pub fn login_user(email: &str, password: &str, client: &APIClient) -> ResultBoxE
}
/// Get user login tokens
fn get_client_tokens(user_id: UserID, client: &APIClient) -> ResultBoxError<UserAccessToken> {
fn get_client_tokens(user_id: &UserID, client: &APIClient) -> ResultBoxError<UserAccessToken> {
database::query_row(
QueryInfo::new(USER_ACCESS_TOKENS_TABLE)
.cond_i64("user_id", user_id)
.cond_user_id("user_id", user_id)
.cond_u32("service_id", client.id),
|res| {
Ok(UserAccessToken {
user_id: res.get_int64("user_id")?,
user_id: res.get_user_id("user_id")?,
client_id: res.get_int64("service_id")? as u32,
token: res.get_str("token1")?,
})
@ -72,16 +72,16 @@ pub fn get_user_by_login_token(token: &str, client: &APIClient) -> ResultBoxErro
.cond_u32("service_id", client.id)
.cond("token1", token)
.add_field("user_id"),
|res| res.get_int64("user_id"),
|res| res.get_user_id("user_id"),
)
}
/// Destroy a given user login tokens
pub fn destroy_login_tokens(id: UserID, client: &APIClient) -> ResultBoxError<()> {
pub fn destroy_login_tokens(id: &UserID, client: &APIClient) -> ResultBoxError<()> {
database::delete(DeleteQuery::new(USER_ACCESS_TOKENS_TABLE)
.cond_u32("service_id", client.id)
.cond_i64("user_id", id)
.cond_user_id("user_id", id)
)?;
Ok(())

View File

@ -6,6 +6,6 @@
use crate::data::user::UserID;
use crate::utils::user_data_utils::user_data_url;
pub fn get_url(_user_id: UserID) -> String {
pub fn get_url(_user_id: &UserID) -> String {
user_data_url("imgfond/0.jpg")
}

View File

@ -19,7 +19,7 @@ use crate::utils::user_data_utils::user_data_path;
pub fn create(conv: &NewConversation) -> ResultBoxError<u64> {
// Create the conversation in the main table
let conv_id = InsertQuery::new(CONV_LIST_TABLE)
.add_user_id("user_id", conv.owner_id)
.add_user_id("user_id", &conv.owner_id)
.add_str("name", conv.name.clone().unwrap_or(String::new()).as_str())
.add_u64("last_active", time())
.add_u64("creation_time", time())
@ -34,14 +34,14 @@ pub fn create(conv: &NewConversation) -> ResultBoxError<u64> {
follow = conv.owner_following;
}
add_member(conv_id, member.clone(), follow)?;
add_member(conv_id, member, follow)?;
}
Ok(conv_id)
}
/// Add a member to a conversation
pub fn add_member(conv_id: u64, user_id: UserID, following: bool) -> ResultBoxError<()> {
pub fn add_member(conv_id: u64, user_id: &UserID, following: bool) -> ResultBoxError<()> {
InsertQuery::new(CONV_USERS_TABLE)
.add_u64("conv_id", conv_id)
.add_user_id("user_id", user_id)
@ -54,7 +54,7 @@ pub fn add_member(conv_id: u64, user_id: UserID, following: bool) -> ResultBoxEr
}
/// Remove a member from a conversation
pub fn remove_member(conv_id: u64, user_id: UserID) -> ResultBoxError<()> {
pub fn remove_member(conv_id: u64, user_id: &UserID) -> ResultBoxError<()> {
database::DeleteQuery::new(CONV_USERS_TABLE)
.cond_u64("conv_id", conv_id)
.cond_user_id("user_id", user_id)
@ -62,7 +62,7 @@ pub fn remove_member(conv_id: u64, user_id: UserID) -> ResultBoxError<()> {
}
/// Get the list of conversations of a specific user
pub fn get_list_user(user_id: UserID) -> ResultBoxError<Vec<Conversation>> {
pub fn get_list_user(user_id: &UserID) -> ResultBoxError<Vec<Conversation>> {
database::QueryInfo::new(CONV_LIST_TABLE)
.alias("l")
@ -85,7 +85,7 @@ pub fn get_list_user(user_id: UserID) -> ResultBoxError<Vec<Conversation>> {
}
/// Get information about a single conversation
pub fn get_single(conv_id: u64, user_id: UserID) -> ResultBoxError<Conversation> {
pub fn get_single(conv_id: u64, user_id: &UserID) -> ResultBoxError<Conversation> {
// Tables
database::QueryInfo::new(CONV_LIST_TABLE)
.alias("l")
@ -112,7 +112,7 @@ pub fn get_list_members(conv_id: u64) -> ResultBoxError<Vec<UserID>> {
}
/// Check if a user belongs to a conversation or not
pub fn does_user_belongs_to(user_id: UserID, conv_id: u64) -> ResultBoxError<bool> {
pub fn does_user_belongs_to(user_id: &UserID, conv_id: u64) -> ResultBoxError<bool> {
Ok(database::QueryInfo::new(CONV_USERS_TABLE)
.cond_u64("conv_id", conv_id)
.cond_user_id("user_id", user_id)
@ -120,7 +120,7 @@ pub fn does_user_belongs_to(user_id: UserID, conv_id: u64) -> ResultBoxError<boo
}
/// Check out wheter a user is the moderator of a conversation or not
pub fn is_user_moderator(user_id: UserID, conv_id: u64) -> ResultBoxError<bool> {
pub fn is_user_moderator(user_id: &UserID, conv_id: u64) -> ResultBoxError<bool> {
Ok(database::QueryInfo::new(CONV_LIST_TABLE)
.cond_u64("id", conv_id)
.cond_user_id("user_id", user_id)
@ -136,7 +136,7 @@ pub fn can_everyone_add_members(conv_id: u64) -> ResultBoxError<bool> {
}
/// Set whether a user is following a conversation or not
pub fn set_following(user_id: UserID, conv_id: u64, following: bool) -> ResultBoxError<()> {
pub fn set_following(user_id: &UserID, conv_id: u64, following: bool) -> ResultBoxError<()> {
database::UpdateInfo::new(CONV_USERS_TABLE)
.cond_u64("conv_id", conv_id)
.cond_user_id("user_id", user_id)
@ -154,7 +154,7 @@ pub fn set_members(conv_id: u64, new_list: &Vec<UserID>, can_delete: bool) -> Re
continue;
}
add_member(conv_id, member.clone(), true)?;
add_member(conv_id, member, true)?;
}
// Remove a member
@ -163,7 +163,7 @@ pub fn set_members(conv_id: u64, new_list: &Vec<UserID>, can_delete: bool) -> Re
if new_list.contains(&member) {
continue;
}
remove_member(conv_id, member)?;
remove_member(conv_id, &member)?;
}
}
@ -188,7 +188,7 @@ pub fn set_can_everyone_add_members(conv_id: u64, allow: bool) -> ResultBoxError
}
/// Search for private conversation between two users
pub fn find_private(user_1: UserID, user_2: UserID) -> ResultBoxError<Vec<u64>> {
pub fn find_private(user_1: &UserID, user_2: &UserID) -> ResultBoxError<Vec<u64>> {
database::QueryInfo::new(CONV_USERS_TABLE)
.alias("t1")
@ -246,7 +246,7 @@ pub fn get_older_messages(conv_id: u64, start_id: u64, limit: u64) -> ResultBoxE
}
/// Get all the messages of a single user for a conversation
pub fn get_user_messages_for_conversations(conv_id: u64, user_id: UserID) -> ResultBoxError<Vec<ConversationMessage>> {
pub fn get_user_messages_for_conversations(conv_id: u64, user_id: &UserID) -> ResultBoxError<Vec<ConversationMessage>> {
database::QueryInfo::new(CONV_MESSAGES_TABLE)
.cond_u64("conv_id", conv_id)
.cond_user_id("user_id", user_id)
@ -274,7 +274,7 @@ pub fn send_message(msg: &NewConversationMessage) -> ResultBoxError<()> {
// Insert the message in the database
database::InsertQuery::new(CONV_MESSAGES_TABLE)
.add_u64("conv_id", msg.conv_id)
.add_user_id("user_id", msg.user_id)
.add_user_id("user_id", &msg.user_id)
.add_u64("time_insert", t)
.add_str("message", msg.message.as_str())
.add_opt_str("image_path", msg.image_path.as_ref())
@ -292,7 +292,7 @@ pub fn send_message(msg: &NewConversationMessage) -> ResultBoxError<()> {
.cond_legacy_bool("saw_last_message", true)
.custom_where("user_id != ?")
.add_custom_where_arg_u64(msg.user_id as u64)
.add_custom_where_arg_u64(msg.user_id.id())
.set_legacy_bool("saw_last_message", false)
.exec()?;
@ -332,7 +332,7 @@ pub fn delete_message_by_id(id: u64) -> ResultBoxError<()> {
}
/// Count the number of unread conversation for a specified user
pub fn count_unread_for_user(user_id: UserID) -> ResultBoxError<usize> {
pub fn count_unread_for_user(user_id: &UserID) -> ResultBoxError<usize> {
database::QueryInfo::new(CONV_USERS_TABLE)
.cond_user_id("user_id", user_id)
.cond_legacy_bool("saw_last_message", false)
@ -341,7 +341,7 @@ pub fn count_unread_for_user(user_id: UserID) -> ResultBoxError<usize> {
}
/// Get the list of unread conversations of a user
pub fn get_list_unread(user_id: UserID) -> ResultBoxError<Vec<UnreadConversation>> {
pub fn get_list_unread(user_id: &UserID) -> ResultBoxError<Vec<UnreadConversation>> {
database::QueryInfo::new(CONV_USERS_TABLE)
.alias("users")
.join(CONV_LIST_TABLE, "list", "users.conv_id = list.id")
@ -364,7 +364,7 @@ pub fn get_list_unread(user_id: UserID) -> ResultBoxError<Vec<UnreadConversation
}
/// Indicate that a user has seen the last messages of a conversation
pub fn mark_user_seen(conv_id: u64, user_id: UserID) -> ResultBoxError<()> {
pub fn mark_user_seen(conv_id: u64, user_id: &UserID) -> ResultBoxError<()> {
database::UpdateInfo::new(CONV_USERS_TABLE)
.cond_u64("conv_id", conv_id)
.cond_user_id("user_id", user_id)
@ -374,7 +374,7 @@ pub fn mark_user_seen(conv_id: u64, user_id: UserID) -> ResultBoxError<()> {
}
/// Remove a user from a conversation
pub fn remove_user_from_conversation(user_id: UserID, conv_id: u64) -> ResultBoxError<()> {
pub fn remove_user_from_conversation(user_id: &UserID, conv_id: u64) -> ResultBoxError<()> {
if is_user_moderator(user_id, conv_id)? {
delete_conversation(conv_id)
} else {
@ -403,7 +403,7 @@ pub fn delete_conversation(conv_id: u64) -> ResultBoxError<()> {
}
/// Delete a conversation membership
pub fn delete_member(user_id: UserID, conv_id: u64) -> ResultBoxError<()> {
pub fn delete_member(user_id: &UserID, conv_id: u64) -> ResultBoxError<()> {
for msg in get_user_messages_for_conversations(conv_id, user_id)? {
delete_message(&msg)?;
}
@ -415,7 +415,7 @@ pub fn delete_member(user_id: UserID, conv_id: u64) -> ResultBoxError<()> {
}
/// Check out whether a user is the owner of a message or not
pub fn is_message_owner(user_id: UserID, message_id: u64) -> ResultBoxError<bool> {
pub fn is_message_owner(user_id: &UserID, message_id: u64) -> ResultBoxError<bool> {
database::QueryInfo::new(CONV_MESSAGES_TABLE)
.cond_u64("id", message_id)
.cond_user_id("user_id", user_id)

View File

@ -9,9 +9,9 @@ use crate::helpers::database;
use crate::constants::database_tables_names::EMOJIS_TABLE;
/// Get the list of emojies of a user
pub fn get_list_user(user_id: UserID) -> ResultBoxError<Vec<CustomEmoji>> {
pub fn get_list_user(user_id: &UserID) -> ResultBoxError<Vec<CustomEmoji>> {
database::QueryInfo::new(EMOJIS_TABLE)
.cond_i64("user_id", user_id)
.cond_user_id("user_id", user_id)
.exec(db_to_custom_emoji)
}
@ -19,7 +19,7 @@ pub fn get_list_user(user_id: UserID) -> ResultBoxError<Vec<CustomEmoji>> {
fn db_to_custom_emoji(row: &database::RowResult) -> ResultBoxError<CustomEmoji> {
Ok(CustomEmoji {
id: row.get_u64("id")?,
user_id: row.get_int64("user_id")?,
user_id: row.get_user_id("user_id")?,
shortcut: row.get_str("shortcut")?,
path: row.get_str("path")?
})

View File

@ -138,8 +138,8 @@ impl QueryInfo {
self
}
pub fn cond_user_id(mut self, key: &str, val: UserID) -> QueryInfo {
self.conditions.insert(key.to_string(), val.to_string());
pub fn cond_user_id(mut self, key: &str, val: &UserID) -> QueryInfo {
self.conditions.insert(key.to_string(), val.id().to_string());
self
}
@ -290,7 +290,7 @@ impl<'a> RowResult<'a> {
/// Get the ID of a user included in the request
pub fn get_user_id(&self, name: &str) -> ResultBoxError<UserID> {
self.get_int64(name)
Ok(UserID::new(self.get_u64(name)?))
}
/// Get the ID of a group included in the response
@ -514,8 +514,8 @@ impl InsertQuery {
self
}
pub fn add_user_id(mut self, key: &str, value: UserID) -> InsertQuery {
self.values.insert(key.to_string(), Value::from(value));
pub fn add_user_id(mut self, key: &str, value: &UserID) -> InsertQuery {
self.values.insert(key.to_string(), Value::from(value.id()));
self
}
@ -611,8 +611,8 @@ impl DeleteQuery {
self
}
pub fn cond_user_id(mut self, key: &str, value: UserID) -> DeleteQuery {
self.conditions.insert(key.to_string(), Value::from(value));
pub fn cond_user_id(mut self, key: &str, value: &UserID) -> DeleteQuery {
self.conditions.insert(key.to_string(), Value::from(value.id()));
self
}
@ -666,8 +666,8 @@ impl UpdateInfo {
}
/// Filter with a user id
pub fn cond_user_id(mut self, name: &str, val: UserID) -> UpdateInfo {
self.cond.insert(name.to_string(), Value::Int(val));
pub fn cond_user_id(mut self, name: &str, val: &UserID) -> UpdateInfo {
self.cond.insert(name.to_string(), Value::UInt(val.id()));
self
}

View File

@ -10,23 +10,23 @@ use crate::constants::database_tables_names::FRIENDS_TABLE;
use crate::helpers::database::QueryInfo;
/// Check out whether two users are friend or not
pub fn are_friend(user_one: UserID, user_two: UserID) -> ResultBoxError<bool> {
pub fn are_friend(user_one: &UserID, user_two: &UserID) -> ResultBoxError<bool> {
Ok(database::count(QueryInfo::new(FRIENDS_TABLE)
.cond_i64("ID_personne", user_one)
.cond_i64("ID_amis", user_two)
.cond_user_id("ID_personne", user_one)
.cond_user_id("ID_amis", user_two)
.cond_i64("actif", 1))? > 0)
}
/// Count the number of friends of a user
pub fn count_friends(user_id: UserID) -> ResultBoxError<usize> {
pub fn count_friends(user_id: &UserID) -> ResultBoxError<usize> {
QueryInfo::new(FRIENDS_TABLE)
.cond_i64("ID_amis", user_id)
.cond_user_id("ID_amis", user_id)
.cond_u32("actif", 1)
.exec_count()
}
/// Check if a user can create posts on another friend's page
pub fn can_post_texts(user_id: UserID, target_user: UserID) -> ResultBoxError<bool> {
pub fn can_post_texts(user_id: &UserID, target_user: &UserID) -> ResultBoxError<bool> {
QueryInfo::new(FRIENDS_TABLE)
.cond_user_id("ID_personne", target_user)
.cond_user_id("ID_amis", user_id)

View File

@ -97,7 +97,7 @@ pub fn create(group: &NewGroup) -> ResultBoxError<GroupID> {
// First, create the group
let group_id = database::InsertQuery::new(GROUPS_LIST_TABLE)
.add_u64("time_create", time())
.add_user_id("userid_create", group.owner_id)
.add_user_id("userid_create", &group.owner_id)
.add_str("name", &group.name)
.insert()?.ok_or(ExecError::new("Could not get group ID!"))?;
let group_id = GroupID::new(group_id);
@ -105,7 +105,7 @@ pub fn create(group: &NewGroup) -> ResultBoxError<GroupID> {
// Insert first member
insert_member(&GroupMember {
id: 0,
user_id: group.owner_id,
user_id: group.owner_id.clone(),
group_id: group_id.clone(),
time_create: time(),
level: GroupMembershipLevel::ADMINISTRATOR,
@ -119,7 +119,7 @@ pub fn create(group: &NewGroup) -> ResultBoxError<GroupID> {
pub fn insert_member(m: &GroupMember) -> ResultBoxError<()> {
database::InsertQuery::new(GROUPS_MEMBERS_TABLE)
.add_group_id("groups_id", &m.group_id)
.add_user_id("user_id", m.user_id)
.add_user_id("user_id", &m.user_id)
.add_u64("time_create", m.time_create)
.add_u32("level", m.level.to_db())
.insert_drop_result()
@ -129,7 +129,7 @@ pub fn insert_member(m: &GroupMember) -> ResultBoxError<()> {
pub fn get_list_user(user_id: UserID, only_followed: bool) -> ResultBoxError<Vec<GroupID>> {
let mut query = database::QueryInfo::new(GROUPS_MEMBERS_TABLE)
.add_field("groups_id")
.cond_user_id("user_id", user_id);
.cond_user_id("user_id", &user_id);
if only_followed {
query = query.cond_legacy_bool("following", true);
@ -176,7 +176,7 @@ pub fn search_group(query: &str, limit: u64) -> ResultBoxError<Vec<GroupID>> {
pub fn get_membership(group_id: &GroupID, user_id: Option<UserID>) -> ResultBoxError<GroupMember> {
let default_membership = GroupMember {
id: 0,
user_id: 0,
user_id: UserID::new(0),
group_id: group_id.clone(),
time_create: 0,
level: GroupMembershipLevel::VISITOR,
@ -191,7 +191,7 @@ pub fn get_membership(group_id: &GroupID, user_id: Option<UserID>) -> ResultBoxE
Ok(database::QueryInfo::new(GROUPS_MEMBERS_TABLE)
.cond_group_id("groups_id", group_id)
.cond_user_id("user_id", user_id)
.cond_user_id("user_id", &user_id)
.query_row(db_to_group_member)
.unwrap_or(default_membership))
}
@ -203,7 +203,7 @@ pub fn get_membership_level(group_id: &GroupID, user_id: Option<UserID>) -> Resu
Some(user_id) => {
let level = database::QueryInfo::new(GROUPS_MEMBERS_TABLE)
.cond_group_id("groups_id", group_id)
.cond_user_id("user_id", user_id)
.cond_user_id("user_id", &user_id)
.add_field("level")
.query_row(|f| f.get_u32("level"))
.unwrap_or(GroupMembershipLevel::VISITOR.to_db());

View File

@ -36,14 +36,14 @@ pub fn count(id: u64, kind: LikeType) -> ResultBoxError<usize> {
}
/// Check if a user likes an element or not
pub fn is_liking(user_id: UserID, id: u64, kind: LikeType) -> ResultBoxError<bool> {
if user_id == 0 {
pub fn is_liking(user_id: &UserID, id: u64, kind: LikeType) -> ResultBoxError<bool> {
if !user_id.is_valid() {
return Ok(false);
}
Ok(QueryInfo::new(LIKES_TABLE)
.cond_u64("ID_type", id)
.cond_i64("ID_personne", user_id)
.cond_user_id("ID_personne", user_id)
.cond("type", kind.to_db_type().as_ref())
.exec_count()? > 0)
}

View File

@ -10,9 +10,9 @@ use crate::helpers::friends_helper::are_friend;
/// @author Pierre Hubert
/// Get & return information about a user based on its ID
pub fn find_user_by_id(id: UserID) -> ResultBoxError<User> {
pub fn find_user_by_id(id: &UserID) -> ResultBoxError<User> {
exec_get_user_query(
database::QueryInfo::new(USERS_TABLE).cond_i64("ID", id))
database::QueryInfo::new(USERS_TABLE).cond_user_id("ID", id))
}
/// Get & return information about a user based on his email
@ -49,7 +49,7 @@ fn exec_get_user_query(query: database::QueryInfo) -> ResultBoxError<User> {
};
Ok(User {
id: res.get_int64("ID")?,
id: res.get_user_id("ID")?,
email: res.get_str("mail")?,
password: res.get_str("password")?,
first_name: res.get_str("prenom")?,
@ -69,14 +69,14 @@ fn exec_get_user_query(query: database::QueryInfo) -> ResultBoxError<User> {
}
/// Check out whether a given id maps to a user or not
pub fn exists(id: UserID) -> ResultBoxError<bool> {
pub fn exists(id: &UserID) -> ResultBoxError<bool> {
Ok(database::QueryInfo::new(USERS_TABLE)
.cond_i64("ID", id)
.cond_user_id("ID", id)
.exec_count()? > 0)
}
/// Check if a given user can see another user's page
pub fn can_see_user_page(user_id: UserID, target_user: UserID) -> ResultBoxError<bool> {
pub fn can_see_user_page(user_id: &UserID, target_user: &UserID) -> ResultBoxError<bool> {
if user_id == target_user {
return Ok(true);
}
@ -89,7 +89,7 @@ pub fn can_see_user_page(user_id: UserID, target_user: UserID) -> ResultBoxError
}
// The user need to be signed in
if user_id <= 0 {
if user_id.id() <= 0 {
return Ok(false);
}
@ -107,15 +107,15 @@ pub fn can_see_user_page(user_id: UserID, target_user: UserID) -> ResultBoxError
}
/// Check out whether a user allow posts on his page or not
pub fn allow_posts_on_his_page(user_id: UserID) -> ResultBoxError<bool> {
pub fn allow_posts_on_his_page(user_id: &UserID) -> ResultBoxError<bool> {
Ok(find_user_by_id(user_id)?.allow_posts_from_friends)
}
/// Check out if a user can create posts on another user page
pub fn can_create_posts(user_id: UserID, target_id: UserID) -> ResultBoxError<bool> {
pub fn can_create_posts(user_id: &UserID, target_id: &UserID) -> ResultBoxError<bool> {
// Login required
if user_id <= 0 {
if !user_id.is_valid() {
return Ok(false);
}

View File

@ -28,7 +28,7 @@ pub fn user_data_path(uri: &Path) -> PathBuf {
/// This function returns the relative folder path in user data directory where the file can be
/// created
pub fn prepare_file_creation(user_id: UserID, folder: &str) -> ResultBoxError<PathBuf> {
let subfolder = match user_id {
let subfolder = match user_id.id() {
0 => Path::new(folder).to_path_buf(),
id => Path::new(folder).join(to_string(&id)?)
};