Skip to content

Commit

Permalink
fix. 完善各模块
Browse files Browse the repository at this point in the history
  • Loading branch information
btjawa committed Dec 31, 2023
1 parent 5eed76b commit 2f73186
Show file tree
Hide file tree
Showing 7 changed files with 73 additions and 35 deletions.
3 changes: 2 additions & 1 deletion src-tauri/.taurignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/ffmpeg/*
/ffmpeg/*
/Temp/*
21 changes: 21 additions & 0 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ chrono = "0.4"
rusqlite = { version = "0.27.0", features = ["bundled"] }
regex = "1.10.2"
futures = "0.3"
tauri = { version = "1.5", features = [ "os-all", "shell-open", "dialog-open", "http-request"] }
tauri = { version = "1.5", features = [ "updater", "os-all", "shell-open", "dialog-open", "http-request"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
reqwest = { version = "0.11.9", features = ["json", "cookies", "stream"] }
Expand Down
9 changes: 6 additions & 3 deletions src-tauri/src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ use log4rs::{
encode::pattern::PatternEncoder,
};
use log::LevelFilter;
use std::{env, path::PathBuf};
pub fn init_logger() -> Result<(), Box<dyn std::error::Error>> {
let logfile = format!("logs/{}.log", Local::now().format("%Y-%m-%d_%H-%M-%S"));
let logfile = format!("{}/{}.log",
PathBuf::from(env::var("APPDATA").unwrap()).join("com.btjawa.bilitools").join("Logs").to_string_lossy(),
Local::now().format("%Y-%m-%d_%H-%M-%S"));
let file_appender = FileAppender::builder()
.encoder(Box::new(PatternEncoder::new("[log {d(%Y-%m-%d %H:%M:%S)}] {m}{n}")))
.encoder(Box::new(PatternEncoder::new("[{l} {d(%Y-%m-%d %H:%M:%S)}] {m}{n}")))
.build(logfile)?;
let console_appender = ConsoleAppender::builder()
.encoder(Box::new(PatternEncoder::new("[log {d(%Y-%m-%d %H:%M:%S)}] {m}{n}")))
.encoder(Box::new(PatternEncoder::new("[{l} {d(%Y-%m-%d %H:%M:%S)}] {m}{n}")))
.build();
let config = Config::builder()
.appender(Appender::builder().build("file", Box::new(file_appender)))
Expand Down
46 changes: 22 additions & 24 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,12 @@ lazy_static! {
static ref LOGIN_POLLING: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
static ref DOWNLOAD_INFO_MAP: Mutex<HashMap<String, VideoInfo>> = Mutex::new(HashMap::new());
static ref WORKING_DIR: PathBuf = {
PathBuf::from(env::var("APPDATA").expect("APPDATA environment variable not found"))
.join("com.btjawa.bilitools")
PathBuf::from(env::var("APPDATA").unwrap()).join("com.btjawa.bilitools")
};
static ref DOWNLOAD_DIR: Arc<RwLock<PathBuf>> = {
Arc::new(RwLock::new(PathBuf::from(env::var("USERPROFILE").expect("USERPROFILE environment variable not found"))
.join("Desktop")))
Arc::new(RwLock::new(PathBuf::from(env::var("USERPROFILE").unwrap()).join("Desktop")))
};
static ref TEMP_DIR: Arc<RwLock<PathBuf>> = Arc::new(RwLock::new(WORKING_DIR.join("Temp")));
static ref TEMP_DIR: Arc<RwLock<PathBuf>> = Arc::new(RwLock::new(env::current_dir().unwrap().join("Temp")));
static ref COOKIE_PATH: PathBuf = WORKING_DIR.join("Cookies");
static ref CONFIG_PATH: Arc<RwLock<PathBuf>> = Arc::new(RwLock::new(WORKING_DIR.join("config.json")));
static ref MAX_CONCURRENT_DOWNLOADS: Arc<RwLock<usize>> = Arc::new(RwLock::new(2));
Expand Down Expand Up @@ -348,7 +346,7 @@ async fn download_file(window: tauri::Window, task: DownloadTask, action: String
let mut downloaded: u64 = 0;
let start_time = Instant::now();
let mut last_log_time = Instant::now();
let log_interval = Duration::from_millis(250);
let log_interval = Duration::from_secs(1);
while let Some(chunk_result) = stream.next().await {
match chunk_result {
Ok(chunk) => {
Expand Down Expand Up @@ -392,7 +390,7 @@ async fn download_file(window: tauri::Window, task: DownloadTask, action: String
async fn merge_video_audio(window: tauri::Window, audio_path: &PathBuf, video_path: &PathBuf, output: &PathBuf) -> Result<String, String> {
log::info!("");
log::info!("Starting merge process for audio");
let current_dir = env::current_dir().map_err(|e| {handle_err(window.clone(), e.to_string()); e.to_string()})?;
let current_dir = env::current_dir().unwrap();
let ffmpeg_path = current_dir.join("ffmpeg").join("ffmpeg.exe");
let output_path = output.to_string_lossy();
if let Some(ss_dir_path) = output.parent() {
Expand All @@ -401,7 +399,6 @@ async fn merge_video_audio(window: tauri::Window, audio_path: &PathBuf, video_pa
log::info!("成功创建{}", ss_dir_path.to_string_lossy());
}
}
let output_clone = output_path.clone();
let video_filename = &output.file_name()
.and_then(|f| f.to_str())
.ok_or_else(|| "无法提取视频文件名".to_string())?;
Expand Down Expand Up @@ -466,7 +463,7 @@ async fn merge_video_audio(window: tauri::Window, audio_path: &PathBuf, video_pa
}
}
}
messages.push(&output_clone);
messages.push(&video_filename);
log::info!("{:?}", messages.join(" | "));
io::stdout().flush().map_err(|e| {handle_err(window.clone(), e.to_string()); e.to_string()})?;
window_clone.emit("merge-progress", &messages).map_err(|e| {handle_err(window.clone(), e.to_string()); e.to_string()})?;
Expand All @@ -488,13 +485,13 @@ async fn merge_video_audio(window: tauri::Window, audio_path: &PathBuf, video_pa
if status.success() {
log::info!("");
log::info!("FFmpeg process completed.");
window.emit("merge-success", output).unwrap();
Ok(output_path.to_string())
window.emit("merge-success", video_filename).unwrap();
Ok(video_filename.to_string())
} else {
if let Err(e) = tokio::fs::remove_file(&*output_path.clone()).await {
return Err(format!("无法删除合并失败视频文件: {}", e));
}
window.emit("merge-failed", output).unwrap();
window.emit("merge-failed", video_filename).unwrap();
Err("FFmpeg command failed".to_string())
}
}
Expand Down Expand Up @@ -559,13 +556,10 @@ fn insert_cookie(window: tauri::Window, cookie_str: &str) -> Result<(), String>
// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
async fn init(window: tauri::Window) -> Result<i64, String> {
init_database(window.clone().clone()).await;
rw_config(window.clone(), "read".to_string(), None).await.map_err(|e| {handle_err(window.clone(), e.to_string()); e.to_string()})?;
let window_clone = window.clone();
stop_login();
tokio::spawn(async move {
init_database(window_clone.clone()).await;
let _ = get_buvid(window_clone).await;
});
let _ = get_buvid(window.clone()).await;
let cookies = load_cookies().unwrap_or_else(|err| { log::warn!("Error loading cookies: {:?}", err);
HashMap::new() });
if let Some(mid_cookie) = cookies.values().find(|cookie| cookie.name.eq("DedeUserID")) {
Expand Down Expand Up @@ -632,16 +626,20 @@ async fn rw_config(window: tauri::Window, action: String, sets: Option<Settings>
}

#[tauri::command]
async fn open_select(_window: tauri::Window, display_name: String, cid: String) {
async fn open_select(window: tauri::Window, display_name: String, cid: String) {
let download_info_map = DOWNLOAD_INFO_MAP.lock().await;
if let Some(video_info) = download_info_map.get(&display_name) {
if video_info.cid == cid {
let _ = Command::new("C:\\Windows\\explorer.exe")
.arg(format!("/select,{}", video_info.output_path.to_string_lossy()))
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("Failed to open Windows Explorer");
if let Err(e) = fs::metadata(&video_info.output_path) {
handle_err(window.clone(), e.to_string());
} else {
let _ = Command::new("C:\\Windows\\explorer.exe")
.arg(format!("/select,\"{}\"", video_info.output_path.to_string_lossy()))
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| {handle_err(window.clone(), e.to_string()); e.to_string()});
}
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -1537,7 +1537,7 @@ input[name="temp-dir-path"] {
animation: settings-page-anime 0.5s cubic-bezier(0,1,.6,1);
}

.settings-page._info svg { width: 20%; }
.settings-page._info svg { width: 235px; }

.settings-page._info img {
width: 80px;
Expand Down
25 changes: 20 additions & 5 deletions src/js/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ async function getDownUrl(details, quality, action, line, fileType, index) {
if (action=="multi") downAudios++;
let qualityStr, ext, displayName;
const safeTitle = videoData[index].title.replace(/\s*[\\/:*?"<>|]\s*/g, '_').replace(/\s/g, '_');
const ssDir = videoData[index].ss_title;
const ssDir = `《${videoData[index].ss_title}》`;
if (action == "only") {
qualityStr = isVideo ? quality.dms_desc : quality.ads_desc;
ext = isVideo ? "mp4" : "aac";
Expand Down Expand Up @@ -998,10 +998,22 @@ async function appendDownPageBlock(type, quality, data) { // 填充下载块
const infoDesc = $('<div>').addClass('down-page-info-desc').html(desc.replace(/\n/g, '<br>'));
const infoTitle = $('<div>').addClass('down-page-info-title').html(finalTitle).css('max-width', `100%`);
const infoProgressText = $('<div>').addClass('down-page-info-progress-text').html(`等待下载`);
const infoProgress = $('<div>').addClass('down-page-info-progress').html($('<div>').addClass('down-page-info-progress-bar'));
const openDirBtn = $('<div>').addClass('down-page-open-dir-btn').html(`<i class="fa-solid fa-file-${type=="aac"?'audio':'video'} icon-small"></i>打开文件`);
const infoProgressBar = $('<div>').addClass('down-page-info-progress-bar');
const infoProgress = $('<div>').addClass('down-page-info-progress').html(infoProgressBar);
const openDirBtn = $('<div>').addClass('down-page-open-dir-btn').html(`<i class="fa-solid fa-file-${type=="aac"?'audio':'video'} icon-small"></i>定位文件`);
infoBlock.append(infoCover, infoData.append(infoId, infoTitle, infoDesc, openDirBtn, infoProgressText, infoProgress)).appendTo(downPage);
openDirBtn.on('click', () => invoke('open_select', { displayName: finalTitle, cid: cid.toString() }));
openDirBtn.on('click', () => {
if (parseFloat(infoProgressBar.css('width')) / parseFloat(infoProgress.css('width')) < 1) {
iziToast.error({
icon: 'fa-regular fa-circle-exclamation',
layout: '2',
title: `下载`,
message: `请等待下载完毕`
});
} else {
invoke('open_select', { displayName: finalTitle, cid: cid.toString() });
}
});
}

function applyDimensionList(details, type, action, ms) { // 填充分辨率
Expand Down Expand Up @@ -1736,7 +1748,8 @@ listen("download-success", async (event) => {
icon: 'fa-solid fa-circle-info',
layout: '2',
title: '下载',
message: `《${event.payload}》下载成功~`,
timeout: 10000,
message: `《${event.payload}》下载成功~<br>可在下载页中点击&nbsp;“定位文件”&nbsp;定位文件`,
});
})

Expand All @@ -1745,6 +1758,7 @@ listen("download-failed", async (event) => {
icon: 'fa-solid fa-circle-info',
layout: '2',
title: '下载',
timeout: 10000,
message: `《${event.payload[0]}》下载失败<br>错误原因: ${event.payload[1]}`,
});
})
Expand All @@ -1754,6 +1768,7 @@ listen("error", async (event) => {
icon: 'fa-solid fa-circle-info',
layout: '2',
title: '错误',
timeout: 10000,
message: `遇到错误:${event.payload}`,
});
})

0 comments on commit 2f73186

Please sign in to comment.