Skip to content

Commit

Permalink
Remove users table
Browse files Browse the repository at this point in the history
  • Loading branch information
exul committed Oct 13, 2017
1 parent 9a743f0 commit 1b76ba9
Show file tree
Hide file tree
Showing 21 changed files with 102 additions and 197 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
CREATE TABLE users_on_rocketchat_servers (
is_virtual_user BOOLEAN NOT NULL,
last_message_sent BIG INT NOT NULL DEFAULT 0,
matrix_user_id VARCHAR NOT NULL,
rocketchat_server_id VARCHAR NOT NULL,
rocketchat_user_id VARCHAR,
Expand Down
2 changes: 2 additions & 0 deletions src/matrix-rocketchat/api/matrix/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ pub trait MatrixApi: Send + Sync + MatrixApiClone {
fn create_room(&self, room_name: Option<String>, room_alias_name: Option<String>, creator_id: &UserId) -> Result<RoomId>;
/// Delete a room alias.
fn delete_room_alias(&self, matrix_room_alias_id: RoomAliasId) -> Result<()>;
/// Check if a user with the given ID already exists on the homeserver
fn does_user_exist(&self, matrix_user_id: UserId) -> Result<bool>;
/// Forget a room.
fn forget_room(&self, matrix_room_id: RoomId) -> Result<()>;
/// Get the room id based on the room alias.
Expand Down
10 changes: 10 additions & 0 deletions src/matrix-rocketchat/api/matrix/r0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use ruma_client_api::r0::membership::forget_room::{self, Endpoint as ForgetRoomE
use ruma_client_api::r0::membership::invite_user::{self, Endpoint as InviteUserEndpoint};
use ruma_client_api::r0::membership::join_room_by_id::{self, Endpoint as JoinRoomByIdEndpoint};
use ruma_client_api::r0::membership::leave_room::{self, Endpoint as LeaveRoomEndpoint};
use ruma_client_api::r0::profile::get_display_name::{self, Endpoint as GetDisplayNameEndpoint};
use ruma_client_api::r0::profile::set_display_name::{self, Endpoint as SetDisplayNameEndpoint};
use ruma_client_api::r0::room::create_room::{self, Endpoint as CreateRoomEndpoint, RoomPreset};
use ruma_client_api::r0::send::send_message_event::{self, Endpoint as SendMessageEventEndpoint};
Expand Down Expand Up @@ -107,6 +108,15 @@ impl super::MatrixApi for MatrixApi {
Ok(())
}

fn does_user_exist(&self, matrix_user_id: UserId) -> Result<bool> {
let path_params = get_display_name::PathParams { user_id: matrix_user_id };
let endpoint = self.base_url.clone() + &GetDisplayNameEndpoint::request_path(path_params);
let params = self.params_hash();

let (_, status_code) = RestApi::call_matrix(GetDisplayNameEndpoint::method(), &endpoint, "", &params)?;
Ok(status_code != StatusCode::NotFound)
}

fn forget_room(&self, matrix_room_id: RoomId) -> Result<()> {
let path_params = forget_room::PathParams { room_id: matrix_room_id };
let endpoint = self.base_url.clone() + &ForgetRoomEndpoint::request_path(path_params);
Expand Down
6 changes: 6 additions & 0 deletions src/matrix-rocketchat/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,10 @@ impl Config {
let user_id = format!("@{}:{}", &self.sender_localpart, &self.hs_domain);
UserId::try_from(&user_id).chain_err(|| ErrorKind::InvalidUserId(user_id)).map_err(Error::from)
}

/// Check if the user ID is part of the application service namespace
pub fn is_application_service_user(&self, matrix_user_id: &UserId) -> bool {
let id_prefix = format!("@{}", self.sender_localpart);
matrix_user_id.to_string().starts_with(&id_prefix)
}
}
2 changes: 1 addition & 1 deletion src/matrix-rocketchat/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ pub mod user_on_rocketchat_server;
pub use self::connection_pool::ConnectionPool;
pub use self::rocketchat_server::{NewRocketchatServer, RocketchatServer};
pub use self::room::Room;
pub use self::user::{NewUser, User};
pub use self::user::User;
pub use self::user_on_rocketchat_server::{NewUserOnRocketchatServer, UserOnRocketchatServer};
11 changes: 1 addition & 10 deletions src/matrix-rocketchat/db/schema.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,5 @@
#![allow(missing_docs)]

table! {
users (matrix_user_id) {
matrix_user_id -> Text,
language -> Text,
last_message_sent -> BigInt,
created_at -> Timestamp,
updated_at -> Timestamp,
}
}

table! {
rocketchat_servers (id) {
id -> Text,
Expand All @@ -23,6 +13,7 @@ table! {
table! {
users_on_rocketchat_servers (matrix_user_id, rocketchat_server_id) {
is_virtual_user -> Bool,
last_message_sent -> BigInt,
matrix_user_id -> Text,
rocketchat_server_id -> Text,
rocketchat_user_id -> Nullable<Text>,
Expand Down
67 changes: 1 addition & 66 deletions src/matrix-rocketchat/db/user.rs
Original file line number Diff line number Diff line change
@@ -1,86 +1,21 @@
use std::time::{SystemTime, UNIX_EPOCH};

use diesel;
use diesel::prelude::*;
use diesel::sqlite::SqliteConnection;
use ruma_identifiers::{RoomId, UserId};

use api::MatrixApi;
use db::Room;
use errors::*;
use i18n::*;
use super::schema::users;

/// A Matrix `User`.
#[derive(Debug, Identifiable, Queryable)]
#[primary_key(matrix_user_id)]
#[derive(Debug)]
pub struct User {
/// The users unique id on the Matrix server.
pub matrix_user_id: UserId,
/// The language the user prefers to get messages in.
pub language: String,
/// Time when the user sent the last message in seconds since UNIX_EPOCH
pub last_message_sent: i64,
/// created timestamp
pub created_at: String,
/// updated timestamp
pub updated_at: String,
}

/// A new Matrix `User`, not yet saved.
#[derive(Insertable, Debug)]
#[table_name = "users"]
pub struct NewUser<'a> {
/// The users unique id on the Matrix server.
pub matrix_user_id: UserId,
/// The language the user prefers to get messages in.
pub language: &'a str,
}

impl User {
/// Insert a new `User` into the database.
pub fn insert(connection: &SqliteConnection, user: &NewUser) -> Result<User> {
diesel::insert(user).into(users::table).execute(connection).chain_err(|| ErrorKind::DBInsertError)?;
User::find(connection, &user.matrix_user_id)
}

/// Find a `User` by his matrix user ID, return an error if the user is not found
pub fn find(connection: &SqliteConnection, matrix_user_id: &UserId) -> Result<User> {
users::table.find(matrix_user_id).first(connection).chain_err(|| ErrorKind::DBSelectError).map_err(Error::from)
}

/// Find or create `User` with a given Matrix user ID.
pub fn find_or_create_by_matrix_user_id(connection: &SqliteConnection, matrix_user_id: UserId) -> Result<User> {
match User::find_by_matrix_user_id(connection, &matrix_user_id)? {
Some(user) => Ok(user),
None => {
let new_user = NewUser {
matrix_user_id: matrix_user_id.clone(),
language: DEFAULT_LANGUAGE,
};
User::insert(connection, &new_user)
}
}
}

/// Find a `User` by his matrix user ID. Returns `None`, if the user is not found.
pub fn find_by_matrix_user_id(connection: &SqliteConnection, matrix_user_id: &UserId) -> Result<Option<User>> {
let users = users::table.find(matrix_user_id).load(connection).chain_err(|| ErrorKind::DBSelectError)?;
Ok(users.into_iter().next())
}

/// Update last message sent.
pub fn set_last_message_sent(&mut self, connection: &SqliteConnection) -> Result<()> {
let last_message_sent =
SystemTime::now().duration_since(UNIX_EPOCH).chain_err(|| ErrorKind::InternalServerError)?.as_secs() as i64;
self.last_message_sent = last_message_sent;
diesel::update(users::table.find(&self.matrix_user_id))
.set(users::last_message_sent.eq(last_message_sent))
.execute(connection)
.chain_err(|| ErrorKind::DBUpdateError)?;
Ok(())
}

/// Checks if a user is in a room.
pub fn is_in_room(matrix_api: &MatrixApi, user_id: &UserId, matrix_room_id: RoomId) -> Result<bool> {
let user_ids_in_room = Room::user_ids(matrix_api, matrix_room_id, None)?;
Expand Down
20 changes: 15 additions & 5 deletions src/matrix-rocketchat/db/user_on_rocketchat_server.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use std::time::{SystemTime, UNIX_EPOCH};

use diesel;
use diesel::prelude::*;
use diesel::sqlite::SqliteConnection;
use ruma_identifiers::UserId;

use errors::*;
use super::schema::users_on_rocketchat_servers;
use super::User;
use db::schema::users_on_rocketchat_servers;

/// A user on a Rocket.Chat server.
#[derive(Associations, Debug, Identifiable, Queryable)]
Expand All @@ -14,6 +15,8 @@ use super::User;
pub struct UserOnRocketchatServer {
/// Flag to indicate if the user is only used to send messages from Rocket.Chat
pub is_virtual_user: bool,
/// Time when the user sent the last message in seconds since UNIX_EPOCH
pub last_message_sent: i64,
/// The users unique id on the Rocket.Chat server.
pub matrix_user_id: UserId,
/// The unique id for the Rocket.Chat server
Expand Down Expand Up @@ -150,9 +153,16 @@ impl UserOnRocketchatServer {
Ok(())
}

/// Get the `User` for a `UserOnRocketchatServer` record.
pub fn user(&self, connection: &SqliteConnection) -> Result<User> {
User::find(connection, &self.matrix_user_id)
/// Update last message sent.
pub fn set_last_message_sent(&mut self, connection: &SqliteConnection) -> Result<()> {
let last_message_sent =
SystemTime::now().duration_since(UNIX_EPOCH).chain_err(|| ErrorKind::InternalServerError)?.as_secs() as i64;
self.last_message_sent = last_message_sent;
diesel::update(users_on_rocketchat_servers::table.find((&self.matrix_user_id, self.rocketchat_server_id.clone())))
.set(users_on_rocketchat_servers::last_message_sent.eq(last_message_sent))
.execute(connection)
.chain_err(|| ErrorKind::DBUpdateError)?;
Ok(())
}

/// Returns true if the user is logged in on the Rocket.Chat server via the application
Expand Down
22 changes: 9 additions & 13 deletions src/matrix-rocketchat/handlers/error_notifier.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use diesel::sqlite::SqliteConnection;
use ruma_identifiers::{RoomId, UserId};
use ruma_identifiers::RoomId;
use slog::Logger;

use i18n::*;
use api::MatrixApi;
use db::User;
use config::Config;
use errors::*;

Expand All @@ -23,28 +22,25 @@ pub struct ErrorNotifier<'a> {
impl<'a> ErrorNotifier<'a> {
/// Send the error message to the user if the error contains a user message. Otherwise just
/// inform the user that an internal error happened.
pub fn send_message_to_user(&self, err: &Error, room_id: RoomId, user_id: &UserId) -> Result<()> {
pub fn send_message_to_user(&self, err: &Error, room_id: RoomId) -> Result<()> {
let mut msg = format!("{}", err);
for err in err.error_chain.iter().skip(1) {
msg = msg + " caused by: " + &format!("{}", err);
}

debug!(self.logger, "{}", msg);

let matrix_bot_id = self.config.matrix_bot_user_id()?;
let language = match User::find_by_matrix_user_id(self.connection, user_id)? {
Some(user) => user.language,
None => DEFAULT_LANGUAGE.to_string(),
};

let user_message = match err.user_message {
Some(ref user_message) => user_message,
Some(ref user_message) => {
debug!(self.logger, "{}", msg);
user_message
}
None => {
let user_msg = t!(["defaults", "internal_error"]).l(&language);
error!(self.logger, "{}", msg);
let user_msg = t!(["defaults", "internal_error"]).l(DEFAULT_LANGUAGE);
return self.matrix_api.send_text_message_event(room_id, matrix_bot_id, user_msg);
}
};

self.matrix_api.send_text_message_event(room_id, matrix_bot_id, user_message.l(&language))
self.matrix_api.send_text_message_event(room_id, matrix_bot_id, user_message.l(DEFAULT_LANGUAGE))
}
}

0 comments on commit 1b76ba9

Please sign in to comment.