Skip to content

Commit a8e32f6

Browse files
authored
Bugfix/chat out of order (#50)
* Bug fixed hopefully * Added patreon
1 parent 8990c08 commit a8e32f6

File tree

13 files changed

+56
-117
lines changed

13 files changed

+56
-117
lines changed

Cargo.lock

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

trackscape-discord-api/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ actix-cors = "0.6.4"
4040
celery = "0.5.5"
4141
mockall = "0.11.4"
4242
async-trait = { version = "0.1.73", features = [] }
43+
redis = { version = "0.23.3", features = ["json"] }
4344

4445

4546
[dev-dependencies]

trackscape-discord-api/src/cache.rs

-85
This file was deleted.

trackscape-discord-api/src/controllers/chat_controller.rs

+15-12
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use crate::cache::Cache;
21
use crate::websocket_server::DiscordToClanChatMessage;
32
use crate::{handler, ChatServerHandle};
43
use actix_web::web::Data;
@@ -13,12 +12,12 @@ use tokio::task::spawn_local;
1312
use trackscape_discord_shared::database::BotMongoDb;
1413
use trackscape_discord_shared::ge_api::ge_api::get_item_mapping;
1514
use trackscape_discord_shared::helpers::hash_string;
16-
use trackscape_discord_shared::jobs::job_helpers::get_redis_client;
1715
use trackscape_discord_shared::jobs::CeleryJobQueue;
1816
use trackscape_discord_shared::osrs_broadcast_extractor::osrs_broadcast_extractor::{
1917
get_wiki_clan_rank_image_url, ClanMessage,
2018
};
2119
use trackscape_discord_shared::osrs_broadcast_handler::OSRSBroadcastHandler;
20+
use trackscape_discord_shared::redis_helpers::{fetch_redis, write_to_cache_with_seconds};
2221
use trackscape_discord_shared::wiki_api::wiki_api::get_quests_and_difficulties;
2322
use web::Json;
2423

@@ -79,7 +78,7 @@ async fn new_discord_message(
7978
async fn new_clan_chats(
8079
req: HttpRequest,
8180
discord_http_client: Data<Http>,
82-
cache: Data<Cache>,
81+
redis_client: Data<redis::Client>,
8382
new_chat: Json<Vec<ClanMessage>>,
8483
mongodb: Data<BotMongoDb>,
8584
celery: Data<Arc<Celery>>,
@@ -127,12 +126,18 @@ async fn new_clan_chats(
127126
//Checks to make sure the message has not already been process since multiple people could be submitting them
128127
let message_content_hash =
129128
hash_string(format!("{}{}", chat.message.clone(), chat.sender.clone()));
130-
match cache.get_value(message_content_hash.clone()).await {
131-
Some(_) => continue,
132-
None => {
133-
cache
134-
.set_value(message_content_hash.clone(), "true".to_string())
135-
.await;
129+
130+
let mut redis_connection = redis_client
131+
.get_connection()
132+
.expect("Could not connect to redis");
133+
134+
let redis_key = format!("MessageHashes:{}", message_content_hash);
135+
match fetch_redis::<String>(&mut redis_connection, &redis_key).await {
136+
Ok(_) => {
137+
continue;
138+
}
139+
Err(_) => {
140+
write_to_cache_with_seconds(&mut redis_connection, &redis_key, true, 10).await
136141
}
137142
}
138143

@@ -143,6 +148,7 @@ async fn new_clan_chats(
143148
}
144149

145150
if registered_guild.clan_name.clone().unwrap() != chat.clan_name {
151+
error!("Clan name does not match the clan name saved in the database");
146152
continue;
147153
}
148154

@@ -213,9 +219,6 @@ async fn new_clan_chats(
213219

214220
let league_world = chat.is_league_world.unwrap_or(false);
215221

216-
// TODO: Load this from Redis
217-
let mut redis_connection = get_redis_client().unwrap();
218-
219222
let item_mapping_from_redis = get_item_mapping(&mut redis_connection).await;
220223

221224
let quests_from_redis = get_quests_and_difficulties(&mut redis_connection).await;

trackscape-discord-api/src/main.rs

+5-11
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
extern crate dotenv;
22

3-
mod cache;
43
mod controllers;
54
mod handler;
65
mod websocket_server;
76

8-
use crate::cache::Cache;
97
use crate::controllers::bot_info_controller::info_controller;
108
use crate::controllers::chat_controller::chat_controller;
119
use actix_cors::Cors;
@@ -18,7 +16,6 @@ use shuttle_actix_web::ShuttleActixWeb;
1816
use std::env;
1917
use std::sync::atomic::AtomicI64;
2018
use std::sync::Mutex;
21-
use std::time::Duration;
2219
use tokio::spawn;
2320
use trackscape_discord_shared::database::{BotMongoDb, MongoDb};
2421
use trackscape_discord_shared::ge_api::ge_api::get_item_mapping;
@@ -61,7 +58,10 @@ async fn actix_web() -> ShuttleActixWeb<impl FnOnce(&mut ServiceConfig) + Send +
6158
}
6259

6360
let db = BotMongoDb::new_db_instance(mongodb_url).await;
64-
let mut redis_conn = get_redis_client().unwrap();
61+
let redis_client = get_redis_client();
62+
let mut redis_conn = redis_client
63+
.get_connection()
64+
.expect("Could not connect to redis");
6565

6666
info!("Loading startup data from the web");
6767
let ge_mapping_request = get_item_mapping(&mut redis_conn).await;
@@ -84,12 +84,6 @@ async fn actix_web() -> ShuttleActixWeb<impl FnOnce(&mut ServiceConfig) + Send +
8484
}
8585
}
8686

87-
let mut cache = Cache::new(Duration::from_secs(10));
88-
let cache_clone = cache.clone();
89-
spawn(async move {
90-
cache.clean_expired().await;
91-
});
92-
9387
#[allow(clippy::mutex_atomic)] // it's intentional.
9488
let connected_websockets_counter = Data::new(Mutex::new(0usize));
9589
let connected_discord_servers = Data::new(AtomicI64::new(0));
@@ -117,10 +111,10 @@ async fn actix_web() -> ShuttleActixWeb<impl FnOnce(&mut ServiceConfig) + Send +
117111
.app_data(web::Data::new(server_tx.clone()))
118112
.app_data(connected_websockets_counter)
119113
.app_data(connected_discord_servers)
120-
.app_data(web::Data::new(cache_clone))
121114
.app_data(web::Data::new(HttpBuilder::new(discord_token).build()))
122115
.app_data(web::Data::new(db))
123116
.app_data(web::Data::new(celery.clone()))
117+
.app_data(web::Data::new(redis_client.clone()))
124118
.default_service(web::route().guard(guard::Not(guard::Get())).to(index));
125119
};
126120

trackscape-discord-shared/src/jobs/job_helpers.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::database::{BotMongoDb, MongoDb};
2-
use redis::{Connection, RedisResult};
2+
use redis::{Client, Connection, RedisResult};
33
use serde::Serialize;
44
use std::env;
55

@@ -10,13 +10,18 @@ pub async fn get_mongodb() -> BotMongoDb {
1010
BotMongoDb::new_db_instance(mongodb_url).await
1111
}
1212

13-
pub fn get_redis_client() -> RedisResult<Connection> {
13+
pub fn get_redis_connection() -> RedisResult<Connection> {
1414
let redis_url = env::var("REDIS_ADDR").expect("REDIS_ADDR not set!");
1515
redis::Client::open(redis_url)
1616
.expect("Could not connect to redis")
1717
.get_connection()
1818
}
1919

20+
pub fn get_redis_client() -> Client {
21+
let redis_url = env::var("REDIS_ADDR").expect("REDIS_ADDR not set!");
22+
redis::Client::open(redis_url).expect("Could not connect to redis")
23+
}
24+
2025
pub async fn write_to_cache<T: Serialize>(
2126
redis_connection: &mut Connection,
2227
redis_key: String,

trackscape-discord-shared/src/jobs/name_change_job.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::database::clan_mates::{name_compare, ClanMates};
2-
use crate::jobs::job_helpers::{get_mongodb, get_redis_client};
2+
use crate::jobs::job_helpers::{get_mongodb, get_redis_connection};
33
use crate::wom::{get_latest_name_change, get_wom_client, ApiLimiter};
44
use celery::prelude::*;
55
use log::info;
@@ -10,7 +10,7 @@ pub async fn name_change() -> TaskResult<()> {
1010
info!("Running name change job");
1111
let wom_client = get_wom_client();
1212
let mongodb = get_mongodb().await;
13-
let mut redis_connection = get_redis_client().expect("Failed to get redis client.");
13+
let mut redis_connection = get_redis_connection().expect("Failed to get redis client.");
1414

1515
let mut limiter = ApiLimiter::new();
1616

trackscape-discord-shared/src/jobs/runelite_commands/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use super::job_helpers::get_redis_client;
1+
use super::job_helpers::get_redis_connection;
22
use redis::{Commands, RedisResult};
33

44
pub mod pb_command;
@@ -11,7 +11,7 @@ pub async fn get_runelite_api_url() -> Result<String, anyhow::Error> {
1111
}
1212

1313
async fn get_runelite_version() -> Result<String, anyhow::Error> {
14-
let mut redis_connection = get_redis_client().unwrap();
14+
let mut redis_connection = get_redis_connection().unwrap();
1515
let version_key = "runelite_version";
1616
let exists: RedisResult<bool> = redis_connection.exists(version_key);
1717
match exists {

trackscape-discord-shared/src/jobs/update_create_clanmate_job.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::database::clan_mates::{ClanMateModel, ClanMates};
2-
use crate::jobs::job_helpers::{get_mongodb, get_redis_client, write_to_cache};
2+
use crate::jobs::job_helpers::{get_mongodb, get_redis_connection, write_to_cache};
33
use crate::wom::{get_latest_name_change, get_wom_client};
44
use celery::prelude::*;
55
use redis::{Commands, RedisResult};
@@ -12,7 +12,7 @@ pub async fn update_create_clanmate(
1212
rank: String,
1313
guild_id: u64,
1414
) -> TaskResult<i32> {
15-
let mut redis_connection = get_redis_client().expect("Failed to get redis client.");
15+
let mut redis_connection = get_redis_connection().expect("Failed to get redis client.");
1616
let redis_key = format!("players:{}", player_name.clone());
1717
let exists: RedisResult<bool> = redis_connection.exists(redis_key.clone());
1818

trackscape-discord-shared/src/redis_helpers.rs

+12
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,18 @@ pub async fn fetch_redis_json_object<T: for<'a> Deserialize<'a>>(
4646
Ok(val)
4747
}
4848

49+
pub async fn fetch_redis<T: redis::FromRedisValue>(
50+
redis_connection: &mut Connection,
51+
redis_key: &str,
52+
) -> Result<T, RedisFetchErrors> {
53+
let val = redis::cmd("GET")
54+
.arg(redis_key)
55+
.query::<T>(redis_connection)
56+
.map_err(|_| RedisFetchErrors::FromDbError)?;
57+
58+
Ok(val)
59+
}
60+
4961
pub enum RedisFetchErrors {
5062
FromDbError,
5163
ParseError,

trackscape-discord-ui/src/App.vue

+2
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ import Drawer from "@/components/NavDrawer.vue";
2929
<a class="link"
3030
href="https://github.com/fatfingers23/trackscape-discord-bot">Just show me the code</a>
3131

32+
<a class="link"
33+
href="https://www.patreon.com/TrackScape">Support us on Patreon</a>
3234
<RouterLink class="link"
3335
to="/TermsOfService">Terms Of Service</RouterLink>
3436
<RouterLink class="link"

trackscape-discord-ui/src/assets/logo.svg

-1
This file was deleted.

trackscape-discord-ui/src/views/BotLandingPage.vue

+7
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,13 @@ client.getBotInfo().then((info) => {
5959
alt="In game cc icon"
6060
>
6161
</router-link>
62+
63+
<a
64+
href="https://www.patreon.com/TrackScape"
65+
class="btn btn-primary btn-outline ml-2 md:pt-0 mt-2"
66+
>
67+
Support TrackScape on Patreon
68+
</a>
6269
</div>
6370
<div class="justify-end">
6471
<a

0 commit comments

Comments
 (0)