Skip to content

Commit

Permalink
feat: update all (close #2)
Browse files Browse the repository at this point in the history
  • Loading branch information
std-microblock committed Feb 12, 2024
1 parent 2414f92 commit 4c82e6e
Show file tree
Hide file tree
Showing 2 changed files with 119 additions and 34 deletions.
96 changes: 79 additions & 17 deletions src/celemod-ui/src/routes/Manage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -116,20 +116,20 @@ const ModMissing = ({ name, version, optional }: MissingModDepInfo) => {
onClick={
url !== null
? async () => {
setState(_i18n.t('下载中'));
download.downloadMod(name, url, {
onProgress: (task, progress) => {
setState(`${progress}% (${task.subtasks.length})`);
},
onFinished: () => {
setState(_i18n.t('下载完成'));
ctx?.reloadMods();
},
onFailed: () => {
setState(_i18n.t('下载失败'));
},
});
}
setState(_i18n.t('下载中'));
download.downloadMod(name, url, {
onProgress: (task, progress) => {
setState(`${progress}% (${task.subtasks.length})`);
},
onFinished: () => {
setState(_i18n.t('下载完成'));
ctx?.reloadMods();
},
onFailed: () => {
setState(_i18n.t('下载失败'));
},
});
}
: undefined
}
>
Expand Down Expand Up @@ -201,9 +201,8 @@ const ModLocal = ({
return (
<div className={`m-mod ${enabled && 'enabled'}`}>
<span
className={`expandBtn ${expanded && 'expanded'} ${
hasDeps && 'clickable'
}`}
className={`expandBtn ${expanded && 'expanded'} ${hasDeps && 'clickable'
}`}
onClick={() => setExpanded(!expanded)}
>
{hasDeps && (!optional || ctx?.fullTree) ? (
Expand Down Expand Up @@ -459,6 +458,35 @@ export const Manage = () => {

return modMap;
}, [installedMods, currentProfile, profiles, checkOptionalDep]);

const [latestModInfos, setLatestModInfos] = useState<[
string, string, string // name, version, url
][]>([]);

useEffect(() => {
callRemote('get_mod_latest_info', v => {
setLatestModInfos(JSON.parse(v))
})
}, [])

const hasUpdateMods = useMemo(() => {
const mods = [];
for (const mod of installedMods) {
const latest = latestModInfos.find(v => v[0] === mod.name);
if (latest && compareVersion(latest[1], mod.version) > 0) {
mods.push({
name: mod.name,
version: latest[1],
url: latest[2]
});
}
}

return mods;
}, [latestModInfos, installedModMap]);

const [hasUpdateBtnState, setHasUpdateBtnState] = useState('更新全部');

const modsTreeRef = useRef(null);
const [filter, setFilter] = useState('');

Expand Down Expand Up @@ -625,6 +653,8 @@ export const Manage = () => {
[currentProfile, installedMods, gamePath, modPath, fullTree, showUpdate]
);

const { download } = useGlobalContext()

return (
<div className="manage">
<modListContext.Provider value={manageCtx}>
Expand Down Expand Up @@ -729,6 +759,38 @@ export const Manage = () => {
{_i18n.t('显示更新')}
</label>
</div>
<div className="opers" style={{
marginTop: "5px"
}}>
{showUpdate && hasUpdateMods.length !== 0 && (
<button onClick={() => {
if (hasUpdateBtnState !== '更新全部') return;
setHasUpdateBtnState('更新中');
const updateUnfinishedSet = new Set(hasUpdateMods.map(v => v.name));
for (const mod of hasUpdateMods) {
download.downloadMod(mod.name, mod.url, {
onProgress: (task, progress) => {
console.log(task, progress);
},
onFinished: () => {
updateUnfinishedSet.delete(mod.name);
if (updateUnfinishedSet.size === 0) {
setHasUpdateBtnState('更新完成');
manageCtx.reloadMods();
}
},
onFailed: () => {
console.log('failed');
setHasUpdateBtnState('更新失败,请查看左下角');
},
force: true,
});
}
}}>
{hasUpdateBtnState}
</button>
)}
</div>
<div className="list" ref={modsTreeRef}>
{installedModsTree.map((v) => (
<Mod {...(v as any)} />
Expand Down
57 changes: 40 additions & 17 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

use serde::{de::VariantAccess, Deserialize, Serialize};

use anyhow::{bail, Context};
use aria2c::DownloadCallbackInfo;
use everest::get_mod_cached_new;
use game_scanner::prelude::Game;
use std::{
borrow::BorrowMut,
cell::RefCell,
Expand All @@ -12,11 +16,7 @@ use std::{
path::{Path, PathBuf},
rc::Rc,
sync::RwLock,
};
use anyhow::{bail, Context};
use aria2c::DownloadCallbackInfo;
use everest::get_mod_cached_new;
use game_scanner::prelude::Game;
};

use sciter::{dispatch_script_call, make_args, Value, GFX_LAYER};

Expand Down Expand Up @@ -50,7 +50,7 @@ fn compare_version(a: &str, b: &str) -> i32 {
}

struct Handler;

fn extract_mod_for_yaml(path: &PathBuf) -> anyhow::Result<serde_yaml::Value> {
let zipfile = std::fs::File::open(path)?;
let mut archive = zip::ZipArchive::new(zipfile)?;
Expand Down Expand Up @@ -144,22 +144,23 @@ fn get_installed_mods_sync(mods_folder_path: String) -> Vec<LocalMod> {
read_to_string_bom(&cache_path)?
} else if entry.file_type().unwrap().is_dir() {
let cache_path = entry.path().read_dir()?.find(|v| {
v.as_ref().map(|v| {
let name = v.file_name()
.to_string_lossy()
.to_string()
.to_lowercase();
name == "everest.yaml" || name == "everest.yml"
})
.unwrap_or(false)
v.as_ref()
.map(|v| {
let name = v.file_name().to_string_lossy().to_string().to_lowercase();
name == "everest.yaml" || name == "everest.yml"
})
.unwrap_or(false)
});
match cache_path {
Some(cache_path) => {
let cache_path = cache_path.unwrap().path();
read_to_string_bom(&cache_path)?
}
None => {
println!("[ WARNING ] Failed to find yaml, skipping {:?}", entry.file_name());
println!(
"[ WARNING ] Failed to find yaml, skipping {:?}",
entry.file_name()
);
continue;
}
}
Expand Down Expand Up @@ -481,7 +482,7 @@ impl Handler {
}

fn start_game_directly(&self, path: String, origin: bool) {
let game =Path::new(&path).join("Celeste.exe");
let game = Path::new(&path).join("Celeste.exe");
let game_origin = Path::new(&path).join("orig").join("Celeste.exe");

if origin {
Expand Down Expand Up @@ -628,6 +629,27 @@ impl Handler {
});
}

fn get_mod_latest_info(&self, callback: sciter::Value) {
std::thread::spawn(move || {
let res: anyhow::Result<Vec<(String, String, String)>> = try {
let mods = get_mod_cached_new()?;
mods.iter()
.map(|(k, v)|
(k.clone(), v.version.clone(), v.download_url.clone())
)
.collect()
};

let data = if let Ok(data) = res {
serde_json::to_string(&data).unwrap()
} else {
"[]".to_string()
};

callback.call(None, &make_args!(data), None).unwrap();
});
}

fn rm_mod(&self, mods_folder_path: String, mod_name: String) {
std::thread::spawn(move || {
if let Err(e) = rm_mod(&mods_folder_path, &mod_name) {
Expand Down Expand Up @@ -751,6 +773,7 @@ impl sciter::EventHandler for Handler {
fn do_self_update(String, Value);
fn start_game_directly(String, bool);
fn verify_celeste_install(String);
fn get_mod_latest_info(Value);
}
}

Expand All @@ -775,7 +798,7 @@ fn main() {
{
use winapi::um::wincon::{AttachConsole, ATTACH_PARENT_PROCESS};
use winapi::um::winuser::SetProcessDPIAware;
unsafe {
unsafe {
AttachConsole(ATTACH_PARENT_PROCESS);
SetProcessDPIAware();
}
Expand Down

0 comments on commit 4c82e6e

Please sign in to comment.