Skip to content

Commit dc40a7a

Browse files
committed
improve robustness
1 parent c0e8535 commit dc40a7a

6 files changed

Lines changed: 90 additions & 45 deletions

File tree

src-tauri/src/commands/utils.rs

Lines changed: 85 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
55
use super::types::{MaaCallbackEvent, MaaState, StateChangedEvent};
66
use crate::ws_broadcast::{WsBroadcast, WsEvent};
7+
use log::error;
78
use std::path::PathBuf;
89
use std::sync::Arc;
910
use tauri::{AppHandle, Emitter, Manager};
@@ -286,16 +287,31 @@ pub fn get_checked_task_status_of_instance(
286287
app_handle: Option<&AppHandle>,
287288
instance_id: Option<&str>,
288289
) -> Vec<Vec<String>> {
289-
let app_config_state = app_handle
290-
.and_then(|app| {
291-
Some(
292-
app.try_state::<Arc<crate::commands::AppConfigState>>()
293-
.unwrap(),
294-
)
295-
})
296-
.unwrap();
297-
let translations = app_config_state.translations.lock().ok().unwrap(); // content as (dist => locales/interface/<selected-language>.ts)
298-
let config = app_config_state.config.lock().ok().unwrap(); // content as (dist => configs/mxu-<program-name>.ts)
290+
let app_config_state =
291+
match app_handle.and_then(|app| app.try_state::<Arc<crate::commands::AppConfigState>>()) {
292+
Some(state) => state,
293+
None => {
294+
error!("[MXU_STATUS] fail to get resource [app_config_state]");
295+
return vec![];
296+
}
297+
};
298+
let translations = match app_config_state.translations.lock() {
299+
Ok(guard) => guard,
300+
Err(e) => {
301+
error!(
302+
"[MXU_STATUS] fail to lock resource [app_config_state.translations]: {:?}",
303+
e
304+
);
305+
return vec![];
306+
}
307+
};
308+
let config = match app_config_state.config.lock() {
309+
Ok(guard) => guard,
310+
Err(e) => {
311+
error!("[MXU_STATUS] fail to lock resource [app_config_state.config]: {:?}", e);
312+
return vec![];
313+
}
314+
};
299315

300316
// i18n
301317
let language = config
@@ -316,23 +332,52 @@ pub fn get_checked_task_status_of_instance(
316332

317333
// instance (config)
318334
let id = instance_id.unwrap_or("");
319-
let instance_config_list = config.get("instances");
320-
let instance_config = instance_config_list
321-
.unwrap()
322-
.as_array()
323-
.unwrap()
335+
let instance_config_list = match config.get("instances").and_then(|v| v.as_array()) {
336+
Some(list) => list,
337+
None => {
338+
error!("[MXU_STATUS] config data [configs/mxu-*.json > .instances] should be [array]");
339+
return vec![];
340+
}
341+
};
342+
let instance_config = match instance_config_list
324343
.iter()
325344
.find(|inst| inst.get("id").and_then(|v| v.as_str()) == Some(id))
326-
.unwrap();
345+
{
346+
Some(inst) => inst,
347+
None => {
348+
error!("[MXU_STATUS] config data [configs/mxu-*.json > .instances] should contains [object] item with whose [.id = {}]", id);
349+
return vec![];
350+
}
351+
};
327352

328353
// instance (runtime)
329-
let maa_state = app_handle
330-
.and_then(|app| Some(app.try_state::<Arc<crate::commands::MaaState>>().unwrap()))
331-
.unwrap();
332-
let instance_runtime_list = maa_state.instances.lock().ok().unwrap();
333-
let instance_runtime = instance_runtime_list
334-
.get(instance_id.unwrap_or_default())
335-
.unwrap();
354+
let maa_state =
355+
match app_handle.and_then(|app| app.try_state::<Arc<crate::commands::MaaState>>()) {
356+
Some(state) => state,
357+
None => {
358+
error!("[MXU_STATUS] fail to get resource [maa_state]");
359+
return vec![];
360+
}
361+
};
362+
363+
let instance_runtime_list = match maa_state.instances.lock() {
364+
Ok(guard) => guard,
365+
Err(e) => {
366+
error!("[MXU_STATUS] fail to lock resource [maa_state]: {:?}", e);
367+
return vec![];
368+
}
369+
};
370+
371+
let instance_runtime = match instance_runtime_list.get(instance_id.unwrap_or_default()) {
372+
Some(runtime) => runtime,
373+
None => {
374+
error!(
375+
"[MXU_STATUS] runtime data [maa_state.instances[{}]] should be [object]",
376+
instance_id.unwrap_or_default()
377+
);
378+
return vec![];
379+
}
380+
};
336381

337382
return instance_runtime
338383
.task_run_state
@@ -347,22 +392,15 @@ pub fn get_checked_task_status_of_instance(
347392
.statuses
348393
.get(selected_task_id)
349394
{
350-
let task_config_list = instance_config.get("tasks").unwrap();
351-
let task_config = task_config_list
352-
.as_array()
353-
.unwrap()
354-
.iter()
355-
.find(|task| {
356-
task.get("id").and_then(|v| v.as_str())
357-
== Some(selected_task_id.as_str())
358-
})
359-
.unwrap();
395+
let task_config_list = instance_config.get("tasks")?.as_array()?;
396+
let task_config = task_config_list.iter().find(|task| {
397+
task.get("id").and_then(|v| v.as_str()) == Some(selected_task_id.as_str())
398+
})?;
360399
let task_name = task_config
361400
.get("taskName")
362-
.unwrap()
363-
.as_str()
364-
.unwrap()
365-
.to_string();
401+
.and_then(|v| v.as_str())
402+
.map(|s| s.to_string())
403+
.unwrap_or("".to_string());
366404
let custom_name = task_config
367405
.get("customName")
368406
.and_then(|v| v.as_str())
@@ -371,16 +409,23 @@ pub fn get_checked_task_status_of_instance(
371409
let task_name_i18n = i18n
372410
.get(format!("task.{}.label", task_name))
373411
.and_then(|v| v.as_str())
374-
.unwrap_or("")
375-
.to_string();
412+
.map(|s| s.to_string())
413+
.unwrap_or("".to_string());
376414
// custom name / task name (i18n) / task name
377415
// => task status ("idle","pending","running","succeeded","failed")
378416
let name: String = if !custom_name.is_empty() {
379417
custom_name
380418
} else if !task_name_i18n.is_empty() {
381419
task_name_i18n
382-
} else {
420+
} else if !task_name.is_empty(){
383421
task_name
422+
} else {
423+
error!(
424+
"[MXU_STATUS] config data [configs/mxu-*.json > .instances[.id = \"{}\"].tasks[.id = \"{}\"].taskName] should be [string]",
425+
id,
426+
selected_task_id
427+
);
428+
return None
384429
};
385430
Some(vec![name, status.to_string()])
386431
} else {

src/i18n/locales/en-US.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ export default {
141141
programPlaceholder: 'Enter program path or click browse...',
142142
argsLabel: 'Additional Arguments',
143143
argsPlaceholder: 'Enter additional arguments (optional, template variables supported)',
144-
argsDescription: 'Template variables {{STATUS}} {{S_BASE64}} {{S_CSV}} {{S_JSON}} {{S_JSON_BASE64}} represent the real-time status of selected tasks of the current instance. See https://github.com/MistEO/MXU/blob/main/src-tauri/src/mxu_actions.rs#L207 for details.',
144+
argsDescription: 'Template variables {{STATUS}} {{S_BASE64}} {{S_CSV}} {{S_JSON}} {{S_JSON_BASE64}} represent the real-time status of selected tasks of the current instance. See https://github.com/MistEO/MXU/blob/main/src-tauri/src/mxu_actions.rs for details.',
145145
waitLabel: 'Wait for Exit',
146146
waitDescription:
147147
'When disabled, continues immediately after launch; when enabled, waits for the process to exit before continuing, suitable for scripts that need to complete synchronously',

src/i18n/locales/ja-JP.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@ export default {
281281
programPlaceholder: 'プログラムパスを入力または参照...',
282282
args: '追加引数',
283283
argsPlaceholder: '追加パラメータを入力(オプション、テンプレート変数可)',
284-
argsDescription: 'テンプレート変数 {{STATUS}} {{S_BASE64}} {{S_CSV}} {{S_JSON}} {{S_JSON_BASE64}} は、現在のインスタンスの選択されたタスクのリアルタイム状態を表します。詳細は https://github.com/MistEO/MXU/blob/main/src-tauri/src/mxu_actions.rs#L207 を参照してください。',
284+
argsDescription: 'テンプレート変数 {{STATUS}} {{S_BASE64}} {{S_CSV}} {{S_JSON}} {{S_JSON_BASE64}} は、現在のインスタンスの選択されたタスクのリアルタイム状態を表します。詳細は https://github.com/MistEO/MXU/blob/main/src-tauri/src/mxu_actions.rs を参照してください。',
285285
browse: '参照',
286286
waitForExit: '終了を待機',
287287
waitForExitHintPre:

src/i18n/locales/ko-KR.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ export default {
138138
programPlaceholder: '프로그램 경로를 입력하거나 오른쪽 찾아보기를 클릭...',
139139
argsLabel: '추가 인수',
140140
argsPlaceholder: '추가 인수 입력(선택 사항, 템플릿 변수 지원)',
141-
argsDescription: '템플릿 변수 {{STATUS}} {{S_BASE64}} {{S_CSV}} {{S_JSON}} {{S_JSON_BASE64}} 는 현재 인스턴스의 선택된 모든 작업의 실시간 상태를 나타냅니다. 자세한 내용은 https://github.com/MistEO/MXU/blob/main/src-tauri/src/mxu_actions.rs#L207 를 참조하세요.',
141+
argsDescription: '템플릿 변수 {{STATUS}} {{S_BASE64}} {{S_CSV}} {{S_JSON}} {{S_JSON_BASE64}} 는 현재 인스턴스의 선택된 모든 작업의 실시간 상태를 나타냅니다. 자세한 내용은 https://github.com/MistEO/MXU/blob/main/src-tauri/src/mxu_actions.rs 를 참조하세요.',
142142
waitLabel: '종료 대기',
143143
waitDescription:
144144
'비활성화하면 실행 후 즉시 계속합니다. 활성화하면 프로세스 종료 후 계속합니다. 스크립트 등 동기 완료가 필요한 작업에 적합합니다',

src/i18n/locales/zh-CN.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ export default {
137137
programPlaceholder: '输入程序路径或点击右侧浏览...',
138138
argsLabel: '附加参数',
139139
argsPlaceholder: '输入附加参数(可选,支持模板变量)',
140-
argsDescription: '模板变量 {{STATUS}} {{S_BASE64}} {{S_CSV}} {{S_JSON}} {{S_JSON_BASE64}} 表示 当前实例-所有选定任务-实时状态,详见 https://github.com/MistEO/MXU/blob/main/src-tauri/src/mxu_actions.rs#L207 。',
140+
argsDescription: '模板变量 {{STATUS}} {{S_BASE64}} {{S_CSV}} {{S_JSON}} {{S_JSON_BASE64}} 表示 当前实例-所有选定任务-实时状态,详见 https://github.com/MistEO/MXU/blob/main/src-tauri/src/mxu_actions.rs 。',
141141
waitLabel: '等待退出',
142142
waitDescription: '禁用时启动进程后立即继续;启用时等待进程退出后再继续工作',
143143
waitYes: '等待程序退出后继续',

src/i18n/locales/zh-TW.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ export default {
136136
programPlaceholder: '輸入程式路徑或點擊右側瀏覽...',
137137
argsLabel: '附加參數',
138138
argsPlaceholder: '輸入附加參數(可選,支持模板變量)',
139-
argsDescription: '模板變量 {{STATUS}} {{S_BASE64}} {{S_CSV}} {{S_JSON}} {{S_JSON_BASE64}} 表示 當前實例-所有選定任務-即時狀態,詳見 https://github.com/MistEO/MXU/blob/main/src-tauri/src/mxu_actions.rs#L207 。',
139+
argsDescription: '模板變量 {{STATUS}} {{S_BASE64}} {{S_CSV}} {{S_JSON}} {{S_JSON_BASE64}} 表示 當前實例-所有選定任務-即時狀態,詳見 https://github.com/MistEO/MXU/blob/main/src-tauri/src/mxu_actions.rs 。',
140140
waitLabel: '等待退出',
141141
waitDescription:
142142
'禁用時啟動程序後立即繼續;啟用時等待程序退出後再繼續,適用於執行腳本等需要同步完成的操作',

0 commit comments

Comments
 (0)