Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 23 additions & 8 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,21 @@ async fn join(
ch2: String,
sub_ch: String,
storage: State<'_, Storage>,
) -> Result<(), ()> {
) -> Result<(), String> {
// Parse channel IDs with proper error handling
let ch1_id = ch1.parse::<u64>()
.map_err(|e| format!("Invalid channel ID '{}': {}", ch1, e))?;
let ch2_id = ch2.parse::<u64>()
.map_err(|e| format!("Invalid channel ID '{}': {}", ch2, e))?;
let sub_ch_id = sub_ch.parse::<u64>()
.map_err(|e| format!("Invalid sub channel ID '{}': {}", sub_ch, e))?;

let vc = storage.vc.lock().await;
vc.join(
app,
ChannelId::new(ch1.parse::<u64>().unwrap()),
ChannelId::new(ch2.parse::<u64>().unwrap()),
ChannelId::new(sub_ch.parse::<u64>().unwrap()),
ChannelId::new(ch1_id),
ChannelId::new(ch2_id),
ChannelId::new(sub_ch_id),
)
.await;
Ok(())
Expand Down Expand Up @@ -99,7 +107,9 @@ pub fn run() {
.setup(move |app| {
let handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
update(handle).await.unwrap();
if let Err(e) = update(handle).await {
eprintln!("Update check failed: {}", e);
}
});
let res = tauri::async_runtime::block_on(async {
vc.start_bot(&pub_token, &pub_token2, &sub_token).await
Expand All @@ -115,7 +125,7 @@ pub fn run() {
// Explorer表示
eprintln!("Error starting bot: {}", e);
let shell = app.handle().shell();
let pwd = std::env::current_dir().unwrap();
let pwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
let exp_shell = shell
.command("explorer.exe")
.arg(pwd);
Expand All @@ -126,7 +136,9 @@ pub fn run() {
.title("DiscordBot API認証エラー")
.blocking_show();
if res {
exp_shell.spawn().expect("failed to shell");
if let Err(e) = exp_shell.spawn() {
eprintln!("Failed to open explorer: {}", e);
}
}
return Err("failed to start bot".to_string().into());
}
Expand All @@ -140,7 +152,10 @@ pub fn run() {
update_is_listening
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
.unwrap_or_else(|e| {
eprintln!("Fatal error running application: {}", e);
std::process::exit(1);
});
}

async fn update(app: AppHandle) -> tauri_plugin_updater::Result<()> {
Expand Down
16 changes: 13 additions & 3 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,23 @@ use std::{fs::File, sync::Arc};
use gag::Redirect;
use tracing::Level;
fn main() {
let fs = File::create("./logfile.log").unwrap();
let fs = File::create("./logfile.log")
.unwrap_or_else(|e| {
eprintln!("Warning: Could not create logfile.log: {}", e);
std::io::stdout() // fallback to stdout
});
tracing_subscriber::fmt()
.with_max_level(Level::ERROR)
.with_ansi(false)
.with_writer(Arc::new(fs))
.init();
let fs_stderr = File::create("./stderr.log").unwrap();
let _redirect = Redirect::stderr(fs_stderr).expect("Failed to redirect stderr");
let fs_stderr = File::create("./stderr.log")
.unwrap_or_else(|e| {
eprintln!("Warning: Could not create stderr.log: {}", e);
std::io::stderr() // fallback to stderr
});
if let Err(e) = Redirect::stderr(fs_stderr) {
eprintln!("Warning: Could not redirect stderr: {}", e);
}
discordvoicecommv1_lib::run()
}
17 changes: 14 additions & 3 deletions src-tauri/src/vc/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,28 @@ pub struct ConfigManager {
}
impl ConfigManager {
pub fn new(path: String) -> Self {
let cfg = confy::load_path::<MyConfig>(&path)
.unwrap_or_else(|e| {
eprintln!("Warning: Could not load config from {}: {}. Using default config.", path, e);
MyConfig::default()
});
ConfigManager {
path: path.clone(),
cfg: Mutex::new(confy::load_path::<MyConfig>(path).unwrap()),
cfg: Mutex::new(cfg),
}
}
pub fn get_cfg(&self) -> MyConfig {
let cfg = self.cfg.lock().unwrap();
let cfg = self.cfg.lock().unwrap_or_else(|poisoned| {
eprintln!("Warning: Config mutex was poisoned, recovering...");
poisoned.into_inner()
});
cfg.clone()
}
pub fn update_volume(&self, user_id: UserId, volume: f32) -> Result<(), ConfyError> {
let mut cfg = self.cfg.lock().unwrap();
let mut cfg = self.cfg.lock().unwrap_or_else(|poisoned| {
eprintln!("Warning: Config mutex was poisoned during volume update, recovering...");
poisoned.into_inner()
});
cfg.user_volumes.insert(user_id, volume);
let cfg_cpy = cfg.clone();
confy::store_path(&self.path, cfg_cpy)
Expand Down
20 changes: 13 additions & 7 deletions src-tauri/src/vc/dis_pub.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,9 @@ impl VoiceEventHandler for Receiver {
event: VoiceUserEvent::Join,
identify: self.identify,
};
self.tx.send(SendEnum::UserData(user_data)).await.unwrap();
if let Err(e) = self.tx.send(SendEnum::UserData(user_data)).await {
error!("Failed to send user join data: {}", e);
}
}
}
Ctx::VoiceTick(tick) => {
Expand Down Expand Up @@ -174,10 +176,10 @@ impl VoiceEventHandler for Receiver {
}
};
if is_listening {
self.tx
.send(SendEnum::VoiceData(send_data))
.await
.expect("tx send failed");
if let Err(e) = self.tx.send(SendEnum::VoiceData(send_data)).await {
error!("Failed to send voice data: {}", e);
return None; // Stop processing if channel is closed
}
}
if let Some(packet) = &data.packet {
let rtp = packet.rtp();
Expand Down Expand Up @@ -233,7 +235,9 @@ impl VoiceEventHandler for Receiver {
event: VoiceUserEvent::Leave,
identify: self.identify,
};
self.tx.send(SendEnum::UserData(user_data)).await.unwrap();
if let Err(e) = self.tx.send(SendEnum::UserData(user_data)).await {
error!("Failed to send user leave data: {}", e);
}
debug!("Client disconnected: user {:?}", user_id);
}
_ => {
Expand Down Expand Up @@ -344,7 +348,9 @@ impl Pub {
async fn _join_vc(&self, manager: Arc<Songbird>, join_info: JoinInfo) {
if let Err(e) = manager.join(join_info.guild_id, join_info.channel_id).await {
// Although we failed to join, we need to clear out existing event handlers on the call.
_ = manager.remove(join_info.guild_id).await;
if let Err(e) = manager.remove(join_info.guild_id).await {
error!("Failed to remove from manager during cleanup: {}", e);
}
error!("failed to join vc:{:?}", e);
}
}
Expand Down
10 changes: 7 additions & 3 deletions src-tauri/src/vc/dis_sub.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ struct Handler;
impl EventHandler for Handler {
async fn ready(&self, ctx: serenity::prelude::Context, ready: Ready) {
info!("{} is connected!", ready.user.name);
CTX.set(Arc::new(RwLock::new(ctx))).unwrap();
if let Err(_) = CTX.set(Arc::new(RwLock::new(ctx))) {
error!("CTX already initialized");
}
}
}

Expand Down Expand Up @@ -116,8 +118,10 @@ impl Sub {
Some(ctx) => ctx.clone(),
};
let ctx = ctx_lock.read().await;
let guild = ctx.http.get_guild(guild_id).await.unwrap();
let channels = guild.channels(ctx.http.clone()).await.unwrap();
let guild = ctx.http.get_guild(guild_id).await
.map_err(|e| format!("Failed to get guild: {}", e))?;
let channels = guild.channels(ctx.http.clone()).await
.map_err(|e| format!("Failed to get channels: {}", e))?;
let voice_channels: Vec<GuildChannel> = channels
.values()
.filter(|channel| channel.bitrate.is_some())
Expand Down
21 changes: 16 additions & 5 deletions src-tauri/src/vc/voice_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,19 @@ impl VoiceManager {
let user_name = match id_name_map.get(&user_id) {
Some(user_name) => user_name.to_owned(),
None => {
let user = http.get_user(user_id).await.unwrap();
user.name
match http.get_user(user_id).await {
Ok(user) => user.name,
Err(e) => {
log::error!("Failed to get user {}: {}", user_id, e);
continue; // Skip this user and continue processing
}
}
}
};
let emit_data = EmitData::new(user_info, user_name.clone());
app.emit("user-data-changed", emit_data).unwrap();
if let Err(e) = app.emit("user-data-changed", emit_data) {
log::error!("Failed to emit user data: {}", e);
}
{
let user_lock = user_volumes.read().await;
let need_insert = user_lock.get(&user_id).is_none();
Expand All @@ -117,11 +124,15 @@ impl VoiceManager {
let volume = match user_volumes.get(&UserId::from(u.user_id.0)) {
Some(v) => *v,
None => {
unreachable!()
log::warn!("No volume setting for user {}, using default 1.0", u.user_id.0);
1.0
}
};
let pcm = convert_voice_data(u.voice_data, volume);
tx.send(pcm).await.unwrap();
if let Err(e) = tx.send(pcm).await {
log::error!("Failed to send PCM data: {}", e);
break; // Channel is closed, exit the processing loop
}
}
}
}
Expand Down