Refactoring

This commit is contained in:
Philip Kristoffersen
2022-04-04 21:57:30 +02:00
parent 1c376c2f31
commit 3b8aaffc31
6 changed files with 76 additions and 97 deletions
+1 -1
View File
@@ -55,7 +55,7 @@ impl From<HeroicGame> for ShortcutOwned {
&install_path,
&target,
"",
&game.launch_parameters.as_str(),
game.launch_parameters.as_str(),
);
let mut owned_shortcut = shortcut.to_owned();
owned_shortcut.tags.push("Heroic".to_owned());
+7 -9
View File
@@ -32,25 +32,23 @@ struct HeroicGogPath {
}
fn get_installed_json_location(install_mode: &InstallationMode) -> PathBuf {
let home_dir = std::env::var("HOME").unwrap_or("".to_string());
let home_dir = std::env::var("HOME").unwrap_or_else(|_| "".to_string());
match install_mode {
InstallationMode::FlatPak => Path::new(&home_dir)
.join(".var/app/com.heroicgameslauncher.hgl/config/legendary/installed.json"),
InstallationMode::UserBin => Path::new(&home_dir).join(".config/legendary/installed.json"),
}
.to_path_buf()
}
fn get_gog_installed_location(install_mode: &InstallationMode) -> PathBuf {
let home_dir = std::env::var("HOME").unwrap_or("".to_string());
let home_dir = std::env::var("HOME").unwrap_or_else(|_| "".to_string());
match install_mode {
InstallationMode::FlatPak => Path::new(&home_dir)
.join(".var/app/com.heroicgameslauncher.hgl/config/heroic/gog_store/installed.json"),
InstallationMode::UserBin => {
Path::new(&home_dir).join(".config/heroic/gog_store/installed.json")
}
}
.to_path_buf()
}
}
fn get_shortcuts_from_install_mode(
@@ -69,9 +67,10 @@ fn get_shortcuts_from_location<P: AsRef<Path>>(path: P) -> Result<Vec<HeroicGame
for game in games_map.values() {
games.push(game.clone());
}
return Ok(games);
Ok(games)
}else{
Ok(vec![])
}
return Ok(vec![]);
}
impl Platform<HeroicGameType, Box<dyn Error>> for HeroicPlatform {
@@ -151,8 +150,7 @@ fn get_gog_games(
})
.filter_map(|config_path| std::fs::read_to_string(config_path).ok())
.filter_map(|config_string| serde_json::from_str::<HeroicGogConfig>(&config_string).ok())
.map(|config| config.installed)
.flatten()
.flat_map(|config| config.installed)
.collect();
let mut is_windows_map = HashMap::new();
+15 -19
View File
@@ -7,7 +7,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use rusty_leveldb::{LdbIterator, Options, WriteBatch, DB};
const BOILR_TAG: &'static str = "boilr";
const BOILR_TAG: &str = "boilr";
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
@@ -77,13 +77,13 @@ struct ValueCollection {
}
impl ValueCollection {
fn new<S: AsRef<str>>(name: S, game_ids: &Vec<usize>) -> Self {
fn new<S: AsRef<str>>(name: S, game_ids: &[usize]) -> Self {
let name = name.as_ref();
let id = name_to_key(name);
let value = ValueCollection {
id,
name: name.to_string(),
added: game_ids.clone(),
added: game_ids.to_vec(),
removed: vec![],
};
value
@@ -275,7 +275,7 @@ fn get_namespaces(db: &mut DB, key_bytes: &[u8]) -> Option<Vec<(i32, String)>> {
match db.get(key_bytes) {
Some(got) => {
let collection_bytes = got.as_slice();
let collectin_str = String::from_utf8_lossy(&collection_bytes)[1..].to_string();
let collectin_str = String::from_utf8_lossy(collection_bytes)[1..].to_string();
let collection = serde_json::from_str(&collectin_str).unwrap_or_default();
Some(collection)
}
@@ -313,18 +313,18 @@ fn get_level_db_location() -> Option<PathBuf> {
.join("Local Storage")
.join("leveldb");
if path.exists() {
return Some(path.to_path_buf());
Some(path)
}else{
None
}
return None;
}
Err(_e) => return None,
Err(_e) => None,
}
}
fn serialize_collection_value<S: AsRef<str>>(name: S, game_ids: &Vec<usize>) -> String {
fn serialize_collection_value<S: AsRef<str>>(name: S, game_ids: &[usize]) -> String {
let value = ValueCollection::new(name, game_ids);
let value_json = serde_json::to_string(&value).expect("Should be able to serialize known type");
value_json
serde_json::to_string(&value).expect("Should be able to serialize known type")
}
fn name_to_key<S: AsRef<str>>(name: S) -> String {
@@ -338,11 +338,7 @@ fn parse_steam_collections<S: AsRef<str>>(
input: S,
) -> Result<Vec<(String, SteamCollection)>, Box<dyn Error>> {
let input = input.as_ref();
let input = if input.starts_with("\u{1}") {
input[1..].to_string()
} else {
input.to_string()
};
let input = input.strip_prefix('\u{1}').unwrap_or(input);
let res = serde_json::from_str::<Vec<(String, SteamCollection)>>(&input)?;
Ok(res)
}
@@ -366,17 +362,17 @@ pub fn write_vdf_collection_to_string<S: AsRef<str>>(
) -> Option<String> {
let input = input.as_ref();
let str = serde_json::to_string(vdf).expect("Should be able to serialize known type");
let encoded_json = format!("\"{}\"", str.replace("\"", "\\\""));
let encoded_json = format!("\"{}\"", str.replace('\\', "\\\""));
let key = "\t\"user-collections\"\t\t";
if let Some(start_index) = input.find_substring(key) {
let start_index_plus_key = start_index + key.len();
if let Some(line_index) = input[start_index_plus_key..].find("\n") {
if let Some(line_index) = input[start_index_plus_key..].find('\n') {
let end_index_in_full = line_index + start_index_plus_key;
let result = format!(
"{}{}{}",
input[..start_index_plus_key].to_string(),
&input[..start_index_plus_key],
encoded_json,
input[end_index_in_full..].to_string()
&input[end_index_in_full..]
);
return Some(result);
}
+4 -4
View File
@@ -42,9 +42,9 @@ fn enable_proton_games<S: AsRef<str>, B: AsRef<str>>(vdf_content: S, games: &[B]
.map(|game_id| {
let res = proton_replace_string.to_string();
let res = res.replace("\"X\"", &format!("\"{}\"", game_id.as_ref()));
let res = res.replace("=", &base_indent_string);
let res = res.replace("+", &field_indent_string);
res
let res = res.replace('=', &base_indent_string);
res.replace('+', &field_indent_string)
});
let mut new_section = section_str.to_string();
for game_string in games_strings_to_add {
@@ -59,7 +59,7 @@ fn enable_proton_games<S: AsRef<str>, B: AsRef<str>>(vdf_content: S, games: &[B]
//TODO make this an error instead?
println!("Could not find proton section in steam, try to manually set proton on at least one game and then rerun");
}
return vdf_content.to_string();
vdf_content.to_string()
}
struct SectionInfo {
+47 -62
View File
@@ -129,7 +129,11 @@ async fn search_fo_to_download(
let shortcuts_to_search_for = shortcuts.iter().filter(|s| {
// if we are missing any of the images we need to search for them
types.iter().map(|t| t.file_name(s.app_id)).any(|image| !known_images.contains(&image)) && !s.app_name.is_empty()
types
.iter()
.map(|t| t.file_name(s.app_id))
.any(|image| !known_images.contains(&image))
&& !s.app_name.is_empty()
});
let shortcuts_to_search_for: Vec<&ShortcutOwned> = shortcuts_to_search_for.collect();
if shortcuts_to_search_for.is_empty() {
@@ -153,7 +157,7 @@ async fn search_fo_to_download(
for (app_id, search) in search_results_a.into_iter().flatten() {
search_results.insert(app_id, search);
}
let mut to_download = vec![];
let grid_folder = Path::new(user_data_folder).join("config").join("grid");
for image_type in types {
@@ -168,22 +172,19 @@ async fn search_fo_to_download(
.collect();
let shortcuts: Vec<&ShortcutOwned> = images_needed.collect();
if let ImageType::Icon = image_type {
let mut index = 0;
for image_id in image_ids{
for (index,image_id) in image_ids.iter().enumerate() {
let shortcut = shortcuts[index];
if let Some(url) = get_steam_icon_url(image_id).await{
if let Some(url) = get_steam_icon_url(*image_id).await {
let path = grid_folder.join(image_type.file_name(shortcut.app_id));
to_download.push(ToDownload {
path,
url,
app_name: shortcut.app_name.clone(),
image_type: image_type.clone(),
image_type,
});
}
index = index + 1;
}
} else {
let image_search_result =
@@ -202,16 +203,12 @@ async fn search_fo_to_download(
Ok(img) => Some(img.url.clone()),
Err(_) => get_steam_image_url(game_id, &image_type).await,
};
if let Some(url) = image_url {
Some(ToDownload {
path,
url,
app_name: shortcut.app_name.clone(),
image_type: image_type.clone(),
})
} else {
None
}
image_url.map(|url| ToDownload {
path,
url,
app_name: shortcut.app_name.clone(),
image_type,
})
}
})
.collect::<Vec<ToDownload>>()
@@ -285,61 +282,49 @@ async fn get_images_for_ids(
async fn get_steam_image_url(game_id: usize, image_type: &ImageType) -> Option<String> {
let steamgriddb_page_url = format!("https://www.steamgriddb.com/api/public/game/{}/", game_id);
let response = reqwest::get(steamgriddb_page_url).await;
match response {
Ok(response) => {
let text_response = response.json::<PublicGameResponse>().await;
match text_response {
Ok(response) => {
let game_id = response
.data
.clone()
.map(|d| d.platforms.map(|p| p.steam.map(|s| s.id)));
let mtime = response.data.map(|d| {
d.platforms
.map(|p| p.steam.map(|s| s.metadata.map(|m| m.store_asset_mtime)))
});
if let (Some(Some(Some(steam_app_id))), Some(Some(Some(Some(Some(mtime)))))) =
(game_id, mtime)
{
return Some(image_type.steam_url(steam_app_id, mtime));
}
}
Err(_) => (),
if let Ok(response) = response {
let text_response = response.json::<PublicGameResponse>().await;
if let Ok(response) = text_response {
let game_id = response
.data
.clone()
.map(|d| d.platforms.map(|p| p.steam.map(|s| s.id)));
let mtime = response.data.map(|d| {
d.platforms
.map(|p| p.steam.map(|s| s.metadata.map(|m| m.store_asset_mtime)))
});
if let (Some(Some(Some(steam_app_id))), Some(Some(Some(Some(Some(mtime)))))) =
(game_id, mtime)
{
return Some(image_type.steam_url(steam_app_id, mtime));
}
}
Err(_) => (),
}
return None;
None
}
async fn get_steam_icon_url(game_id: usize) -> Option<String> {
let steamgriddb_page_url = format!("https://www.steamgriddb.com/api/public/game/{}/", game_id);
let response = reqwest::get(steamgriddb_page_url).await;
match response {
Ok(response) => {
let text_response = response.json::<PublicGameResponse>().await;
match text_response {
Ok(response) => {
let game_id = response
.data
.clone()
.map(|d| d.platforms.map(|p| p.steam.map(|s| s.id)));
let mtime = response.data.map(|d| {
d.platforms
.map(|p| p.steam.map(|s| s.metadata.map(|m| m.clienticon)))
});
if let (Some(Some(Some(steam_app_id))), Some(Some(Some(Some(Some(mtime)))))) =
(game_id, mtime)
{
return Some(icon_url(&steam_app_id, &mtime));
}
}
Err(_) => (),
if let Ok(response) = response {
let text_response = response.json::<PublicGameResponse>().await;
if let Ok(response) = text_response {
let game_id = response
.data
.clone()
.map(|d| d.platforms.map(|p| p.steam.map(|s| s.id)));
let mtime = response.data.map(|d| {
d.platforms
.map(|p| p.steam.map(|s| s.metadata.map(|m| m.clienticon)))
});
if let (Some(Some(Some(steam_app_id))), Some(Some(Some(Some(Some(mtime)))))) =
(game_id, mtime)
{
return Some(icon_url(&steam_app_id, &mtime));
}
}
Err(_) => (),
}
return None;
None
}
fn icon_url(steam_app_id: &str, icon_id: &str) -> String {
+2 -2
View File
@@ -122,7 +122,7 @@ fn fix_shortcut_icons(
fn write_shortcut_collections<S: AsRef<str>>(
steam_id: S,
platform_results: &Vec<(String, Vec<ShortcutOwned>)>,
platform_results: &[(String, Vec<ShortcutOwned>)],
) -> Result<(), Box<dyn Error>> {
let mut collections = vec![];
@@ -250,7 +250,7 @@ where
}
current_shortcuts.push(shortcut_owned.clone());
}
if shortcuts_to_proton.len() > 0 {
if !shortcuts_to_proton.is_empty() {
setup_proton_games(shortcuts_to_proton.as_slice());
}