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

View File

@@ -137,7 +137,15 @@ pub async fn profile_create(
let path = canonicalize(&path)?; let path = canonicalize(&path)?;
let mut profile = Profile::new(name, game_version, path.clone()).await?; let mut profile = Profile::new(name, game_version, path.clone()).await?;
if let Some(ref icon) = icon { 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 { if let Some((loader_version, loader)) = loader {
profile.metadata.loader = loader; profile.metadata.loader = loader;

View File

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

View File

@@ -21,7 +21,7 @@ impl DirectoryInfo {
// Config directory // Config directory
let config_dir = Self::env_path("THESEUS_CONFIG_DIR") 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( .ok_or(crate::ErrorKind::FSError(
"Could not find valid config dir".to_string(), "Could not find valid config dir".to_string(),
))?; ))?;

View File

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

View File

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

View File

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

View File

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

View File

@@ -19,7 +19,7 @@ theseus = { path = "../../theseus" }
serde_json = "1.0" serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] } 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"] } tokio = { version = "1", features = ["full"] }
thiserror = "1.0" thiserror = "1.0"
tokio-stream = { version = "0.1", features = ["fs"] } tokio-stream = { version = "0.1", features = ["fs"] }

View File

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

View File

@@ -1,6 +1,6 @@
<script setup> <script setup>
import { watch } from 'vue' import { ref, watch } from 'vue'
import { RouterView, useRoute, useRouter, RouterLink } from 'vue-router' import { RouterView, RouterLink } from 'vue-router'
import { import {
ChevronLeftIcon, ChevronLeftIcon,
ChevronRightIcon, ChevronRightIcon,
@@ -13,9 +13,7 @@ import {
} from 'omorphia' } from 'omorphia'
import { useTheming } from '@/store/state' import { useTheming } from '@/store/state'
import { toggleTheme } from '@/helpers/theme' import { toggleTheme } from '@/helpers/theme'
import { list } from '@/helpers/profile'
const route = useRoute()
const router = useRouter()
const themeStore = useTheming() const themeStore = useTheming()
@@ -24,6 +22,16 @@ toggleTheme(themeStore.darkTheme)
watch(themeStore, (newState) => { watch(themeStore, (newState) => {
toggleTheme(newState.darkTheme) 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> </script>
<template> <template>
@@ -47,13 +55,12 @@ watch(themeStore, (newState) => {
<div class="view"> <div class="view">
<div class="appbar"> <div class="appbar">
<section class="navigation-controls"> <section class="navigation-controls">
<ChevronLeftIcon @click="router.back()" /> <ChevronLeftIcon @click="$router.back()" />
<ChevronRightIcon @click="router.forward()" /> <ChevronRightIcon @click="$router.forward()" />
<p>{{ route.name }}</p> <p>{{ $route.name }}</p>
</section> </section>
<section class="mod-stats"> <section class="mod-stats">
<p>Updating 2 mods...</p> <p>{{ installedMods }} mods installed</p>
<p>123 mods installed</p>
</section> </section>
</div> </div>
<div class="router-view"> <div class="router-view">
@@ -74,36 +81,32 @@ watch(themeStore, (newState) => {
.router-view { .router-view {
width: 100%; width: 100%;
height: calc(100% - 2rem); height: 100%;
overflow: auto; overflow: auto;
overflow-x: hidden; overflow-x: hidden;
margin-top: 2rem;
} }
.view { .view {
margin-left: 5rem; margin-left: 5rem;
width: calc(100% - 5rem); width: calc(100% - 5rem);
height: calc(100%); height: calc(100%);
.appbar { .appbar {
position: absolute;
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
height: 2rem; background: #40434a;
width: calc(100% - 5rem);
border-bottom: 1px solid rgba(64, 67, 74, 0.2);
background: var(--color-button-bg);
text-align: center; text-align: center;
padding: 0.5rem 1rem;
.navigation-controls { .navigation-controls {
display: inherit; display: inherit;
align-items: inherit; align-items: inherit;
justify-content: stretch; justify-content: stretch;
width: 30%;
font-size: 0.9rem;
svg { svg {
width: 18px; width: 1.25rem;
height: 1.25rem;
transition: all ease-in-out 0.1s; transition: all ease-in-out 0.1s;
&:hover { &:hover {
@@ -130,13 +133,6 @@ watch(themeStore, (newState) => {
display: inherit; display: inherit;
align-items: inherit; align-items: inherit;
justify-content: flex-end; 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 { RouterLink } from 'vue-router'
import { Card } from 'omorphia' import { Card } from 'omorphia'
import { PlayIcon } from '@/assets/icons' import { PlayIcon } from '@/assets/icons'
import { convertFileSrc } from '@tauri-apps/api/tauri'
const props = defineProps({ const props = defineProps({
display: {
type: String,
default: '',
},
instance: { instance: {
type: Object, type: Object,
default() { default() {
@@ -18,40 +16,22 @@ const props = defineProps({
<template> <template>
<div> <div>
<RouterLink <RouterLink :to="`/instance/${encodeURIComponent(props.instance.path)}`">
v-if="display === 'list'" <Card class="instance-card-item">
class="instance-list-item" <img :src="convertFileSrc(props.instance.metadata.icon)" alt="Trending mod card" />
:to="`/instance/${props.instance.id}`" <div class="project-info">
>{{ props.instance.name }}</RouterLink <p class="title">{{ props.instance.metadata.name }}</p>
> <p class="description">
<Card {{ props.instance.metadata.loader }} {{ props.instance.metadata.game_version }}
v-else-if="display === 'card'" </p>
class="instance-card-item" </div>
@click="$router.push(`/instance/${props.instance.id}`)" <div class="cta"><PlayIcon /></div>
> </Card>
<img :src="props.instance.img" alt="Trending mod card" /> </RouterLink>
<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>
</div> </div>
</template> </template>
<style lang="scss" scoped> <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 { .instance-card-item {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -60,6 +40,7 @@ const props = defineProps({
cursor: pointer; cursor: pointer;
padding: 0.75rem; padding: 0.75rem;
transition: 0.1s ease-in-out all; transition: 0.1s ease-in-out all;
&:hover { &:hover {
filter: brightness(0.85); filter: brightness(0.85);
.cta { .cta {
@@ -67,6 +48,7 @@ const props = defineProps({
bottom: 4.5rem; bottom: 4.5rem;
} }
} }
.cta { .cta {
position: absolute; position: absolute;
display: flex; display: flex;
@@ -82,7 +64,7 @@ const props = defineProps({
transition: 0.3s ease-in-out bottom, 0.1s ease-in-out opacity; transition: 0.3s ease-in-out bottom, 0.1s ease-in-out opacity;
cursor: pointer; cursor: pointer;
svg { svg {
color: #fff; color: var(--color-accent-contrast);
width: 1.5rem; width: 1.5rem;
height: 1.5rem; height: 1.5rem;
} }
@@ -101,7 +83,7 @@ const props = defineProps({
width: 100%; width: 100%;
.title { .title {
color: var(--color-contrast); color: var(--color-contrast);
max-width: 6rem; //max-width: 10rem;
overflow: hidden; overflow: hidden;
white-space: nowrap; white-space: nowrap;
text-overflow: ellipsis; text-overflow: ellipsis;
@@ -112,6 +94,7 @@ const props = defineProps({
display: inline-block; display: inline-block;
} }
.description { .description {
color: var(--color-base);
display: -webkit-box; display: -webkit-box;
-webkit-line-clamp: 2; -webkit-line-clamp: 2;
-webkit-box-orient: vertical; -webkit-box-orient: vertical;
@@ -120,12 +103,8 @@ const props = defineProps({
font-size: 0.775rem; font-size: 0.775rem;
line-height: 125%; line-height: 125%;
margin: 0.25rem 0 0; margin: 0.25rem 0 0;
text-transform: capitalize;
} }
} }
} }
.dark-mode {
.cta > svg {
color: #000;
}
}
</style> </style>

View File

@@ -6,11 +6,11 @@
import { invoke } from '@tauri-apps/api/tauri' import { invoke } from '@tauri-apps/api/tauri'
// Installs pack from a version ID // Installs pack from a version ID
export async function install(version_id) { export async function install(versionId) {
return await invoke('pack_install_version_id', version_id) return await invoke('pack_install_version_id', { versionId })
} }
// Installs pack from a path // Installs pack from a path
export async function install_from_file(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 // Run Minecraft using a pathed profile
// Returns PID of child // Returns PID of child
export async function run(path, credentials) { export async function run(path) {
return await invoke('profile_run', { path, credentials }) return await invoke('profile_run', { path })
} }
// Run Minecraft using a pathed profile // Run Minecraft using a pathed profile
// Waits for end // Waits for end
export async function run_wait(path, credentials) { export async function run_wait(path) {
return await invoke('profile_run_wait', { path, credentials }) return await invoke('profile_run_wait', { path })
} }

View File

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

View File

@@ -1,22 +1,17 @@
<script setup> <script setup>
import { useInstances, useNews } from '@/store/state'
import RowDisplay from '@/components/RowDisplay.vue' import RowDisplay from '@/components/RowDisplay.vue'
import { shallowRef } from 'vue'
import { list } from '@/helpers/profile.js'
const instanceStore = useInstances() const profiles = await list()
const newsStore = useNews() const recentInstances = shallowRef(Object.values(profiles))
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)
</script> </script>
<template> <template>
<div class="page-container"> <div class="page-container">
<RowDisplay label="Jump back in" :instances="recentInstances" :can-paginate="false" /> <RowDisplay label="Jump back in" :instances="recentInstances" :can-paginate="false" />
<RowDisplay label="Popular packs" :instances="popularInstances" :can-paginate="true" /> <RowDisplay label="Popular packs" :instances="recentInstances" :can-paginate="true" />
<RowDisplay label="News & updates" :news="newsStore.news" :can-paginate="true" /> <RowDisplay label="Test" :instances="recentInstances" :can-paginate="true" />
</div> </div>
</template> </template>

View File

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

View File

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

View File

@@ -10,6 +10,7 @@
Sort By Sort By
<DropdownSelect <DropdownSelect
v-model="sortFilter" v-model="sortFilter"
name="sort-by"
:options="['Name', 'Version', 'Author']" :options="['Name', 'Version', 'Author']"
default-value="Name" default-value="Name"
class="dropdown" class="dropdown"
@@ -33,9 +34,9 @@
<div class="table-cell table-text">Author</div> <div class="table-cell table-text">Author</div>
<div class="table-cell table-text">Actions</div> <div class="table-cell table-text">Actions</div>
</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"> <div class="table-cell table-text">
<Button v-if="mod.outdated" icon-only> <Button v-if="true" icon-only>
<UpdatedIcon /> <UpdatedIcon />
</Button> </Button>
<Button v-else disabled icon-only> <Button v-else disabled icon-only>
@@ -43,10 +44,14 @@
</Button> </Button>
</div> </div>
<div class="table-cell table-text name-cell"> <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" /> <Avatar :src="mod.icon" />
{{ mod.name }} {{ mod.name }}
</router-link> </router-link>
<div v-else class="mod-text">
<Avatar :src="mod.icon" />
{{ mod.name }}
</div>
</div> </div>
<div class="table-cell table-text">{{ mod.version }}</div> <div class="table-cell table-text">{{ mod.version }}</div>
<div class="table-cell table-text">{{ mod.author }}</div> <div class="table-cell table-text">{{ mod.author }}</div>
@@ -54,118 +59,17 @@
<Button icon-only> <Button icon-only>
<TrashIcon /> <TrashIcon />
</Button> </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> </div>
</div> </div>
</Card> </Card>
</template> </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> <script setup>
import { import {
Avatar, Avatar,
@@ -178,6 +82,97 @@ import {
UpdatedIcon, UpdatedIcon,
DropdownSelect, DropdownSelect,
} from 'omorphia' } 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> </script>
<style scoped lang="scss"> <style scoped lang="scss">

View File

@@ -22,7 +22,6 @@
]" ]"
> >
<EnvironmentIndicator <EnvironmentIndicator
:type-only="moderation"
:client-side="data.client_side" :client-side="data.client_side"
:server-side="data.server_side" :server-side="data.server_side"
:type="data.project_type" :type="data.project_type"
@@ -30,7 +29,7 @@
</Categories> </Categories>
<hr class="card-divider" /> <hr class="card-divider" />
<div class="button-group"> <div class="button-group">
<Button color="primary" class="instance-button"> <Button color="primary" class="instance-button" @click="install">
<DownloadIcon /> <DownloadIcon />
Install Install
</Button> </Button>
@@ -209,6 +208,7 @@ import {
OpenCollectiveIcon, OpenCollectiveIcon,
} from '@/assets/external' } from '@/assets/external'
import { get_categories, get_loaders } from '@/helpers/tags' import { get_categories, get_loaders } from '@/helpers/tags'
import { install as pack_install } from '@/helpers/pack'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime' import relativeTime from 'dayjs/plugin/relativeTime'
import { ofetch } from 'ofetch' import { ofetch } from 'ofetch'
@@ -230,11 +230,20 @@ const [data, versions, members, dependencies] = await Promise.all([
watch( watch(
() => route.params.id, () => route.params.id,
() => { () => {
router.go() if (route.params.id) router.go()
} }
) )
dayjs.extend(relativeTime) 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> </script>
<style scoped lang="scss"> <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 = formattedAndFacets.slice(0, formattedAndFacets.length - 1)
formattedAndFacets += '' formattedAndFacets += ''
// TODO: fix me - ask jai
// If orFacets are present, start building formatted orFacet filter // If orFacets are present, start building formatted orFacet filter
let formattedOrFacets = '' let formattedOrFacets = ''
if (this.orFacets.length > 0 || this.activeVersions.length > 0) { if (this.orFacets.length > 0 || this.activeVersions.length > 0) {
@@ -91,18 +92,6 @@ export const useSearch = defineStore('searchStore', {
this.offset = response.offset this.offset = response.offset
this.pageCount = Math.ceil(this.totalHits / this.limit) 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() { resetFilters() {
this.facets = [] this.facets = []
this.orFacets = [] this.orFacets = []

View File

@@ -1,6 +1,4 @@
import { useInstances } from './instances'
import { useSearch } from './search' import { useSearch } from './search'
import { useTheming } from './theme' 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" resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38"
integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== 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: balanced-match@^1.0.0:
version "1.0.2" version "1.0.2"
resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" 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" resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2"
integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== 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: commander@^2.20.3:
version "2.20.3" version "2.20.3"
resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" 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" resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.4.tgz#a6f2dce612fadd2ef1f519b73551f17e85199831"
integrity sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ== 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: destr@^1.2.2:
version "1.2.2" version "1.2.2"
resolved "https://registry.yarnpkg.com/destr/-/destr-1.2.2.tgz#7ba9befcafb645a50e76b260449c63927b51e22f" 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" "@floating-ui/dom" "^0.1.10"
vue-resize "^2.0.0-alpha.1" 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: fs.realpath@^1.0.0:
version "1.0.0" version "1.0.0"
resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" 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" resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-1.0.1.tgz#fe85b2ec75a59037f2adfec100fd6c601761152e"
integrity sha512-/sKlQJCBYVY9Ers9hqzKou4H6V5UWc/M59TH2dvkt+84itfnq7uFOMLpOiOS4ujvHP4etln18fmIxA5R5fll0g== 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: minimatch@^3.0.5, minimatch@^3.1.1, minimatch@^3.1.2:
version "3.1.2" version "3.1.2"
resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b" 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" resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.8.7.tgz#bb79fc8729308549d28fe3a98fce73d2c0656450"
integrity sha512-yPngTo3aXUUmyuTjeTUT75txrf+aMh9FiD7q9ZE/i6r0bPb22g4FsE6Y338PQX1bmfy08i9QQCB7/rcUAVntfw== 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: punycode@^2.1.0:
version "2.3.0" version "2.3.0"
resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.3.0.tgz#f67fa67c94da8f4d0cfff981aee4118064199b8f" 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 // Initialize state
let st = State::get().await?; let st = State::get().await?;
st.settings.write().await.max_concurrent_downloads = 1; st.settings.write().await.max_concurrent_downloads = 10;
// Clear profiles // Clear profiles
println!("Clearing profiles."); println!("Clearing profiles.");
@@ -64,8 +64,6 @@ async fn main() -> theseus::Result<()> {
.await?; .await?;
State::sync().await?; State::sync().await?;
// Attempt to run game // Attempt to run game
if auth::users().await?.len() == 0 { if auth::users().await?.len() == 0 {
println!("No users found, authenticating."); println!("No users found, authenticating.");