Wire Profile Backend to Frontend (#71)

* Search updates

* fixes2

* Some more work

* start instance page wiring

* Pack installation + Profile viewing

* Remove print statement

* Fix disappearing profiles

* fix compile err

* Finish Instance Running

* remove print statement

* fix prettier

* Fix clippy + early return
This commit is contained in:
Geometrically 2023-04-08 18:54:38 -07:00 committed by GitHub
parent 764d75181f
commit a62d931fe2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 502 additions and 739 deletions

View File

@ -1,10 +1,13 @@
use crate::config::{MODRINTH_API_URL, REQWEST_CLIENT};
use crate::config::MODRINTH_API_URL;
use crate::data::ModLoader;
use crate::state::{ModrinthProject, ModrinthVersion, SideType};
use crate::util::fetch::{fetch, fetch_mirrors, write, write_cached_icon};
use crate::util::fetch::{
fetch, fetch_json, fetch_mirrors, write, write_cached_icon,
};
use crate::State;
use async_zip::tokio::read::seek::ZipFileReader;
use futures::TryStreamExt;
use reqwest::Method;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::Cursor;
@ -70,12 +73,15 @@ enum PackDependency {
pub async fn install_pack_from_version_id(
version_id: String,
) -> crate::Result<PathBuf> {
let version: ModrinthVersion = REQWEST_CLIENT
.get(format!("{}version/{}", MODRINTH_API_URL, version_id))
.send()
.await?
.json()
.await?;
let state = State::get().await?;
let version: ModrinthVersion = fetch_json(
Method::GET,
&format!("{}version/{}", MODRINTH_API_URL, version_id),
None,
&state.io_semaphore,
)
.await?;
let (url, hash) =
if let Some(file) = version.files.iter().find(|x| x.primary) {
@ -92,28 +98,19 @@ pub async fn install_pack_from_version_id(
)
})?;
let file = async {
let state = &State::get().await?;
let semaphore = state.io_semaphore.acquire().await?;
fetch(&url, hash.map(|x| &**x), &semaphore).await
}
.await?;
let file = fetch(&url, hash.map(|x| &**x), &state.io_semaphore).await?;
let project: ModrinthProject = REQWEST_CLIENT
.get(format!(
"{}project/{}",
MODRINTH_API_URL, version.project_id
))
.send()
.await?
.json()
.await?;
let project: ModrinthProject = fetch_json(
Method::GET,
&format!("{}project/{}", MODRINTH_API_URL, version.project_id),
None,
&state.io_semaphore,
)
.await?;
let icon = if let Some(icon_url) = project.icon_url {
let state = State::get().await?;
let semaphore = state.io_semaphore.acquire().await?;
let icon_bytes = fetch(&icon_url, None, &semaphore).await?;
let icon_bytes = fetch(&icon_url, None, &state.io_semaphore).await?;
let filename = icon_url.rsplit('/').next();
@ -123,7 +120,7 @@ pub async fn install_pack_from_version_id(
filename,
&state.directories.caches_dir(),
icon_bytes,
&semaphore,
&state.io_semaphore,
)
.await?,
)
@ -244,8 +241,6 @@ async fn install_pack(
}
}
let permit = state.io_semaphore.acquire().await?;
let file = fetch_mirrors(
&project
.downloads
@ -253,7 +248,7 @@ async fn install_pack(
.map(|x| &**x)
.collect::<Vec<&str>>(),
project.hashes.get(&PackFileHash::Sha1).map(|x| &**x),
&permit,
&state.io_semaphore,
)
.await?;
@ -263,7 +258,8 @@ async fn install_pack(
match path {
Component::CurDir | Component::Normal(_) => {
let path = profile.join(project.path);
write(&path, &file, &permit).await?;
write(&path, &file, &state.io_semaphore)
.await?;
}
_ => {}
};
@ -312,9 +308,12 @@ async fn install_pack(
}
if new_path.file_name().is_some() {
let permit = state.io_semaphore.acquire().await?;
write(&profile.join(new_path), &content, &permit)
.await?;
write(
&profile.join(new_path),
&content,
&state.io_semaphore,
)
.await?;
}
}
}

View File

@ -137,7 +137,15 @@ pub async fn profile_create(
let path = canonicalize(&path)?;
let mut profile = Profile::new(name, game_version, path.clone()).await?;
if let Some(ref icon) = icon {
profile.set_icon(icon).await?;
let bytes = tokio::fs::read(icon).await?;
profile
.set_icon(
&state.directories.caches_dir(),
&state.io_semaphore,
bytes::Bytes::from(bytes),
&icon.to_string_lossy(),
)
.await?;
}
if let Some((loader_version, loader)) = loader {
profile.metadata.loader = loader;

View File

@ -62,8 +62,7 @@ pub async fn download_version_info(
}
info.id = version_id.clone();
let permit = st.io_semaphore.acquire().await?;
write(&path, &serde_json::to_vec(&info)?, &permit).await?;
write(&path, &serde_json::to_vec(&info)?, &st.io_semaphore).await?;
Ok(info)
}?;
@ -93,11 +92,13 @@ pub async fn download_client(
.join(format!("{version}.jar"));
if !path.exists() {
let permit = st.io_semaphore.acquire().await?;
let bytes =
fetch(&client_download.url, Some(&client_download.sha1), &permit)
.await?;
write(&path, &bytes, &permit).await?;
let bytes = fetch(
&client_download.url,
Some(&client_download.sha1),
&st.io_semaphore,
)
.await?;
write(&path, &bytes, &st.io_semaphore).await?;
log::info!("Fetched client version {version}");
}
@ -123,8 +124,7 @@ pub async fn download_assets_index(
.and_then(|ref it| Ok(serde_json::from_slice(it)?))
} else {
let index = d::minecraft::fetch_assets_index(version).await?;
let permit = st.io_semaphore.acquire().await?;
write(&path, &serde_json::to_vec(&index)?, &permit).await?;
write(&path, &serde_json::to_vec(&index)?, &st.io_semaphore).await?;
log::info!("Fetched assets index");
Ok(index)
}?;
@ -154,25 +154,23 @@ pub async fn download_assets(
tokio::try_join! {
async {
if !resource_path.exists() {
let permit = st.io_semaphore.acquire().await?;
let resource = fetch_cell
.get_or_try_init(|| fetch(&url, Some(hash), &permit))
.get_or_try_init(|| fetch(&url, Some(hash), &st.io_semaphore))
.await?;
write(&resource_path, resource, &permit).await?;
write(&resource_path, resource, &st.io_semaphore).await?;
log::info!("Fetched asset with hash {hash}");
}
Ok::<_, crate::Error>(())
},
async {
if with_legacy {
let permit = st.io_semaphore.acquire().await?;
let resource = fetch_cell
.get_or_try_init(|| fetch(&url, Some(hash), &permit))
.get_or_try_init(|| fetch(&url, Some(hash), &st.io_semaphore))
.await?;
let resource_path = st.directories.legacy_assets_dir().join(
name.replace('/', &String::from(std::path::MAIN_SEPARATOR))
);
write(&resource_path, resource, &permit).await?;
write(&resource_path, resource, &st.io_semaphore).await?;
log::info!("Fetched legacy asset with hash {hash}");
}
Ok::<_, crate::Error>(())
@ -219,10 +217,9 @@ pub async fn download_libraries(
artifact: Some(ref artifact),
..
}) => {
let permit = st.io_semaphore.acquire().await?;
let bytes = fetch(&artifact.url, Some(&artifact.sha1), &permit)
let bytes = fetch(&artifact.url, Some(&artifact.sha1), &st.io_semaphore)
.await?;
write(&path, &bytes, &permit).await?;
write(&path, &bytes, &st.io_semaphore).await?;
log::info!("Fetched library {}", &library.name);
Ok::<_, crate::Error>(())
}
@ -235,9 +232,8 @@ pub async fn download_libraries(
&artifact_path
].concat();
let permit = st.io_semaphore.acquire().await?;
let bytes = fetch(&url, None, &permit).await?;
write(&path, &bytes, &permit).await?;
let bytes = fetch(&url, None, &st.io_semaphore).await?;
write(&path, &bytes, &st.io_semaphore).await?;
log::info!("Fetched library {}", &library.name);
Ok::<_, crate::Error>(())
}
@ -263,8 +259,7 @@ pub async fn download_libraries(
);
if let Some(native) = classifiers.get(&parsed_key) {
let permit = st.io_semaphore.acquire().await?;
let data = fetch(&native.url, Some(&native.sha1), &permit).await?;
let data = fetch(&native.url, Some(&native.sha1), &st.io_semaphore).await?;
let reader = std::io::Cursor::new(&data);
if let Ok(mut archive) = zip::ZipArchive::new(reader) {
match archive.extract(&st.directories.version_natives_dir(version)) {

View File

@ -21,7 +21,7 @@ impl DirectoryInfo {
// Config directory
let config_dir = Self::env_path("THESEUS_CONFIG_DIR")
.or_else(|| Some(dirs::config_dir()?.join("theseus")))
.or_else(|| Some(dirs::config_dir()?.join("com.modrinth.theseus")))
.ok_or(crate::ErrorKind::FSError(
"Could not find valid config dir".to_string(),
))?;

View File

@ -2,7 +2,7 @@
use crate::config::sled_config;
use crate::jre;
use std::sync::Arc;
use tokio::sync::{Mutex, OnceCell, RwLock, Semaphore};
use tokio::sync::{OnceCell, RwLock, Semaphore};
// Submodules
mod dirs;
@ -38,8 +38,6 @@ pub use self::java_globals::*;
// Global state
static LAUNCHER_STATE: OnceCell<Arc<State>> = OnceCell::const_new();
pub struct State {
/// Database, used to store some information
pub(self) database: sled::Db,
/// Information on the location of files used in the launcher
pub directories: DirectoryInfo,
/// Semaphore used to limit concurrent I/O and avoid errors
@ -88,7 +86,7 @@ impl State {
// Launcher data
let (metadata, profiles) = tokio::try_join! {
Metadata::init(&database),
Profiles::init(&database, &directories, &io_semaphore),
Profiles::init(&directories, &io_semaphore),
}?;
let users = Users::init(&database)?;
@ -112,7 +110,6 @@ impl State {
}
Ok(Arc::new(Self {
database,
directories,
io_semaphore,
metadata,
@ -133,7 +130,6 @@ impl State {
/// Synchronize in-memory state with persistent state
pub async fn sync() -> crate::Result<()> {
let state = Self::get().await?;
let batch = Arc::new(Mutex::new(sled::Batch::default()));
let sync_settings = async {
let state = Arc::clone(&state);
@ -148,13 +144,11 @@ impl State {
let sync_profiles = async {
let state = Arc::clone(&state);
let batch = Arc::clone(&batch);
tokio::spawn(async move {
let profiles = state.profiles.read().await;
let mut batch = batch.lock().await;
profiles.sync(&mut batch).await?;
profiles.sync().await?;
Ok::<_, crate::Error>(())
})
.await?
@ -162,13 +156,6 @@ impl State {
tokio::try_join!(sync_settings, sync_profiles)?;
state.database.apply_batch(
Arc::try_unwrap(batch)
.expect("Error saving state by acquiring Arc")
.into_inner(),
)?;
state.database.flush_async().await?;
Ok(())
}
}

View File

@ -1,7 +1,7 @@
use super::settings::{Hooks, MemorySettings, WindowSize};
use crate::config::BINCODE_CONFIG;
use crate::data::DirectoryInfo;
use crate::state::projects::Project;
use crate::util::fetch::write_cached_icon;
use daedalus::modded::LoaderVersion;
use dunce::canonicalize;
use futures::prelude::*;
@ -14,21 +14,15 @@ use tokio::fs;
use tokio::sync::Semaphore;
const PROFILE_JSON_PATH: &str = "profile.json";
const PROFILE_SUBTREE: &[u8] = b"profiles";
pub(crate) struct Profiles(pub HashMap<PathBuf, Profile>);
// TODO: possibly add defaults to some of these values
pub const CURRENT_FORMAT_VERSION: u32 = 1;
pub const SUPPORTED_ICON_FORMATS: &[&str] = &[
"bmp", "gif", "jpeg", "jpg", "jpe", "png", "svg", "svgz", "webp", "rgb",
"mp4",
];
// Represent a Minecraft instance.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Profile {
#[serde(skip)]
pub path: PathBuf,
pub metadata: ProfileMetadata,
#[serde(skip_serializing_if = "Option::is_none")]
@ -124,26 +118,15 @@ impl Profile {
#[tracing::instrument]
pub async fn set_icon<'a>(
&'a mut self,
icon: &'a Path,
cache_dir: &Path,
semaphore: &Semaphore,
icon: bytes::Bytes,
file_name: &str,
) -> crate::Result<&'a mut Self> {
let ext = icon
.extension()
.and_then(std::ffi::OsStr::to_str)
.unwrap_or("");
if SUPPORTED_ICON_FORMATS.contains(&ext) {
let file_name = format!("icon.{ext}");
fs::copy(icon, &self.path.join(&file_name)).await?;
self.metadata.icon =
Some(Path::new(&format!("./{file_name}")).to_owned());
Ok(self)
} else {
Err(crate::ErrorKind::InputError(format!(
"Unsupported image type: {ext}"
))
.into())
}
let file =
write_cached_icon(file_name, cache_dir, icon, semaphore).await?;
self.metadata.icon = Some(file);
Ok(self)
}
#[tracing::instrument]
@ -161,7 +144,10 @@ impl Profile {
let new_path = self.path.join(path);
if new_path.exists() {
for path in std::fs::read_dir(self.path.join(path))? {
files.push(path?.path());
let path = path?.path();
if path.is_file() {
files.push(path);
}
}
}
Ok::<(), crate::Error>(())
@ -177,26 +163,17 @@ impl Profile {
}
impl Profiles {
#[tracing::instrument(skip(db))]
#[tracing::instrument]
pub async fn init(
db: &sled::Db,
dirs: &DirectoryInfo,
io_sempahore: &Semaphore,
) -> crate::Result<Self> {
let profile_db = db.get(PROFILE_SUBTREE)?.map_or(
Ok(Default::default()),
|bytes| {
bincode::decode_from_slice::<Box<[PathBuf]>, _>(
&bytes,
*BINCODE_CONFIG,
)
.map(|it| it.0)
},
)?;
let mut profiles = HashMap::new();
let mut entries = fs::read_dir(dirs.profiles_dir()).await?;
let mut profiles = stream::iter(profile_db.iter())
.then(|it| async move {
let path = PathBuf::from(it);
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
if path.is_dir() {
let prof = match Self::read_profile_from_dir(&path).await {
Ok(prof) => Some(prof),
Err(err) => {
@ -204,13 +181,12 @@ impl Profiles {
None
}
};
(path, prof)
})
.filter_map(|(key, opt_value)| async move {
opt_value.map(|value| (key, value))
})
.collect::<HashMap<PathBuf, Profile>>()
.await;
if let Some(profile) = prof {
let path = canonicalize(path)?;
profiles.insert(path, profile);
}
}
}
// project path, parent profile path
let mut files: HashMap<PathBuf, PathBuf> = HashMap::new();
@ -278,10 +254,7 @@ impl Profiles {
}
#[tracing::instrument(skip_all)]
pub async fn sync<'a>(
&'a self,
batch: &'a mut sled::Batch,
) -> crate::Result<&Self> {
pub async fn sync(&self) -> crate::Result<&Self> {
stream::iter(self.0.iter())
.map(Ok::<_, crate::Error>)
.try_for_each_concurrent(None, |(path, profile)| async move {
@ -295,13 +268,6 @@ impl Profiles {
})
.await?;
batch.insert(
PROFILE_SUBTREE,
bincode::encode_to_vec(
self.0.keys().collect::<Box<[_]>>(),
*BINCODE_CONFIG,
)?,
);
Ok(self)
}

View File

@ -2,6 +2,7 @@
use crate::config::{MODRINTH_API_URL, REQWEST_CLIENT};
use crate::util::fetch::write_cached_icon;
use async_zip::tokio::read::fs::ZipFileReader;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::json;
@ -10,14 +11,14 @@ use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tokio::io::AsyncReadExt;
use tokio::sync::Semaphore;
// use zip::ZipArchive;
use async_zip::tokio::read::fs::ZipFileReader;
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Project {
pub sha512: String,
pub disabled: bool,
pub metadata: ProjectMetadata,
pub file_name: String,
pub update_available: bool,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
@ -50,7 +51,7 @@ pub struct ModrinthProject {
}
/// A specific version of a project
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ModrinthVersion {
pub id: String,
pub project_id: String,
@ -73,7 +74,7 @@ pub struct ModrinthVersion {
pub loaders: Vec<String>,
}
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ModrinthVersionFile {
pub hashes: HashMap<String, String>,
pub url: String,
@ -83,7 +84,7 @@ pub struct ModrinthVersionFile {
pub file_type: Option<FileType>,
}
#[derive(Serialize, Deserialize, Clone)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Dependency {
pub version_id: Option<String>,
pub project_id: Option<String>,
@ -91,7 +92,27 @@ pub struct Dependency {
pub dependency_type: DependencyType,
}
#[derive(Serialize, Deserialize, Copy, Clone)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ModrinthTeamMember {
pub team_id: String,
pub user: ModrinthUser,
pub role: String,
pub ordering: i64,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ModrinthUser {
pub id: String,
pub github_id: Option<u64>,
pub username: String,
pub name: Option<String>,
pub avatar_url: Option<String>,
pub bio: Option<String>,
pub created: DateTime<Utc>,
pub role: String,
}
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
#[serde(rename_all = "lowercase")]
pub enum DependencyType {
Required,
@ -120,7 +141,11 @@ pub enum FileType {
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ProjectMetadata {
Modrinth(Box<ModrinthProject>),
Modrinth {
project: Box<ModrinthProject>,
version: Box<ModrinthVersion>,
members: Vec<ModrinthTeamMember>,
},
Inferred {
title: Option<String>,
description: Option<String>,
@ -163,9 +188,11 @@ async fn read_icon_from_file(
.is_ok()
{
let bytes = bytes::Bytes::from(bytes);
let permit = io_semaphore.acquire().await?;
let path = write_cached_icon(
&icon_path, cache_dir, bytes, &permit,
&icon_path,
cache_dir,
bytes,
io_semaphore,
)
.await?;
@ -196,12 +223,6 @@ pub async fn infer_data_from_files(
file_path_hashes.insert(hash, path.clone());
}
// TODO: add disabled mods
// TODO: add retrying
#[derive(Deserialize)]
pub struct ModrinthVersion {
pub project_id: String,
}
let files: HashMap<String, ModrinthVersion> = REQWEST_CLIENT
.post(format!("{}version_files", MODRINTH_API_URL))
.json(&json!({
@ -229,22 +250,54 @@ pub async fn infer_data_from_files(
.json()
.await?;
let teams: Vec<ModrinthTeamMember> = REQWEST_CLIENT
.get(format!(
"{}teams?ids={}",
MODRINTH_API_URL,
serde_json::to_string(
&projects.iter().map(|x| x.team.clone()).collect::<Vec<_>>()
)?
))
.send()
.await?
.json::<Vec<Vec<ModrinthTeamMember>>>()
.await?
.into_iter()
.flatten()
.collect();
let mut return_projects = HashMap::new();
let mut further_analyze_projects: Vec<(String, PathBuf)> = Vec::new();
for (hash, path) in file_path_hashes {
if let Some(file) = files.get(&hash) {
if let Some(version) = files.get(&hash) {
if let Some(project) =
projects.iter().find(|x| file.project_id == x.id)
projects.iter().find(|x| version.project_id == x.id)
{
let file_name = path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let team_members = teams
.iter()
.filter(|x| x.team_id == project.team)
.cloned()
.collect::<Vec<_>>();
return_projects.insert(
path,
Project {
sha512: hash,
disabled: false,
metadata: ProjectMetadata::Modrinth(Box::new(
project.clone(),
)),
metadata: ProjectMetadata::Modrinth {
project: Box::new(project.clone()),
version: Box::new(version.clone()),
members: team_members,
},
file_name,
update_available: false,
},
);
continue;
@ -255,6 +308,12 @@ pub async fn infer_data_from_files(
}
for (hash, path) in further_analyze_projects {
let file_name = path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let zip_file_reader = if let Ok(zip_file_reader) =
ZipFileReader::new(path.clone()).await
{
@ -266,6 +325,8 @@ pub async fn infer_data_from_files(
sha512: hash,
disabled: path.ends_with(".disabled"),
metadata: ProjectMetadata::Unknown,
file_name,
update_available: false,
},
);
continue;
@ -318,6 +379,8 @@ pub async fn infer_data_from_files(
Project {
sha512: hash,
disabled: path.ends_with(".disabled"),
file_name,
update_available: false,
metadata: ProjectMetadata::Inferred {
title: Some(
pack.display_name
@ -383,6 +446,8 @@ pub async fn infer_data_from_files(
Project {
sha512: hash,
disabled: path.ends_with(".disabled"),
file_name,
update_available: false,
metadata: ProjectMetadata::Inferred {
title: Some(if pack.name.is_empty() {
pack.modid
@ -447,6 +512,8 @@ pub async fn infer_data_from_files(
Project {
sha512: hash,
disabled: path.ends_with(".disabled"),
file_name,
update_available: false,
metadata: ProjectMetadata::Inferred {
title: Some(pack.name.unwrap_or(pack.id)),
description: pack.description,
@ -511,6 +578,8 @@ pub async fn infer_data_from_files(
Project {
sha512: hash,
disabled: path.ends_with(".disabled"),
file_name,
update_available: false,
metadata: ProjectMetadata::Inferred {
title: Some(
pack.metadata
@ -575,6 +644,8 @@ pub async fn infer_data_from_files(
Project {
sha512: hash,
disabled: path.ends_with(".disabled"),
file_name,
update_available: false,
metadata: ProjectMetadata::Inferred {
title: None,
description: pack.description,
@ -594,6 +665,8 @@ pub async fn infer_data_from_files(
Project {
sha512: hash,
disabled: path.ends_with(".disabled"),
file_name,
update_available: false,
metadata: ProjectMetadata::Unknown,
},
);

View File

@ -1,25 +1,51 @@
//! Functions for fetching infromation from the Internet
use crate::config::REQWEST_CLIENT;
use bytes::Bytes;
use reqwest::Method;
use serde::de::DeserializeOwned;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use tokio::sync::Semaphore;
use tokio::{
fs::{self, File},
io::AsyncWriteExt,
sync::SemaphorePermit,
};
const FETCH_ATTEMPTS: usize = 3;
/// Downloads a file with retry and checksum functionality
#[tracing::instrument(skip(_permit))]
pub async fn fetch<'a>(
pub async fn fetch(
url: &str,
sha1: Option<&str>,
_permit: &SemaphorePermit<'a>,
) -> crate::Result<bytes::Bytes> {
semaphore: &Semaphore,
) -> crate::Result<Bytes> {
fetch_advanced(Method::GET, url, sha1, semaphore).await
}
pub async fn fetch_json<T>(
method: Method,
url: &str,
sha1: Option<&str>,
semaphore: &Semaphore,
) -> crate::Result<T>
where
T: DeserializeOwned,
{
let result = fetch_advanced(method, url, sha1, semaphore).await?;
let value = serde_json::from_slice(&result)?;
Ok(value)
}
/// Downloads a file with retry and checksum functionality
#[tracing::instrument(skip(semaphore))]
pub async fn fetch_advanced(
method: Method,
url: &str,
sha1: Option<&str>,
semaphore: &Semaphore,
) -> crate::Result<Bytes> {
let _permit = semaphore.acquire().await?;
for attempt in 1..=(FETCH_ATTEMPTS + 1) {
let result = REQWEST_CLIENT.get(url).send().await;
let result = REQWEST_CLIENT.request(method.clone(), url).send().await;
match result {
Ok(x) => {
@ -50,7 +76,9 @@ pub async fn fetch<'a>(
}
}
Err(_) if attempt <= 3 => continue,
Err(err) => return Err(err.into()),
Err(err) => {
return Err(err.into());
}
}
}
@ -58,12 +86,12 @@ pub async fn fetch<'a>(
}
/// Downloads a file from specified mirrors
#[tracing::instrument(skip(permit))]
pub async fn fetch_mirrors<'a>(
#[tracing::instrument(skip(semaphore))]
pub async fn fetch_mirrors(
mirrors: &[&str],
sha1: Option<&str>,
permit: &SemaphorePermit<'a>,
) -> crate::Result<bytes::Bytes> {
semaphore: &Semaphore,
) -> crate::Result<Bytes> {
if mirrors.is_empty() {
return Err(crate::ErrorKind::InputError(
"No mirrors provided!".to_string(),
@ -72,7 +100,7 @@ pub async fn fetch_mirrors<'a>(
}
for (index, mirror) in mirrors.iter().enumerate() {
let result = fetch(mirror, sha1, permit).await;
let result = fetch(mirror, sha1, semaphore).await;
if result.is_ok() || (result.is_err() && index == (mirrors.len() - 1)) {
return result;
@ -82,28 +110,29 @@ pub async fn fetch_mirrors<'a>(
unreachable!()
}
#[tracing::instrument(skip(bytes, _permit))]
#[tracing::instrument(skip(bytes, semaphore))]
pub async fn write<'a>(
path: &Path,
bytes: &[u8],
_permit: &SemaphorePermit<'a>,
semaphore: &Semaphore,
) -> crate::Result<()> {
let _permit = semaphore.acquire().await?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).await?;
}
let mut file = File::create(path).await?;
log::debug!("Done writing file {}", path.display());
file.write_all(bytes).await?;
log::debug!("Done writing file {}", path.display());
Ok(())
}
#[tracing::instrument(skip(bytes, permit))]
pub async fn write_cached_icon<'a>(
#[tracing::instrument(skip(bytes, semaphore))]
pub async fn write_cached_icon(
icon_path: &str,
cache_dir: &Path,
bytes: Bytes,
permit: &SemaphorePermit<'a>,
semaphore: &Semaphore,
) -> crate::Result<PathBuf> {
let extension = Path::new(&icon_path).extension().and_then(OsStr::to_str);
let hash = sha1_async(bytes.clone()).await?;
@ -113,8 +142,9 @@ pub async fn write_cached_icon<'a>(
hash
});
write(&path, &bytes, permit).await?;
write(&path, &bytes, semaphore).await?;
let path = dunce::canonicalize(path)?;
Ok(path)
}

View File

@ -19,7 +19,7 @@ theseus = { path = "../../theseus" }
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.2", features = ["shell-open"] }
tauri = { version = "1.2", features = ["protocol-asset"] }
tokio = { version = "1", features = ["full"] }
thiserror = "1.0"
tokio-stream = { version = "0.1", features = ["fs"] }

View File

@ -13,9 +13,9 @@
"tauri": {
"allowlist": {
"all": false,
"shell": {
"all": false,
"open": true
"protocol": {
"asset": true,
"assetScope": ["$APPDATA/caches/icons/*"]
}
},
"bundle": {
@ -52,7 +52,7 @@
}
},
"security": {
"csp": null
"csp": "default-src 'self'; img-src 'self' asset: https://asset.localhost"
},
"updater": {
"active": false

View File

@ -1,6 +1,6 @@
<script setup>
import { watch } from 'vue'
import { RouterView, useRoute, useRouter, RouterLink } from 'vue-router'
import { ref, watch } from 'vue'
import { RouterView, RouterLink } from 'vue-router'
import {
ChevronLeftIcon,
ChevronRightIcon,
@ -13,9 +13,7 @@ import {
} from 'omorphia'
import { useTheming } from '@/store/state'
import { toggleTheme } from '@/helpers/theme'
const route = useRoute()
const router = useRouter()
import { list } from '@/helpers/profile'
const themeStore = useTheming()
@ -24,6 +22,16 @@ toggleTheme(themeStore.darkTheme)
watch(themeStore, (newState) => {
toggleTheme(newState.darkTheme)
})
const installedMods = ref(0)
list().then(
(profiles) =>
(installedMods.value = Object.values(profiles).reduce(
(acc, val) => acc + Object.keys(val.projects).length,
0
))
)
// TODO: add event when profiles update to update installed mods count
</script>
<template>
@ -47,13 +55,12 @@ watch(themeStore, (newState) => {
<div class="view">
<div class="appbar">
<section class="navigation-controls">
<ChevronLeftIcon @click="router.back()" />
<ChevronRightIcon @click="router.forward()" />
<p>{{ route.name }}</p>
<ChevronLeftIcon @click="$router.back()" />
<ChevronRightIcon @click="$router.forward()" />
<p>{{ $route.name }}</p>
</section>
<section class="mod-stats">
<p>Updating 2 mods...</p>
<p>123 mods installed</p>
<p>{{ installedMods }} mods installed</p>
</section>
</div>
<div class="router-view">
@ -74,36 +81,32 @@ watch(themeStore, (newState) => {
.router-view {
width: 100%;
height: calc(100% - 2rem);
height: 100%;
overflow: auto;
overflow-x: hidden;
margin-top: 2rem;
}
.view {
margin-left: 5rem;
width: calc(100% - 5rem);
height: calc(100%);
.appbar {
position: absolute;
display: flex;
justify-content: space-between;
align-items: center;
height: 2rem;
width: calc(100% - 5rem);
border-bottom: 1px solid rgba(64, 67, 74, 0.2);
background: var(--color-button-bg);
background: #40434a;
text-align: center;
padding: 0.5rem 1rem;
.navigation-controls {
display: inherit;
align-items: inherit;
justify-content: stretch;
width: 30%;
font-size: 0.9rem;
svg {
width: 18px;
width: 1.25rem;
height: 1.25rem;
transition: all ease-in-out 0.1s;
&:hover {
@ -130,13 +133,6 @@ watch(themeStore, (newState) => {
display: inherit;
align-items: inherit;
justify-content: flex-end;
width: 50%;
font-size: 0.8rem;
margin-right: 1rem;
p:nth-child(1) {
margin-right: 0.55rem;
}
}
}
}

View File

@ -2,11 +2,9 @@
import { RouterLink } from 'vue-router'
import { Card } from 'omorphia'
import { PlayIcon } from '@/assets/icons'
import { convertFileSrc } from '@tauri-apps/api/tauri'
const props = defineProps({
display: {
type: String,
default: '',
},
instance: {
type: Object,
default() {
@ -18,40 +16,22 @@ const props = defineProps({
<template>
<div>
<RouterLink
v-if="display === 'list'"
class="instance-list-item"
:to="`/instance/${props.instance.id}`"
>{{ props.instance.name }}</RouterLink
>
<Card
v-else-if="display === 'card'"
class="instance-card-item"
@click="$router.push(`/instance/${props.instance.id}`)"
>
<img :src="props.instance.img" alt="Trending mod card" />
<div class="project-info">
<p class="title">{{ props.instance.name }}</p>
<p class="description">{{ props.instance.version }}</p>
</div>
<div class="cta"><PlayIcon /></div>
</Card>
<RouterLink :to="`/instance/${encodeURIComponent(props.instance.path)}`">
<Card class="instance-card-item">
<img :src="convertFileSrc(props.instance.metadata.icon)" alt="Trending mod card" />
<div class="project-info">
<p class="title">{{ props.instance.metadata.name }}</p>
<p class="description">
{{ props.instance.metadata.loader }} {{ props.instance.metadata.game_version }}
</p>
</div>
<div class="cta"><PlayIcon /></div>
</Card>
</RouterLink>
</div>
</template>
<style lang="scss" scoped>
.instance-list-item {
display: inline-block;
margin: 0.25rem auto;
cursor: pointer;
transition: all ease-out 0.1s;
font-size: 0.8rem;
color: var(--color-primary);
&:hover {
text-decoration: none;
filter: brightness(150%);
}
}
.instance-card-item {
display: flex;
flex-direction: column;
@ -60,6 +40,7 @@ const props = defineProps({
cursor: pointer;
padding: 0.75rem;
transition: 0.1s ease-in-out all;
&:hover {
filter: brightness(0.85);
.cta {
@ -67,6 +48,7 @@ const props = defineProps({
bottom: 4.5rem;
}
}
.cta {
position: absolute;
display: flex;
@ -82,7 +64,7 @@ const props = defineProps({
transition: 0.3s ease-in-out bottom, 0.1s ease-in-out opacity;
cursor: pointer;
svg {
color: #fff;
color: var(--color-accent-contrast);
width: 1.5rem;
height: 1.5rem;
}
@ -101,7 +83,7 @@ const props = defineProps({
width: 100%;
.title {
color: var(--color-contrast);
max-width: 6rem;
//max-width: 10rem;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
@ -112,6 +94,7 @@ const props = defineProps({
display: inline-block;
}
.description {
color: var(--color-base);
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
@ -120,12 +103,8 @@ const props = defineProps({
font-size: 0.775rem;
line-height: 125%;
margin: 0.25rem 0 0;
text-transform: capitalize;
}
}
}
.dark-mode {
.cta > svg {
color: #000;
}
}
</style>

View File

@ -6,11 +6,11 @@
import { invoke } from '@tauri-apps/api/tauri'
// Installs pack from a version ID
export async function install(version_id) {
return await invoke('pack_install_version_id', version_id)
export async function install(versionId) {
return await invoke('pack_install_version_id', { versionId })
}
// Installs pack from a path
export async function install_from_file(path) {
return await invoke('pack_install_file', path)
return await invoke('pack_install_file', { path })
}

View File

@ -35,12 +35,12 @@ export async function list() {
// Run Minecraft using a pathed profile
// Returns PID of child
export async function run(path, credentials) {
return await invoke('profile_run', { path, credentials })
export async function run(path) {
return await invoke('profile_run', { path })
}
// Run Minecraft using a pathed profile
// Waits for end
export async function run_wait(path, credentials) {
return await invoke('profile_run_wait', { path, credentials })
export async function run_wait(path) {
return await invoke('profile_run_wait', { path })
}

View File

@ -4,7 +4,13 @@ import App from '@/App.vue'
import { createPinia } from 'pinia'
import '../node_modules/omorphia/dist/style.css'
import '@/assets/stylesheets/global.scss'
import FloatingVue from 'floating-vue'
import { initialize_state } from '@/helpers/state'
const pinia = createPinia()
createApp(App).use(router).use(pinia).mount('#app')
initialize_state()
.then(() => {
createApp(App).use(router).use(pinia).use(FloatingVue).mount('#app')
})
.catch((err) => console.error(err))

View File

@ -1,5 +1,5 @@
<script setup>
import { ref, computed } from 'vue'
import { ref } from 'vue'
import { ofetch } from 'ofetch'
import {
Pagination,
@ -13,39 +13,35 @@ import {
Card,
ClientIcon,
ServerIcon,
AnimatedLogo,
} from 'omorphia'
import Multiselect from 'vue-multiselect'
import { useSearch } from '@/store/state'
import { get_categories, get_loaders, get_game_versions } from '@/helpers/tags'
// Pull search store
const searchStore = useSearch()
const selectedVersions = ref([])
const showSnapshots = ref(false)
const loading = ref(true)
// Sets the clear button's disabled attr
const isClearDisabled = computed({
get() {
if (searchStore.facets.length > 0) return false
if (searchStore.orFacets.length > 0) return false
const [categories, loaders, availableGameVersions] = await Promise.all([
get_categories(),
get_loaders(),
get_game_versions(),
])
if (searchStore.environments.server === true || searchStore.environments.client === true)
return false
if (searchStore.openSource === true) return false
if (selectedVersions.value.length > 0) return false
return true
},
})
const getSearchResults = async (shouldLoad = false) => {
const queryString = searchStore.getQueryString()
if (shouldLoad === true) {
loading.value = true
}
const response = await ofetch(`https://api.modrinth.com/v2/search${queryString}`)
loading.value = false
searchStore.setSearchResults(response)
}
const categories = await get_categories()
const loaders = await get_loaders()
const availableGameVersions = await get_game_versions()
getSearchResults(true)
/**
* Adds or removes facets from state
* @param {String} facet The facet to commit to state
*/
const toggleFacet = async (facet) => {
const index = searchStore.facets.indexOf(facet)
@ -55,10 +51,6 @@ const toggleFacet = async (facet) => {
await getSearchResults()
}
/**
* Adds or removes orFacets from state
* @param {String} orFacet The orFacet to commit to state
*/
const toggleOrFacet = async (orFacet) => {
const index = searchStore.orFacets.indexOf(orFacet)
@ -68,68 +60,15 @@ const toggleOrFacet = async (orFacet) => {
await getSearchResults()
}
/**
* Makes the API request to labrinth
*/
const getSearchResults = async () => {
const queryString = searchStore.getQueryString()
const response = await ofetch(`https://api.modrinth.com/v2/search${queryString}`)
searchStore.setSearchResults(response)
}
await getSearchResults()
/**
* For when user enters input in search bar
*/
const refreshSearch = async () => {
await getSearchResults()
}
/**
* For when the user changes the Sort dropdown
* @param {Object} e Event param to see selected option
*/
const handleSort = async (e) => {
searchStore.filter = e.option
await getSearchResults()
}
/**
* For when user changes Limit dropdown
* @param {Object} e Event param to see selected option
*/
const handleLimit = async (e) => {
searchStore.limit = e.option
await getSearchResults()
}
/**
* For when user pages results
* @param {Number} page The new page to display
*/
const switchPage = async (page) => {
searchStore.currentPage = parseInt(page)
if (page === 1) searchStore.offset = 0
else searchStore.offset = searchStore.currentPage * 10 - 10
else searchStore.offset = (searchStore.currentPage - 1) * searchStore.limit
await getSearchResults()
}
/**
* For when a user interacts with version filters
*/
const handleVersionSelect = async () => {
searchStore.activeVersions = selectedVersions.value.map((ver) => ver)
await getSearchResults()
}
/**
* For when user resets all filters
*/
const handleReset = async () => {
searchStore.resetFilters()
selectedVersions.value = []
isClearDisabled.value = true
await getSearchResults()
}
</script>
@ -137,7 +76,19 @@ const handleReset = async () => {
<template>
<div class="search-container">
<aside class="filter-panel">
<Button role="button" :disabled="isClearDisabled" @click="handleReset"
<Button
role="button"
:disabled="
!(
searchStore.facets.length > 0 ||
searchStore.orFacets.length > 0 ||
searchStore.environments.server === true ||
searchStore.environments.client === true ||
searchStore.openSource === true ||
searchStore.activeVersions.length > 0
)
"
@click="handleReset"
><ClearIcon />Clear Filters</Button
>
<div class="categories">
@ -177,18 +128,18 @@ const handleReset = async () => {
<SearchFilter
v-model="searchStore.environments.client"
display-name="Client"
:facet-name="client"
facet-name="client"
class="filter-checkbox"
@click="refreshSearch"
@click="getSearchResults"
>
<ClientIcon aria-hidden="true" />
</SearchFilter>
<SearchFilter
v-model="searchStore.environments.server"
display-name="Server"
:facet-name="server"
facet-name="server"
class="filter-checkbox"
@click="refreshSearch"
@click="getSearchResults"
>
<ServerIcon aria-hidden="true" />
</SearchFilter>
@ -197,7 +148,7 @@ const handleReset = async () => {
<h2>Minecraft versions</h2>
<Checkbox v-model="showSnapshots" class="filter-checkbox">Show snapshots</Checkbox>
<multiselect
v-model="selectedVersions"
v-model="searchStore.activeVersions"
:options="
showSnapshots
? availableGameVersions.map((x) => x.version)
@ -211,14 +162,17 @@ const handleReset = async () => {
:close-on-select="false"
:clear-search-on-select="false"
:show-labels="false"
:selectable="() => selectedVersions.length <= 6"
placeholder="Choose versions..."
@update:model-value="handleVersionSelect"
@update:model-value="getSearchResults"
/>
</div>
<div class="open-source">
<h2>Open source</h2>
<Checkbox v-model="searchStore.openSource" class="filter-checkbox" @click="refreshSearch">
<Checkbox
v-model="searchStore.openSource"
class="filter-checkbox"
@click="getSearchResults"
>
Open source
</Checkbox>
</div>
@ -231,12 +185,13 @@ const handleReset = async () => {
<input
v-model="searchStore.searchInput"
type="text"
placeholder="Search.."
@input="refreshSearch"
placeholder="Search modpacks..."
@input="getSearchResults"
/>
</div>
<span>Sort by</span>
<DropdownSelect
v-model="searchStore.filter"
name="Sort dropdown"
:options="[
'Relevance',
@ -245,19 +200,18 @@ const handleReset = async () => {
'Recently published',
'Recently updated',
]"
:default-value="searchStore.filter"
:model-value="searchStore.filter"
class="sort-dropdown"
@change="handleSort"
@change="getSearchResults"
/>
<span>Show per page</span>
<DropdownSelect
v-model="searchStore.limit"
name="Limit dropdown"
:options="['5', '10', '15', '20', '50', '100']"
:options="[5, 10, 15, 20, 50, 100]"
:default-value="searchStore.limit.toString()"
:model-value="searchStore.limit.toString()"
class="limit-dropdown"
@change="handleLimit"
@change="getSearchResults"
/>
</div>
</Card>
@ -266,7 +220,8 @@ const handleReset = async () => {
:count="searchStore.pageCount"
@switch-page="switchPage"
/>
<section class="project-list display-mode--list instance-results" role="list">
<AnimatedLogo v-if="loading" class="loading" />
<section v-else class="project-list display-mode--list instance-results" role="list">
<ProjectCard
v-for="result in searchStore.searchResults"
:id="`${result?.project_id}/`"
@ -396,18 +351,9 @@ const handleReset = async () => {
margin: 0 1rem 0 17rem;
width: 100%;
.instance-project-item {
width: 100%;
height: auto;
cursor: pointer;
}
.result-project-item {
a {
&:hover {
text-decoration: none !important;
}
}
.loading {
margin: 2rem;
text-align: center;
}
}
}

View File

@ -1,22 +1,17 @@
<script setup>
import { useInstances, useNews } from '@/store/state'
import RowDisplay from '@/components/RowDisplay.vue'
import { shallowRef } from 'vue'
import { list } from '@/helpers/profile.js'
const instanceStore = useInstances()
const newsStore = useNews()
instanceStore.fetchInstances()
newsStore.fetchNews()
// Remove once state is populated with real data
const recentInstances = instanceStore.instances.slice(0, 4)
const popularInstances = instanceStore.instances.filter((i) => i.downloads > 50 || i.trending)
const profiles = await list()
const recentInstances = shallowRef(Object.values(profiles))
</script>
<template>
<div class="page-container">
<RowDisplay label="Jump back in" :instances="recentInstances" :can-paginate="false" />
<RowDisplay label="Popular packs" :instances="popularInstances" :can-paginate="true" />
<RowDisplay label="News & updates" :news="newsStore.news" :can-paginate="true" />
<RowDisplay label="Popular packs" :instances="recentInstances" :can-paginate="true" />
<RowDisplay label="Test" :instances="recentInstances" :can-paginate="true" />
</div>
</template>

View File

@ -1,14 +1,15 @@
<script setup>
import { useInstances } from '@/store/state'
import GridDisplay from '@/components/GridDisplay.vue'
import { shallowRef } from 'vue'
import { list } from '@/helpers/profile.js'
const instances = useInstances()
instances.fetchInstances()
const profiles = await list()
const instances = shallowRef(Object.values(profiles))
</script>
<template>
<div>
<GridDisplay label="Instances" :instances="instances.instances" />
<GridDisplay label="Modpacks" :instances="instances.instances" />
<GridDisplay label="Instances" :instances="instances" />
<GridDisplay label="Modpacks" :instances="instances" />
</div>
</template>

View File

@ -2,13 +2,15 @@
<div class="instance-container">
<div class="side-cards">
<Card class="instance-card">
<Avatar size="lg" :src="getInstance(instanceStore).img" />
<Avatar size="lg" :src="convertFileSrc(instance.metadata.icon)" />
<div class="instance-info">
<h2 class="name">{{ getInstance(instanceStore).name }}</h2>
Fabric {{ getInstance(instanceStore).version }}
<h2 class="name">{{ instance.metadata.name }}</h2>
<span class="metadata"
>{{ instance.metadata.loader }} {{ instance.metadata.game_version }}</span
>
</div>
<span class="button-group">
<Button color="primary" class="instance-button">
<Button color="primary" class="instance-button" @click="run($route.params.id)">
<PlayIcon />
Play
</Button>
@ -18,15 +20,15 @@
</span>
</Card>
<div class="pages-list">
<RouterLink :to="`/instance/${$route.params.id}/`" class="btn">
<RouterLink :to="`/instance/${encodeURIComponent($route.params.id)}/`" class="btn">
<BoxIcon />
Mods
</RouterLink>
<RouterLink :to="`/instance/${$route.params.id}/options`" class="btn">
<RouterLink :to="`/instance/${encodeURIComponent($route.params.id)}/options`" class="btn">
<SettingsIcon />
Options
</RouterLink>
<RouterLink :to="`/instance/${$route.params.id}/logs`" class="btn">
<RouterLink :to="`/instance/${encodeURIComponent($route.params.id)}/logs`" class="btn">
<FileIcon />
Logs
</RouterLink>
@ -34,26 +36,20 @@
</div>
<div class="content">
<Promotion />
<router-view />
<router-view :instance="instance" />
</div>
</div>
</template>
<script setup>
import { BoxIcon, SettingsIcon, FileIcon, Button, Avatar, Card, Promotion } from 'omorphia'
import { PlayIcon, OpenFolderIcon } from '@/assets/icons'
import { useInstances } from '@/store/state'
import { get, run } from '@/helpers/profile'
import { useRoute } from 'vue-router'
import { shallowRef } from 'vue'
import { convertFileSrc } from '@tauri-apps/api/tauri'
const instanceStore = useInstances()
instanceStore.fetchInstances()
</script>
<script>
export default {
methods: {
getInstance(instanceStore) {
return instanceStore.instances.find((i) => i.id === parseInt(this.$route.params.id))
},
},
}
const route = useRoute()
const instance = shallowRef(await get(route.params.id))
</script>
<style scoped lang="scss">
@ -101,6 +97,10 @@ Button {
color: var(--color-contrast);
}
.metadata {
text-transform: capitalize;
}
.instance-container {
display: flex;
flex-direction: row;

View File

@ -10,6 +10,7 @@
Sort By
<DropdownSelect
v-model="sortFilter"
name="sort-by"
:options="['Name', 'Version', 'Author']"
default-value="Name"
class="dropdown"
@ -33,9 +34,9 @@
<div class="table-cell table-text">Author</div>
<div class="table-cell table-text">Actions</div>
</div>
<div v-for="mod in search" :key="mod.name" class="table-row">
<div v-for="mod in search" :key="mod.file_name" class="table-row">
<div class="table-cell table-text">
<Button v-if="mod.outdated" icon-only>
<Button v-if="true" icon-only>
<UpdatedIcon />
</Button>
<Button v-else disabled icon-only>
@ -43,10 +44,14 @@
</Button>
</div>
<div class="table-cell table-text name-cell">
<router-link :to="`/project/${mod.slug}/`" class="mod-text">
<router-link v-if="mod.slug" :to="`/project/${mod.slug}/`" class="mod-text">
<Avatar :src="mod.icon" />
{{ mod.name }}
</router-link>
<div v-else class="mod-text">
<Avatar :src="mod.icon" />
{{ mod.name }}
</div>
</div>
<div class="table-cell table-text">{{ mod.version }}</div>
<div class="table-cell table-text">{{ mod.author }}</div>
@ -54,118 +59,17 @@
<Button icon-only>
<TrashIcon />
</Button>
<input id="switch-1" type="checkbox" class="switch stylized-toggle" checked />
<input
id="switch-1"
type="checkbox"
class="switch stylized-toggle"
:checked="mod.disabled"
/>
</div>
</div>
</div>
</Card>
</template>
<script>
export default {
name: 'Mods',
data() {
return {
searchFilter: '',
sortFilter: '',
mods: [
{
name: 'Fabric API',
slug: 'fabric-api',
icon: 'https://cdn.modrinth.com/data/P7dR8mSH/icon.png',
version: '0.76.0+1.19.4',
author: 'modmuss50',
description:
'Lightweight and modular API providing common hooks and intercompatibility measures utilized by mods using the Fabric toolchain.',
outdated: true,
},
{
name: 'Spirit',
slug: 'spirit',
icon: 'https://cdn.modrinth.com/data/b1LdOZlE/465598dc5d89f67fb8f8de6def21240fa35e3a54.png',
version: '2.2.4',
author: 'CodexAdrian',
description: 'Create your own configurable mob spawner!',
outdated: true,
},
{
name: 'Botarium',
slug: 'botarium',
icon: 'https://cdn.modrinth.com/data/2u6LRnMa/98b286b0d541ad4f9409e0af3df82ad09403f179.gif',
version: '2.0.5',
author: 'CodexAdrian',
description:
'A crossplatform API for devs that makes transfer and storage of items, fluids and energy easier, as well as some other helpful things',
outdated: true,
},
{
name: 'Tempad',
slug: 'tempad',
icon: 'https://cdn.modrinth.com/data/gKNwt7xu/icon.gif',
version: '2.2.4',
author: 'CodexAdrian',
description: 'Create a portal to anywhere from anywhere',
outdated: false,
},
{
name: 'Sodium',
slug: 'sodium',
icon: 'https://cdn.modrinth.com/data/AANobbMI/icon.png',
version: '0.4.10',
author: 'jellysquid3',
description: 'Modern rendering engine and client-side optimization mod for Minecraft',
outdated: false,
},
],
}
},
computed: {
search() {
const filtered = this.mods.filter((mod) => {
return mod.name.toLowerCase().includes(this.searchFilter.toLowerCase())
})
return this.updateSort(filtered, this.sortFilter)
},
},
methods: {
updateSort(projects, sort) {
switch (sort) {
case 'Version':
return projects.slice().sort((a, b) => {
if (a.version < b.version) {
return -1
}
if (a.version > b.version) {
return 1
}
return 0
})
case 'Author':
return projects.slice().sort((a, b) => {
if (a.author < b.author) {
return -1
}
if (a.author > b.author) {
return 1
}
return 0
})
default:
return projects.slice().sort((a, b) => {
if (a.name < b.name) {
return -1
}
if (a.name > b.name) {
return 1
}
return 0
})
}
},
},
}
</script>
<script setup>
import {
Avatar,
@ -178,6 +82,97 @@ import {
UpdatedIcon,
DropdownSelect,
} from 'omorphia'
import { computed, ref, shallowRef } from 'vue'
import { convertFileSrc } from '@tauri-apps/api/tauri'
const props = defineProps({
instance: {
type: Object,
default() {
return {}
},
},
})
const projects = shallowRef([])
for (const project of Object.values(props.instance.projects)) {
if (project.metadata.type === 'modrinth') {
let owner = project.metadata.members.find((x) => x.role === 'Owner')
projects.value.push({
name: project.metadata.project.title,
slug: project.metadata.project.slug,
author: owner ? owner.user.username : null,
version: project.metadata.version.version_number,
file_name: project.file_name,
icon: project.metadata.project.icon_url,
disabled: project.disabled,
})
} else if (project.metadata.type === 'inferred') {
projects.value.push({
name: project.metadata.title ?? project.file_name,
author: project.metadata.authors[0],
version: project.metadata.version,
file_name: project.file_name,
icon: project.metadata.icon ? convertFileSrc(project.metadata.icon) : null,
disabled: project.disabled,
})
} else {
projects.value.push({
name: project.file_name,
author: '',
version: null,
file_name: project.file_name,
icon: null,
disabled: project.disabled,
})
}
}
const searchFilter = ref('')
const sortFilter = ref('')
const search = computed(() => {
const filtered = projects.value.filter((mod) => {
return mod.name.toLowerCase().includes(searchFilter.value.toLowerCase())
})
return updateSort(filtered, sortFilter.value)
})
function updateSort(projects, sort) {
switch (sort) {
case 'Version':
return projects.slice().sort((a, b) => {
if (a.version < b.version) {
return -1
}
if (a.version > b.version) {
return 1
}
return 0
})
case 'Author':
return projects.slice().sort((a, b) => {
if (a.author < b.author) {
return -1
}
if (a.author > b.author) {
return 1
}
return 0
})
default:
return projects.slice().sort((a, b) => {
if (a.name < b.name) {
return -1
}
if (a.name > b.name) {
return 1
}
return 0
})
}
}
</script>
<style scoped lang="scss">

View File

@ -22,7 +22,6 @@
]"
>
<EnvironmentIndicator
:type-only="moderation"
:client-side="data.client_side"
:server-side="data.server_side"
:type="data.project_type"
@ -30,7 +29,7 @@
</Categories>
<hr class="card-divider" />
<div class="button-group">
<Button color="primary" class="instance-button">
<Button color="primary" class="instance-button" @click="install">
<DownloadIcon />
Install
</Button>
@ -209,6 +208,7 @@ import {
OpenCollectiveIcon,
} from '@/assets/external'
import { get_categories, get_loaders } from '@/helpers/tags'
import { install as pack_install } from '@/helpers/pack'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import { ofetch } from 'ofetch'
@ -230,11 +230,20 @@ const [data, versions, members, dependencies] = await Promise.all([
watch(
() => route.params.id,
() => {
router.go()
if (route.params.id) router.go()
}
)
dayjs.extend(relativeTime)
async function install() {
if (data.value.project_type === 'modpack') {
let id = await pack_install(versions.value[0].id)
let router = useRouter()
await router.push({ path: `/instance/${encodeURIComponent(id)}` })
}
}
</script>
<style scoped lang="scss">

View File

@ -1,115 +0,0 @@
import { defineStore } from 'pinia'
export const useInstances = defineStore('instanceStore', {
state: () => ({
instances: [],
}),
actions: {
fetchInstances() {
// Fetch from Tauri backend. We will repurpose this to get current instances, news, and popular packs. This action is distinct from the search action
const instances = [
{
id: 1,
name: 'Fabulously Optimized',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
version: '1.18.1',
downloads: 10,
trending: true,
img: 'https://cdn.modrinth.com/user/MpxzqsyW/eb0038489a55e7e7a188a5b50462f0b10dfc1613.jpeg',
},
{
id: 2,
name: 'New Caves',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
version: '1.18 ',
downloads: 8,
trending: true,
img: 'https://cdn.modrinth.com/data/ssUbhMkL/icon.png',
},
{
id: 3,
name: 'All the Mods 6',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
version: '1.16.5',
downloads: 4,
trending: true,
img: 'https://avatars1.githubusercontent.com/u/6166773?v=4',
},
{
id: 4,
name: 'Bees',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
version: '1.15.2',
downloads: 9,
trending: false,
img: 'https://cdn.modrinth.com/data/ssUbhMkL/icon.png',
},
{
id: 5,
name: 'SkyFactory 4',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
version: '1.12.2',
downloads: 1000,
trending: false,
img: 'https://cdn.modrinth.com/user/MpxzqsyW/eb0038489a55e7e7a188a5b50462f0b10dfc1613.jpeg',
},
{
id: 6,
name: 'RLCraft',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
version: '1.12.2',
downloads: 10000,
trending: false,
img: 'https://avatars1.githubusercontent.com/u/6166773?v=4',
},
{
id: 7,
name: 'Regrowth',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
version: '1.7.10',
downloads: 1000,
trending: false,
img: 'https://cdn.modrinth.com/data/ssUbhMkL/icon.png',
},
{
id: 8,
name: 'Birds',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
version: '1.15.2',
downloads: 9,
trending: false,
img: 'https://avatars.githubusercontent.com/u/83074853?v=4',
},
{
id: 9,
name: 'Dogs',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
version: '1.15.2',
downloads: 9,
trending: false,
img: 'https://cdn.modrinth.com/user/MpxzqsyW/eb0038489a55e7e7a188a5b50462f0b10dfc1613.jpeg',
},
{
id: 10,
name: 'Cats',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
version: '1.15.2',
downloads: 9,
trending: false,
img: 'https://cdn.modrinth.com/data/ssUbhMkL/icon.png',
},
{
id: 11,
name: 'Rabbits',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
version: '1.15.2',
downloads: 9,
trending: false,
img: 'https://avatars1.githubusercontent.com/u/6166773?v=4',
},
]
this.instances = [...instances]
},
},
})

View File

@ -1,35 +0,0 @@
import { defineStore } from 'pinia'
export const useNews = defineStore('newsStore', {
state: () => ({ news: [] }),
actions: {
fetchNews() {
// Fetch from backend.
const news = [
{
id: 1,
headline: 'Caves & Cliffs Update: Part II Dev Q&A',
blurb: 'Your questions, answered!',
source: 'From Minecraft.Net',
img: 'https://avatars1.githubusercontent.com/u/6166773?v=4',
},
{
id: 2,
headline: 'Project of the WeeK: Gobblygook',
blurb: 'Your questions, answered!',
source: 'Modrinth Blog',
img: 'https://avatars.githubusercontent.com/t/3923733?s=280&v=4',
},
{
id: 3,
headline: 'Oreo makes a launcher',
blurb: 'What did it take?',
source: 'Modrinth Blog',
img: 'https://avatars.githubusercontent.com/u/30800863?v=4',
},
]
this.news = [...news]
},
},
})

View File

@ -36,6 +36,7 @@ export const useSearch = defineStore('searchStore', {
formattedAndFacets = formattedAndFacets.slice(0, formattedAndFacets.length - 1)
formattedAndFacets += ''
// TODO: fix me - ask jai
// If orFacets are present, start building formatted orFacet filter
let formattedOrFacets = ''
if (this.orFacets.length > 0 || this.activeVersions.length > 0) {
@ -91,18 +92,6 @@ export const useSearch = defineStore('searchStore', {
this.offset = response.offset
this.pageCount = Math.ceil(this.totalHits / this.limit)
},
toggleCategory(cat) {
this.categories[cat] = !this.categories[cat]
},
toggleLoader(loader) {
this.loaders[loader] = !this.loaders[loader]
},
toggleEnv(env) {
this.environments[env] = !this.environments[env]
},
setVersions(versions) {
this.activeVersions = versions
},
resetFilters() {
this.facets = []
this.orFacets = []

View File

@ -1,6 +1,4 @@
import { useInstances } from './instances'
import { useSearch } from './search'
import { useTheming } from './theme'
import { useNews } from './news'
export { useInstances, useSearch, useTheming, useNews }
export { useSearch, useTheming }

View File

@ -449,20 +449,6 @@ argparse@^2.0.1:
resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38"
integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==
asynckit@^0.4.0:
version "0.4.0"
resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
integrity sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==
axios@^1.3.4:
version "1.3.4"
resolved "https://registry.yarnpkg.com/axios/-/axios-1.3.4.tgz#f5760cefd9cfb51fd2481acf88c05f67c4523024"
integrity sha512-toYm+Bsyl6VC5wSkfkbbNB6ROv7KY93PEBBL6xyDczaIHasAiv4wPqQ/c4RjoQzipxRD2W5g21cOqQulZ7rHwQ==
dependencies:
follow-redirects "^1.15.0"
form-data "^4.0.0"
proxy-from-env "^1.1.0"
balanced-match@^1.0.0:
version "1.0.2"
resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee"
@ -533,13 +519,6 @@ color-name@~1.1.4:
resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2"
integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==
combined-stream@^1.0.8:
version "1.0.8"
resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f"
integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==
dependencies:
delayed-stream "~1.0.0"
commander@^2.20.3:
version "2.20.3"
resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33"
@ -635,11 +614,6 @@ deep-is@^0.1.3:
resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.4.tgz#a6f2dce612fadd2ef1f519b73551f17e85199831"
integrity sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==
delayed-stream@~1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619"
integrity sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==
destr@^1.2.2:
version "1.2.2"
resolved "https://registry.yarnpkg.com/destr/-/destr-1.2.2.tgz#7ba9befcafb645a50e76b260449c63927b51e22f"
@ -905,20 +879,6 @@ floating-vue@^2.0.0-beta.20:
"@floating-ui/dom" "^0.1.10"
vue-resize "^2.0.0-alpha.1"
follow-redirects@^1.15.0:
version "1.15.2"
resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.2.tgz#b460864144ba63f2681096f274c4e57026da2c13"
integrity sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==
form-data@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.0.tgz#93919daeaf361ee529584b9b31664dc12c9fa452"
integrity sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==
dependencies:
asynckit "^0.4.0"
combined-stream "^1.0.8"
mime-types "^2.1.12"
fs.realpath@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"
@ -1160,18 +1120,6 @@ mdurl@^1.0.1:
resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-1.0.1.tgz#fe85b2ec75a59037f2adfec100fd6c601761152e"
integrity sha512-/sKlQJCBYVY9Ers9hqzKou4H6V5UWc/M59TH2dvkt+84itfnq7uFOMLpOiOS4ujvHP4etln18fmIxA5R5fll0g==
mime-db@1.52.0:
version "1.52.0"
resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70"
integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==
mime-types@^2.1.12:
version "2.1.35"
resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.35.tgz#381a871b62a734450660ae3deee44813f70d959a"
integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==
dependencies:
mime-db "1.52.0"
minimatch@^3.0.5, minimatch@^3.1.1, minimatch@^3.1.2:
version "3.1.2"
resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b"
@ -1339,11 +1287,6 @@ prettier@^2.8.7:
resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.8.7.tgz#bb79fc8729308549d28fe3a98fce73d2c0656450"
integrity sha512-yPngTo3aXUUmyuTjeTUT75txrf+aMh9FiD7q9ZE/i6r0bPb22g4FsE6Y338PQX1bmfy08i9QQCB7/rcUAVntfw==
proxy-from-env@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2"
integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==
punycode@^2.1.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.3.0.tgz#f67fa67c94da8f4d0cfff981aee4118064199b8f"

View File

@ -31,7 +31,7 @@ async fn main() -> theseus::Result<()> {
// Initialize state
let st = State::get().await?;
st.settings.write().await.max_concurrent_downloads = 1;
st.settings.write().await.max_concurrent_downloads = 10;
// Clear profiles
println!("Clearing profiles.");
@ -64,8 +64,6 @@ async fn main() -> theseus::Result<()> {
.await?;
State::sync().await?;
// Attempt to run game
if auth::users().await?.len() == 0 {
println!("No users found, authenticating.");