Skip to content

Commit a5f1ec4

Browse files
committed
add log and env_logger, add bunch of log calls
1 parent 4c2f54b commit a5f1ec4

11 files changed

Lines changed: 61 additions & 81 deletions

backend/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,5 @@ twitch_highway = { version = "0.3.1", features = ["eventsub", "tokio", "bits", "
2525
serde_with = "3.15.1"
2626
asknothingx2-util = "0.1.10"
2727
tower = "0.5.2"
28+
env_logger = "0.11.8"
29+
log = "0.4.28"

backend/src/commands/command_controller.rs

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use num_derive::FromPrimitive;
1111
use serde::{Deserialize, Serialize};
1212
use sqlx::Type;
1313
use std::str::FromStr;
14+
use log::{error, warn};
1415
use crate::commands::command_repo::SaveCommandError;
1516
use crate::state::L1Arc;
1617

@@ -57,8 +58,8 @@ pub async fn get_all_user_commands(
5758
let commands = match search.search.as_deref() {
5859
Some("") | None => command_repo::get_all_commands_by_auto_generated(&state.l1.prod_db, false).await,
5960
Some(search) => command_repo::search_all_commands_by_is_auto_generated(&state.l1.prod_db, search, false).await,
60-
}.map_err(|_| {
61-
// log
61+
}.map_err(|e| {
62+
error!("{:?}", e);
6263
StatusCode::INTERNAL_SERVER_ERROR
6364
})?;
6465
Ok(Json(commands))
@@ -72,8 +73,8 @@ pub async fn get_all_commands(
7273
let commands = match search.search.as_deref() {
7374
Some("") | None => command_repo::get_all_commands(&l1.prod_db).await,
7475
Some(search) => command_repo::search_all_commands(&l1.prod_db, search).await,
75-
}.map_err(|_| {
76-
// log
76+
}.map_err(|e| {
77+
error!("{:?}", e);
7778
StatusCode::INTERNAL_SERVER_ERROR
7879
})?;
7980
Ok(Json(commands))
@@ -85,8 +86,8 @@ pub async fn get_by_trigger_id(
8586
) -> AxResult<impl IntoResponse> {
8687
Ok(Json(command_repo::get_by_id(&l1.prod_db, trigger_id.as_ref())
8788
.await
88-
.map_err(|_| {
89-
// log
89+
.map_err(|e| {
90+
error!("{:?}", e);
9091
StatusCode::INTERNAL_SERVER_ERROR
9192
})?))
9293
}
@@ -100,8 +101,8 @@ pub async fn set_enabled(
100101
let enabled = bool::from_str(body.as_ref()).map_err(|_| StatusCode::BAD_REQUEST)?;
101102
command_repo::set_enabled(state.l1.as_ref(), trigger_id.as_ref(), enabled)
102103
.await
103-
.map_err(|_| {
104-
// log
104+
.map_err(|e| {
105+
error!("{:?}", e);
105106
StatusCode::INTERNAL_SERVER_ERROR
106107
})?
107108
.ok_or(StatusCode::NOT_FOUND)?;
@@ -116,8 +117,8 @@ pub async fn set_visible(
116117
let visible = bool::from_str(body.as_str()).map_err(|_| StatusCode::BAD_REQUEST)?;
117118
command_repo::set_visible(&l1.prod_db, trigger_id.as_str(), visible)
118119
.await
119-
.map_err(|_| {
120-
// log
120+
.map_err(|e| {
121+
error!("{:?}", e);
121122
StatusCode::INTERNAL_SERVER_ERROR
122123
})?
123124
.ok_or(StatusCode::NOT_FOUND)?;
@@ -130,12 +131,12 @@ pub async fn save(
130131
) -> impl IntoResponse {
131132
match command_repo::save(l1.as_ref(), &to_save).await {
132133
Ok(()) => StatusCode::OK,
133-
Err(SaveCommandError::DbError(_db_error)) => {
134-
// log
134+
Err(SaveCommandError::DbError(db_error)) => {
135+
error!("Error saving command from panel: {:?}", db_error);
135136
StatusCode::INTERNAL_SERVER_ERROR
136137
}
137-
Err(SaveCommandError::RegexError(_r)) => {
138-
// log, but actually more return. This error needs to reach the user in the panel
138+
Err(SaveCommandError::RegexError(r)) => {
139+
warn!("User tried to save invalid regex: {:?}", r);
139140
//TODO figure out how to return this error to the user
140141
StatusCode::BAD_REQUEST
141142
}
@@ -146,8 +147,8 @@ pub async fn delete_by_id(
146147
l1: L1Arc,
147148
Path(trigger_id): Path<String>,
148149
) -> AxResult<impl IntoResponse> {
149-
command_repo::delete_by_id(l1.as_ref(), trigger_id.as_ref()).await.map_err(|_| {
150-
// log
150+
command_repo::delete_by_id(l1.as_ref(), trigger_id.as_ref()).await.map_err(|e| {
151+
error!("Unable to execute command deletion: {:?}", e);
151152
StatusCode::INTERNAL_SERVER_ERROR
152153
})?;
153154
Ok(())

backend/src/commands/command_executor_service.rs

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,11 @@ use std::collections::HashMap;
1111
use std::pin::Pin;
1212
use std::sync::Arc;
1313
use std::time::Instant;
14+
use log::{debug, error, trace, warn};
1415
use tokio::sync::RwLock;
1516

1617
#[allow(dead_code)]
17-
#[derive(Clone, Copy, Ord, PartialOrd, PartialEq, Eq, Deserialize, Serialize, FromPrimitive, Type)]
18+
#[derive(Clone, Copy, Debug, Ord, PartialOrd, PartialEq, Eq, Deserialize, Serialize, FromPrimitive, Type)]
1819
#[repr(u8)]
1920
pub enum TwitchUserPermission {
2021
Everyone = 0,
@@ -113,15 +114,12 @@ pub struct CommandTrigger {
113114

114115
static TEXT_COMMAND_CALLBACK: TriggerCallback = |app_state, trigger_id, _chat_message| Box::pin(async move {
115116
match TemplateService::get_template_by_trigger_id(&app_state.l1.prod_db, trigger_id.as_ref()).await {
116-
Err(_e) => {
117-
// log
118-
// logger.debug("Executing text command {}", commandId);
117+
Err(e) => error!("Could not fetch template for command {} from db: {:?}", trigger_id, e),
118+
Ok(None) => warn!("Could not find template id for command id {}", trigger_id),
119+
Ok(Some(t)) => {
120+
debug!("Executing text command {}", trigger_id);
121+
app_state.l2.twitch_service.send_raw_template(t.template.as_ref(), HashMap::new())
119122
}
120-
Ok(None) => {
121-
// log
122-
// logger.error("Could not find template id for command id {}", commandId);
123-
}
124-
Ok(Some(t)) => app_state.l2.twitch_service.send_raw_template(t.template.as_ref(), HashMap::new())
125123
}
126124
});
127125

@@ -187,7 +185,7 @@ impl CommandExecutorService {
187185

188186
async fn execute_trigger_if_matching(&self, app_state: Arc<FullState>, trigger: &CommandTrigger, chat_message: ChatMessage) {
189187
if chat_message.user.permission < trigger.permission {
190-
// logger.debug("User {} with {}, missing {} permission for command {}", message.user().name(), message.user().permission(), trigger.permission(), trigger.id());
188+
trace!("User {} with perm: {:?}, missing {:?} permission for command {}", chat_message.user.name, chat_message.user.permission, trigger.permission, trigger.id);
191189
return;
192190
}
193191

@@ -197,8 +195,8 @@ impl CommandExecutorService {
197195

198196
let cooldown_res = self.cooldown_service.check_update_cooldown(&chat_message, trigger.id.as_ref(), &trigger.user_cooldown, &trigger.global_cooldown);
199197
if cooldown_res.is_some() {
200-
// logger.debug("Call to command {} from {} rejected because of global cooldowns", trigger.id(), message.user().name());
201-
// logger.debug("Call to command {} from {} rejected because of user cooldowns", trigger.id(), message.user().name());
198+
trace!("Call to command {} from {} rejected because of global cooldowns", trigger.id, chat_message.user.name);
199+
trace!("Call to command {} from {} rejected because of user cooldowns", trigger.id, chat_message.user.name);
202200
return;
203201
}
204202

backend/src/commands/command_repo.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ pub async fn search_all_commands(prod_db: &ProdDB, search: &str) -> anyhow::Resu
125125
"#, search_str, search_str, search_str, search_str)
126126
.fetch_all(prod_db.deref())
127127
.await
128-
.context("failed to search table for all commands")?;
128+
.with_context(|| format!("failed to search table for all commands; search: {}", search))?;
129129
get_patterns(prod_db, query_res).await
130130
}
131131

@@ -156,7 +156,7 @@ pub async fn search_all_commands_by_is_auto_generated(prod_db: &ProdDB, search:
156156
"#, search_str, search_str, search_str, search_str, is_auto_generated)
157157
.fetch_all(prod_db.deref())
158158
.await
159-
.context("failed to search table for all commands by is_auto_generated")?;
159+
.with_context(|| format!("failed to search table for all commands by is_auto_generated; search: {}", search))?;
160160
get_patterns(prod_db, query_res).await
161161
}
162162

backend/src/lib.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use service_oauth::oauth_service::OAuthService;
66
use sqlx::MySqlPool;
77
use std::str::FromStr;
88
use std::sync::{Arc, OnceLock, RwLock};
9+
use log::error;
910
use tokio::runtime::Handle;
1011
use tokio::sync::broadcast::error::RecvError;
1112
use url::Url;
@@ -22,7 +23,9 @@ mod service_oauth;
2223
mod twitch;
2324
mod state;
2425

26+
2527
pub async fn start() {
28+
env_logger::init();
2629
//check if all mandatory configuration values are set
2730
//start mini webserver
2831

@@ -75,20 +78,21 @@ pub async fn start() {
7578
let oauth = full.l1.oauth_service.new_oauth_request("twitch".to_string(), "account".to_string(), |_x, _x1| "".to_string());
7679
println!("oauth: {:?}", oauth);
7780

78-
let (command_channel, _) = tokio::sync::broadcast::channel::<Box<ChatMessage>>(20);
81+
let (chat_channel, _) = tokio::sync::broadcast::channel::<Box<ChatMessage>>(20);
7982
// fanout of messages
8083
let full2 = full.clone();
81-
let sender2 = command_channel.clone();
84+
let sender2 = chat_channel.clone();
8285
Handle::current().spawn(async { TwitchService::start_websocket(full2, sender2) });
83-
let mut receiver = command_channel.subscribe();
86+
87+
let mut receiver = chat_channel.subscribe();
8488
let full2 = full.clone();
8589
Handle::current().spawn(async move {
8690
loop {
8791
let message = match receiver.recv().await {
8892
Ok(m) => *m,
8993
Err(RecvError::Closed) => return,
90-
Err(RecvError::Lagged(_s)) => {
91-
// log skip
94+
Err(RecvError::Lagged(skipped)) => {
95+
error!("Twitch ChatMessage channel lagged, skipped {} messages!", skipped);
9296
continue;
9397
}
9498
};

backend/src/service_oauth/oauth_endpoint.rs

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,11 @@ use axum::extract::{Path, Query, State};
55
use axum::response::IntoResponse;
66
use axum::response::Result as AxResult;
77
use axum::Json;
8+
use log::error;
89
use reqwest::StatusCode;
910
use serde::Deserialize;
1011
use crate::state::L1Arc;
1112

12-
/// Get redirect url for a particular service. The url is fully formed with the host accessible from the outside.
13-
///
14-
/// `service_name` is the string name/id of the service that you use to in [OAuthService::new_oauth_request]
15-
pub fn get_redirect_url(bot_base_url_config: String, service_name: &str) -> String {
16-
bot_base_url_config + "/auth/" + service_name
17-
}
18-
19-
/// Get the public url to the panel oauth setup page
20-
pub fn get_oauth_setup_url(bot_base_url_config: String) -> String {
21-
bot_base_url_config + "/auth"
22-
}
23-
2413
#[derive(Deserialize)]
2514
pub struct ReceiveOAuthQuery {
2615
state: String,
@@ -38,8 +27,8 @@ pub async fn receive_oauth(
3827
let panel_base_url = if let Ok(v) = state.l1.webserver_config.read() {
3928
v.panel_base_url.as_str().to_string()
4029
} else {
41-
// log lock poisoned
42-
return Err(StatusCode::INTERNAL_SERVER_ERROR)?;
30+
error!("Error, webserver_config lock poisoned, unable to set panel redirect url");
31+
"".to_string()
4332
};
4433
// Body:new( should be Redirect:to(& but for testing with postman, this is deactivated
4534
if query.error.is_some() || query.error_description.is_some() {
@@ -51,11 +40,12 @@ pub async fn receive_oauth(
5140
if query.code.is_none() {
5241
return Ok(Body::new(format!("{}?success=false&error={}", panel_base_url, url_encode("Query param code is required for non error Oauth response"))))
5342
}
54-
Ok(Body::new(format!("{}{}", panel_base_url, match state.l1.oauth_service.return_oauth(service, query.state, query.scope.unwrap(), query.code.unwrap()) {
43+
let result = state.l1.oauth_service.return_oauth(service, query.state, query.scope.unwrap(), query.code.unwrap());
44+
Ok(Body::new(format!("{}{}", panel_base_url, match result {
5545
Ok(()) => format!("{}?success=true", panel_base_url),
5646
Err(OauthReturnError::NotRequested) => format!("{}?success=false&error={}", panel_base_url, url_encode("This oauth was never requested from the bot")),
5747
Err(OauthReturnError::ReturnChannelClosed) => {
58-
eprintln!("Failed to process auth code, return channel was closed");
48+
error!("Error, failed to process auth code, return channel was unexpectedly closed");
5949
format!("{}?success=false&error={}", panel_base_url, url_encode("Could not process auth code. Internal server error"))
6050
}
6151
})))

backend/src/twitch/authentication.rs

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,12 @@
1-
use crate::axum::url_encode;
21
use crate::twitch::twitch_service::OauthCredential;
3-
use crate::service_oauth::oauth_service::{AuthorizationUrl, AuthorizationUrlBuilder, OAuthService, OauthState};
42
use anyhow::Context;
53
use axum::http::method::Method;
64
use axum::http::StatusCode;
75
use serde::{Deserialize, Serialize};
86
use serde_with::serde_as;
97
use serde_with::DurationSeconds;
108
use sqlx::types::chrono::Local;
11-
use std::str::FromStr;
129
use std::time::Duration;
13-
use url::Url;
1410

1511
#[serde_as]
1612
#[derive(Deserialize)]
@@ -101,20 +97,3 @@ pub async fn refresh_token(refresh_token: impl AsRef<str>, client_id: impl AsRef
10197
.context("Original response body: ".to_string() + &response_body)?;
10298
Ok(Some(validation_return))
10399
}
104-
105-
pub fn authorization_url(client_id: impl AsRef<str>) -> Box<AuthorizationUrlBuilder> {
106-
const TWITCH_AUTHORIZE: &'static str = "https://id.twitch.tv/oauth2/authorize";
107-
const SCOPES: [&str; 6] = ["channel:bot", "user:bot", "moderator:read:chatters", "moderator:read:moderators", "user:read:chat", "user:manage:chat_color"];
108-
let client_id = client_id.as_ref().to_string();
109-
// Box::new( move |redirect, state| {
110-
// format!(r#"
111-
// {}
112-
// ?response_type=code
113-
// &client_id={}
114-
// &redirect_uri={}
115-
// &scope={}
116-
// &state={}
117-
// "#, TWITCH_AUTHORIZE, client_id, redirect, SCOPES.map(url_encode).join("+"), state)
118-
// })
119-
todo!()
120-
}

backend/src/twitch/ideal_twitch_client.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,6 @@ enum SendChatError {
1313

1414
impl Helix {
1515
pub async fn send_chat_message(broadcaster_id: impl AsRef<str>, sender_id: impl AsRef<str>, message: impl AsRef<str>, reply_parent_message_id: Option<impl AsRef<str>>, for_source_only: bool) -> Result<Vec<User>, SendChatError> {
16-
todo!()
16+
panic!("not implemented, just an example")
1717
}
1818
}

backend/src/twitch/twitch_api.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use twitch_highway::eventsub::{websocket, EventSubAPI, SubscriptionType};
1111
use tower::MakeService;
1212
use twitch_highway::eventsub::websocket::routes::{channel_chat_message, revocation, welcome};
1313
use anyhow::Context;
14+
use log::error;
1415
use crate::commands::command_executor_service::ChatMessage;
1516
use crate::state::FullState;
1617
use crate::twitch::twitch_service::TwitchService;
@@ -35,7 +36,9 @@ impl TwitchService {
3536
.with_state(state));
3637

3738
let _ws = websocket::client("wss://eventsub.wss.twitch.tv/ws", twitch_router).await;
38-
//log error
39+
if let Err(e) = _ws {
40+
error!("Unable to connect to twitch websocket: {:?}", e);
41+
}
3942
}
4043
}
4144

backend/src/twitch/twitch_service.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use serde::Deserialize;
88
use sqlx::types::chrono::{DateTime, Local};
99
use std::sync::Arc;
1010
use std::time::Instant;
11+
use log::{info, warn};
1112
use tokio::runtime::Handle;
1213
use tokio::sync::{Mutex, RwLock};
1314
use twitch_highway::TwitchAPI;
@@ -54,8 +55,8 @@ impl TwitchService {
5455
};
5556
let oauth = match Self::check_or_get_oauth(&cred_from_db, &l1.prod_db, &twitch_config).await {
5657
Ok(oauth) => oauth,
57-
Err(_e) => {
58-
// log err
58+
Err(e) => {
59+
warn!("Twitch Oauth credentials from DB invalid, and could not be refreshed: {:?}", e);
5960
TwitchCredentialStatus {
6061
was_valid_at_check: true,
6162
valid_checked_at: Instant::now(),
@@ -104,6 +105,7 @@ impl TwitchService {
104105
let twitch_api = self.twitch_api.clone();
105106
let token_validation = self.token_validation.clone();
106107
Handle::current().spawn(async move {
108+
info!("Awaiting manual reauthorization of twitch account oauth!");
107109
let credential = TwitchService::request_new_oauth(&l1, config).await;
108110
{
109111
let mut api_lock = twitch_api.write().await;
@@ -115,7 +117,7 @@ impl TwitchService {
115117
token_lock.was_valid_at_check = true;
116118
token_lock.credential = credential;
117119
}
118-
//log
120+
info!("Successfully get, refreshed, and set new Oauth Token for Twitch Client");
119121
});
120122
return Err(e).context("Credentials Bad, not retrying");
121123
}

0 commit comments

Comments
 (0)