🚧 wip(everything): this is super unfinished and might have some licensing issues still i dont think so tho
2
.cargo/config.toml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
[target.'cfg(windows)']
|
||||
rustflags = ["-C", "link-args=/STACK:16777220"]
|
||||
8
.dockerignore
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
.vscode
|
||||
target
|
||||
.gitignore
|
||||
docker-compose.yml
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
node_modules
|
||||
.github
|
||||
0
.env
Normal file
1
.envrc
Normal file
|
|
@ -0,0 +1 @@
|
|||
use flake
|
||||
50
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
name: Bug report
|
||||
description: Create a report to help us improve Polyfrost. Include screenshots if possible.
|
||||
labels: [bug]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: Before raising an issue, please search for existing issues to avoid creating duplicates.
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Original reporter/ticket ID
|
||||
description: If you are rewording a ticket, put the original reporter(s) and ticket ID(s). If not, leave this blank.
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Describe the bug
|
||||
description: A clear and concise description of what the bug is.
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
description: Steps to reproduce the behavior.
|
||||
placeholder: |
|
||||
1. Go to '...'
|
||||
2. Click on '...'
|
||||
3. Scroll down to '...'
|
||||
4. See error
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Expected behavior
|
||||
description: A clear and concise description of what you expected to happen.
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Operating System information
|
||||
description: Information about your environment.
|
||||
placeholder: |
|
||||
macOS 13.4.2, git 1.4.0, etc.
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Additional context
|
||||
description: Add any other context about the problem here.
|
||||
validations:
|
||||
required: false
|
||||
10
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
blank_issues_enabled: true
|
||||
contact_links:
|
||||
- name: Discord
|
||||
about: Ask questions or share feature requests on our Discord Server.
|
||||
url: https://polyfrost.org/discord
|
||||
- name: Polyfrost Documentation
|
||||
about: Useful documentation about Polyfrost, OneConfig, and other Polyfrost projects.
|
||||
url: https://docs.modrinth.com
|
||||
- name: Polyfrost Docs^2
|
||||
about: Useful documentation about how you can contribute to Polyfrost projects.
|
||||
37
.github/ISSUE_TEMPLATE/enhancement.yml
vendored
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
name: Enhancement
|
||||
description: Suggest an enhancement for an existing feature
|
||||
labels: [enhancement]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: Before raising an issue, please search for existing issues and [Discord](https://polyfrost.org/discord) suggestions to avoid creating duplicates.
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Original reporter/ticket ID
|
||||
description: If you are rewording a ticket, put the original reporter(s) and ticket ID(s). If not, leave this blank.
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Is your suggested enhancement related to a problem? Please describe, or link another Issue.
|
||||
description: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Describe the solution you'd like
|
||||
description: A clear and concise description of what you want to happen.
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Describe alternatives you've considered
|
||||
description: A clear and concise description of any alternative solutions or features you've considered.
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Additional context
|
||||
description: Add any other context or screenshots about the suggested enhancement here.
|
||||
validations:
|
||||
required: false
|
||||
35
.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
## Description
|
||||
|
||||
<!-- Describe your changes in detail -->
|
||||
|
||||
## Related Issue(s)
|
||||
|
||||
<!-- List the issue(s) this PR solves -->
|
||||
Fixes #
|
||||
|
||||
## How to test
|
||||
|
||||
<!-- Provide steps to test this PR -->
|
||||
|
||||
## Release Notes
|
||||
|
||||
<!--
|
||||
Add entries for the CHANGELOG.md or "NONE" if there aren't any user facing changes.
|
||||
Each line becomes a separate entry.
|
||||
Format: [!<optional for breaking>] <description>
|
||||
Example: !basic auth is no longer supported
|
||||
-->
|
||||
```release-note
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
<!--
|
||||
Does this PR require updates to the documentation at docs.polyfrost.org?
|
||||
* Yes
|
||||
* 1. Please create a docs issue: https://github.com/Polyfrost/Nexus/issues/new?assignees=&labels=bug&template=new_feature.yml
|
||||
* 2. Make sure this api is cross compatible with the existing api (or at least documented as such, see our policy on cross compatibility at https://contributing.polyfrost.org/)
|
||||
* 2. Paste the link to the docs issue below this comment
|
||||
* No
|
||||
* Are you sure? If so, nothing to do here.
|
||||
-->
|
||||
14
.github/dependabot.yml
vendored
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: 'github-actions'
|
||||
directory: '/'
|
||||
schedule:
|
||||
interval: 'weekly'
|
||||
- package-ecosystem: 'cargo'
|
||||
directory: '/'
|
||||
schedule:
|
||||
interval: 'daily'
|
||||
- package-ecosystem: 'npm'
|
||||
directory: '/'
|
||||
schedule:
|
||||
interval: 'daily'
|
||||
30
.github/workflows/stale.yml
vendored
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
name: Stale Issues / PRs
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '00 10 * * *'
|
||||
|
||||
jobs:
|
||||
statle:
|
||||
name: Check for Stale Issues / PRs
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Stale
|
||||
uses: actions/stale@v9
|
||||
with:
|
||||
close-issue-message: >
|
||||
This issue was closed because it has been stale for 10 days with no activity.
|
||||
close-pr-message: >
|
||||
This PR was closed because it has been stale for 10 days with no activity.
|
||||
days-before-stale: 120
|
||||
days-before-close: 10
|
||||
days-before-pr-close: -1
|
||||
exempt-all-assignees: true
|
||||
exempt-all-pr-milestones: true
|
||||
exempt-issue-labels: 'planned,added,fixed,meta: no-stale'
|
||||
exempt-pr-labels: 'dependencies,i18n,meta: no-stale'
|
||||
stale-issue-label: 'meta: stale'
|
||||
stale-issue-message: >
|
||||
This issue was marked as stale because there has been no activity in the past 120 days.
|
||||
To remove this label, set the label `meta: no-stale`, or interact with this issue.
|
||||
|
||||
110
.gitignore
vendored
|
|
@ -1,3 +1,7 @@
|
|||
# Nix
|
||||
result*
|
||||
repl-result-out*
|
||||
.direnv
|
||||
|
||||
# Prisma
|
||||
crates/prisma/src/prisma.rs
|
||||
|
|
@ -7,11 +11,15 @@ dev.db-journal
|
|||
# Vendor
|
||||
dist
|
||||
.eslintcache
|
||||
.env*
|
||||
# .env*
|
||||
vendor/
|
||||
vender/
|
||||
|
||||
# Created by https://www.toptal.com/developers/gitignore/api/node,rust,yarn,linux,macos,windows,rust-analyzer,visualstudiocode,git
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=node,rust,yarn,linux,macos,windows,rust-analyzer,visualstudiocode,git
|
||||
core/src/game
|
||||
core/src/api/package
|
||||
|
||||
# Created by https://www.toptal.com/developers/gitignore/api/git,node,rust,yarn,linux,macos,windows,rust-analyzer,visualstudiocode,intellij+all
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=git,node,rust,yarn,linux,macos,windows,rust-analyzer,visualstudiocode,intellij+all
|
||||
|
||||
### Git ###
|
||||
# Created by git for backups. To disable backups in Git:
|
||||
|
|
@ -20,7 +28,7 @@ vendor/
|
|||
|
||||
# Created by git when using merge tools for conflicts
|
||||
*.BACKUP.*
|
||||
*.BASE.*
|
||||
# *.BASE.*
|
||||
*.LOCAL.*
|
||||
*.REMOTE.*
|
||||
*_BACKUP_*.txt
|
||||
|
|
@ -28,6 +36,94 @@ vendor/
|
|||
*_LOCAL_*.txt
|
||||
*_REMOTE_*.txt
|
||||
|
||||
### Intellij+all ###
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
|
||||
# User-specific stuff
|
||||
.idea/**/workspace.xml
|
||||
.idea/**/tasks.xml
|
||||
.idea/**/usage.statistics.xml
|
||||
.idea/**/dictionaries
|
||||
.idea/**/shelf
|
||||
|
||||
# AWS User-specific
|
||||
.idea/**/aws.xml
|
||||
|
||||
# Generated files
|
||||
.idea/**/contentModel.xml
|
||||
|
||||
# Sensitive or high-churn files
|
||||
.idea/**/dataSources/
|
||||
.idea/**/dataSources.ids
|
||||
.idea/**/dataSources.local.xml
|
||||
.idea/**/sqlDataSources.xml
|
||||
.idea/**/dynamic.xml
|
||||
.idea/**/uiDesigner.xml
|
||||
.idea/**/dbnavigator.xml
|
||||
|
||||
# Gradle
|
||||
.idea/**/gradle.xml
|
||||
.idea/**/libraries
|
||||
|
||||
# Gradle and Maven with auto-import
|
||||
# When using Gradle or Maven with auto-import, you should exclude module files,
|
||||
# since they will be recreated, and may cause churn. Uncomment if using
|
||||
# auto-import.
|
||||
# .idea/artifacts
|
||||
# .idea/compiler.xml
|
||||
# .idea/jarRepositories.xml
|
||||
# .idea/modules.xml
|
||||
# .idea/*.iml
|
||||
# .idea/modules
|
||||
# *.iml
|
||||
# *.ipr
|
||||
|
||||
# CMake
|
||||
cmake-build-*/
|
||||
|
||||
# Mongo Explorer plugin
|
||||
.idea/**/mongoSettings.xml
|
||||
|
||||
# File-based project format
|
||||
*.iws
|
||||
|
||||
# IntelliJ
|
||||
out/
|
||||
|
||||
# mpeltonen/sbt-idea plugin
|
||||
.idea_modules/
|
||||
|
||||
# JIRA plugin
|
||||
atlassian-ide-plugin.xml
|
||||
|
||||
# Cursive Clojure plugin
|
||||
.idea/replstate.xml
|
||||
|
||||
# SonarLint plugin
|
||||
.idea/sonarlint/
|
||||
|
||||
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||
com_crashlytics_export_strings.xml
|
||||
crashlytics.properties
|
||||
crashlytics-build.properties
|
||||
fabric.properties
|
||||
|
||||
# Editor-based Rest Client
|
||||
.idea/httpRequests
|
||||
|
||||
# Android studio 3.1+ serialized cache file
|
||||
.idea/caches/build_file_checksums.ser
|
||||
|
||||
### Intellij+all Patch ###
|
||||
# Ignore everything but code style settings and run configurations
|
||||
# that are supposed to be shared within teams.
|
||||
|
||||
.idea/*
|
||||
|
||||
!.idea/codeStyles
|
||||
!.idea/runConfigurations
|
||||
|
||||
### Linux ###
|
||||
*~
|
||||
|
||||
|
|
@ -152,7 +248,7 @@ web_modules/
|
|||
.yarn-integrity
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
# .env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
|
@ -270,7 +366,7 @@ ehthumbs_vista.db
|
|||
# Folder config file
|
||||
[Dd]esktop.ini
|
||||
|
||||
# Recycle Bin used on file shares
|
||||
# Recyc# le Bin used on file shares
|
||||
$RECYCLE.BIN/
|
||||
|
||||
# Windows Installer files
|
||||
|
|
@ -301,5 +397,3 @@ $RECYCLE.BIN/
|
|||
# .pnp.*
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/node,rust,yarn,linux,macos,windows,rust-analyzer,visualstudiocode,git
|
||||
|
||||
src-tauri/gen/**
|
||||
|
|
|
|||
8
.idea/.gitignore
generated
vendored
|
|
@ -1,8 +0,0 @@
|
|||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
12
.idea/Launcher.iml
generated
|
|
@ -1,12 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="EMPTY_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/onelauncher/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src-tauri/src" isTestSource="false" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/target" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
7
.idea/discord.xml
generated
|
|
@ -1,7 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="DiscordProjectSettings">
|
||||
<option name="show" value="PROJECT_FILES" />
|
||||
<option name="description" value="" />
|
||||
</component>
|
||||
</project>
|
||||
6
.idea/inspectionProfiles/Project_Default.xml
generated
|
|
@ -1,6 +0,0 @@
|
|||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||
</profile>
|
||||
</component>
|
||||
8
.idea/modules.xml
generated
|
|
@ -1,8 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/Launcher.iml" filepath="$PROJECT_DIR$/.idea/Launcher.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
6
.idea/vcs.xml
generated
|
|
@ -1,6 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
2
.nvmrc
|
|
@ -1 +1 @@
|
|||
18
|
||||
20
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@ hard_tabs = true
|
|||
newline_style = "Unix"
|
||||
use_small_heuristics = "Default"
|
||||
reorder_imports = true
|
||||
reorder_imported_names = true
|
||||
imports_granularity = "Crate"
|
||||
reorder_modules = true
|
||||
remove_nested_parens = true
|
||||
edition = "2021"
|
||||
|
|
|
|||
48
.vscode/settings.json
vendored
|
|
@ -1,11 +1,48 @@
|
|||
{
|
||||
"files.associations": {
|
||||
"*.scss": "tailwindcss",
|
||||
"*.css": "tailwindcss"
|
||||
},
|
||||
"[rust]": {
|
||||
"editor.defaultFormatter": "rust-lang.rust-analyzer"
|
||||
},
|
||||
"files.watcherExclude": {
|
||||
"**/_build": true,
|
||||
"**/.classpath": true,
|
||||
"**/.flatpak-builder": true,
|
||||
"**/.git/objects/**": true,
|
||||
"**/.git/subtree-cache/**": true,
|
||||
"**/.idea": true,
|
||||
"**/.project": true,
|
||||
"**/.settings": true,
|
||||
"**/.venv": true,
|
||||
"**/node_modules": true,
|
||||
"**/.rustup": true,
|
||||
"**/.cargo": true,
|
||||
"**/.crates": true
|
||||
},
|
||||
"rust-analyzer.diagnostics.disabled": [
|
||||
"E0004",
|
||||
"inactive-code",
|
||||
"inactive_code"
|
||||
],
|
||||
"rust-analyzer.files.excludeDirs": [
|
||||
"_build",
|
||||
".flatpak-builder",
|
||||
".git",
|
||||
".gitlab",
|
||||
".gitlab-ci",
|
||||
".gradle",
|
||||
".idea",
|
||||
".next",
|
||||
".project",
|
||||
".settings",
|
||||
".venv",
|
||||
"bin",
|
||||
"hooks",
|
||||
"node_modules",
|
||||
"screenshots",
|
||||
"target",
|
||||
".cargo",
|
||||
".rustup",
|
||||
".crates"
|
||||
],
|
||||
"rust-analyzer.procMacro.enable": true,
|
||||
"rust-analyzer.diagnostics.experimental.enable": false,
|
||||
"search.exclude": {
|
||||
|
|
@ -39,9 +76,6 @@
|
|||
"toml",
|
||||
"solid"
|
||||
],
|
||||
"css.customData": [
|
||||
".vscode/tailwind.json"
|
||||
],
|
||||
"eslint.lintTask.enable": true,
|
||||
"eslint.workingDirectories": [],
|
||||
"explorer.fileNesting.enabled": true,
|
||||
|
|
|
|||
55
.vscode/tailwind.json
vendored
|
|
@ -1,55 +0,0 @@
|
|||
{
|
||||
"version": 1.1,
|
||||
"atDirectives": [
|
||||
{
|
||||
"name": "@tailwind",
|
||||
"description": "Use the `@tailwind` directive to insert Tailwind's `base`, `components`, `utilities` and `screens` styles into your CSS.",
|
||||
"references": [
|
||||
{
|
||||
"name": "Tailwind Documentation",
|
||||
"url": "https://tailwindcss.com/docs/functions-and-directives#tailwind"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "@apply",
|
||||
"description": "Use the `@apply` directive to inline any existing utility classes into your own custom CSS. This is useful when you find a common utility pattern in your HTML that you’d like to extract to a new component.",
|
||||
"references": [
|
||||
{
|
||||
"name": "Tailwind Documentation",
|
||||
"url": "https://tailwindcss.com/docs/functions-and-directives#apply"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "@responsive",
|
||||
"description": "You can generate responsive variants of your own classes by wrapping their definitions in the `@responsive` directive:\n```css\n@responsive {\n .alert {\n background-color: #E53E3E;\n }\n}\n```\n",
|
||||
"references": [
|
||||
{
|
||||
"name": "Tailwind Documentation",
|
||||
"url": "https://tailwindcss.com/docs/functions-and-directives#responsive"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "@screen",
|
||||
"description": "The `@screen` directive allows you to create media queries that reference your breakpoints by **name** instead of duplicating their values in your own CSS:\n```css\n@screen sm {\n /* ... */\n}\n```\n…gets transformed into this:\n```css\n@media (min-width: 640px) {\n /* ... */\n}\n```\n",
|
||||
"references": [
|
||||
{
|
||||
"name": "Tailwind Documentation",
|
||||
"url": "https://tailwindcss.com/docs/functions-and-directives#screen"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "@variants",
|
||||
"description": "Generate `hover`, `focus`, `active` and other **variants** of your own utilities by wrapping their definitions in the `@variants` directive:\n```css\n@variants hover, focus {\n .btn-brand {\n background-color: #3182CE;\n }\n}\n```\n",
|
||||
"references": [
|
||||
{
|
||||
"name": "Tailwind Documentation",
|
||||
"url": "https://tailwindcss.com/docs/functions-and-directives#variants"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
125
ATTRIBUTION.md
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
# Attribution
|
||||
|
||||
The source code of this repository is licensed under the GNU General Public License, Version 3 only, which is provided in the file [LICENSE](./LICENSE), with a header provided below. [Certain files in our library wrappers](./core/wrapper/) may be under a different license or [require credit](#additional-libraries), with their specific headers outlined in the below non-exhaustive list.
|
||||
|
||||
## OneLauncher
|
||||
|
||||
```txt
|
||||
OneLauncher - Open source Rust-based Minecraft Launcher
|
||||
Copyright (C) 2023~2024 Polyfrost and Contributors
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, version 3.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
```
|
||||
|
||||
## Polyfrost branding
|
||||
|
||||
Any files depicting [Polyfrost branding](https://polyfrost.org/legal/branding), including the Polyfrost logo, any landing and background images, the OneConfig logo, the OneLauncher logo, and variations thereof, are licensed under the following:
|
||||
|
||||
```txt
|
||||
All rights reserved. Copyright (C) 2022~2024 Polyfrost
|
||||
```
|
||||
|
||||
This includes, but may not be limited to, the following files:
|
||||
|
||||
* [`desktop/.icons/*`](./desktop/.icons/)
|
||||
* [`desktop/src/assets/licensed/*`](./desktop/src/assets/licensed/)
|
||||
|
||||
## Additional Libraries
|
||||
|
||||
The following are libraries, projects, and codebases which we (Polyfrost and Contributors) copied or modified from, with additional attribution inline (THIS IS A NON-EXHAUSTIVE LIST, IF WE ARE MISSING A LICENSE, PLEASE CHECK OUR [attributions page](https://polyfrost.org/attributions), OR LEAVE A TICKET IN [our Discord server](https://polyfrost.org/discord)):
|
||||
|
||||
## Prism Launcher
|
||||
|
||||
```txt
|
||||
Prism Launcher - Minecraft Launcher
|
||||
Copyright (C) 2022-2024 Prism Launcher Contributors
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, version 3.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
This file incorporates work covered by the following copyright and
|
||||
permission notice:
|
||||
|
||||
Copyright 2013-2021 MultiMC Contributors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
```
|
||||
|
||||
## Modrinth App
|
||||
|
||||
```txt
|
||||
Modrinth App
|
||||
Copyright (C) 2022-2023 Modrinth
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, version 3.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
```
|
||||
|
||||
## Gamemode
|
||||
|
||||
```txt
|
||||
Copyright (c) 2017-2022, Feral Interactive
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of Feral Interactive nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
```
|
||||
137
CODE_OF_CONDUCT.md
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
This is a modified version of the Contributor Covenant to clarify trolling (line 35),
|
||||
and add contact information (lines 67-68).
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, caste, color, religion, or sexual
|
||||
identity and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the overall
|
||||
community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or advances of
|
||||
any kind
|
||||
* Trolling (excessive antagonistic, inflammatory, insincere behaviour), insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email address,
|
||||
without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official email address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement via
|
||||
[our Discord server](https://polyfrost.org/discord), or via
|
||||
[email](mailto:coc@polyfrost.org).
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series of
|
||||
actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or permanent
|
||||
ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within the
|
||||
community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.1, available at
|
||||
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
||||
|
||||
Community Impact Guidelines were inspired by
|
||||
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
||||
[https://www.contributor-covenant.org/translations][translations].
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
||||
[Mozilla CoC]: https://github.com/mozilla/diversity
|
||||
[FAQ]: https://www.contributor-covenant.org/faq
|
||||
[translations]: https://www.contributor-covenant.org/translations
|
||||
107
Cargo.toml
|
|
@ -1,8 +1,11 @@
|
|||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"src-tauri",
|
||||
"onelauncher"
|
||||
"core",
|
||||
"debugger",
|
||||
"desktop/src-tauri",
|
||||
"testing",
|
||||
"backend"
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
|
|
@ -12,17 +15,21 @@ repository = "https://github.com/Polyfrost/Nexus"
|
|||
documentation = "https://docs.polyfrost.org/nexus"
|
||||
readme = "README.md"
|
||||
homepage = "https://polyfrost.org"
|
||||
authors = [ "Polyfrost" ]
|
||||
authors = [ "Polyfrost", "Polyfrost Contributors" ]
|
||||
|
||||
[workspace.dependencies]
|
||||
tauri = { version = "2.0.0-beta", features = [] }
|
||||
tauri-build = { version = "2.0.0-beta", features = [] }
|
||||
tauri = { version = "2.0.0-beta", features = [
|
||||
"rustls-tls",
|
||||
"tracing",
|
||||
] }
|
||||
tauri-build = { version = "2.0.0-beta" }
|
||||
tauri-plugin-authenticator = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
|
||||
tauri-plugin-shell = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
|
||||
tauri-plugin-stronghold = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
|
||||
tauri-plugin-window-state = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
|
||||
tauri-plugin-single-instance = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
|
||||
tauri-plugin-updater = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2", features = [ "rustls-tls" ] }
|
||||
|
||||
interpulse = { version = "0.1" }
|
||||
interpulse = { version = "0.1.3" }
|
||||
|
||||
tracing = { version = "0.1" }
|
||||
tracing-subscriber = { version = "0.3", features = [
|
||||
|
|
@ -31,46 +38,88 @@ tracing-subscriber = { version = "0.3", features = [
|
|||
] }
|
||||
tracing-error = { version = "0.2" }
|
||||
tracing-appender = { version = "0.2" }
|
||||
sentry = { version = "0.32", default-features = false, features = [
|
||||
"rustls",
|
||||
"reqwest",
|
||||
"backtrace",
|
||||
"panic",
|
||||
"anyhow",
|
||||
"debug-images"
|
||||
] }
|
||||
|
||||
notify = { version = "6.1", default-features = false }
|
||||
notify-debouncer-mini = { version = "0.4", default-features = false }
|
||||
|
||||
uuid = { version = "1.8", features = [
|
||||
"serde",
|
||||
"v4"
|
||||
] }
|
||||
tokio = { version = "1", features = [ "full" ] }
|
||||
serde = { version = "1", features = [ "derive" ] }
|
||||
tokio = { version = "1.37", features = [ "full" ] }
|
||||
async-tungstenite = { version = "0.25", features = [
|
||||
"tokio-runtime",
|
||||
"tokio-rustls-native-certs"
|
||||
] }
|
||||
tokio-stream = { version = "0.1.15", features = [ "fs" ] }
|
||||
serde = { version = "1.0", features = [ "derive" ] }
|
||||
chrono = { version = "0.4", features = [ "serde" ] }
|
||||
reqwest = { version = "0.12", features = [
|
||||
rand = { version = "0.8.5" }
|
||||
byteorder = { version = "1.5.0" }
|
||||
base64 = { version = "0.22" }
|
||||
p256 = { version = "0.13.2", features = [ "ecdsa" ] }
|
||||
reqwest = { version = "0.12", default-features = false, features = [
|
||||
"json",
|
||||
"stream",
|
||||
"multipart",
|
||||
"blocking",
|
||||
"rustls-tls-native-roots",
|
||||
"deflate",
|
||||
"gzip",
|
||||
"brotli"
|
||||
] }
|
||||
serde_json = { version = "1" }
|
||||
flate2 = { version = "1" }
|
||||
iota_stronghold = { version = "2" }
|
||||
iota-crypto = { version = "0.23" }
|
||||
hex = { version = "0.4" }
|
||||
zeroize = { version = "1", features = [ "zeroize_derive" ] }
|
||||
quote = { version = "1.0" }
|
||||
syn = { version = "2.0", features = [ "full" ] }
|
||||
tempfile = { version = "3.10" }
|
||||
dunce = { version = "1.0.4" }
|
||||
serde_json = { version = "1.0" }
|
||||
serde_ini = { version = "0.2" }
|
||||
flate2 = { version = "1.0" }
|
||||
tar = { version = "0.4" }
|
||||
zip = { version = "0.6" }
|
||||
async-trait = { version = "0.1" }
|
||||
thiserror = { version = "1" }
|
||||
anyhow = { version = "1" }
|
||||
dirs = { version = "5" }
|
||||
open = { version = "5" }
|
||||
thiserror = { version = "1.0" }
|
||||
anyhow = { version = "1.0" }
|
||||
dirs = { version = "5.0" }
|
||||
open = { version = "5.1" }
|
||||
discord-rich-presence = { version = "0.2" }
|
||||
winreg = { version = "0.52" }
|
||||
sha1 = { version = "0.10.6" }
|
||||
bytes = { version = "1" }
|
||||
lazy_static = { version = "1" }
|
||||
once_cell = { version = "1" }
|
||||
paste = { version = "1.0" }
|
||||
sha1_smol = { version = "1.0", features = [ "std" ] }
|
||||
sha2 = { version = "0.10" }
|
||||
bytes = { version = "1.6" }
|
||||
lazy_static = { version = "1.4" }
|
||||
once_cell = { version = "1.19" }
|
||||
indicatif = { version = "0.17" }
|
||||
futures = { version = "0.3" }
|
||||
tokio-stream = { version = "0.1", features = [ "fs" ] }
|
||||
async-recursion = { version = "1.1" }
|
||||
notify = { version = "6.1", default-features = false, features = [ "serde" ] }
|
||||
notify-debouncer-mini = { version = "0.4", default-features = false }
|
||||
async_zip = { version = "0.0.17", features = [ "full" ] }
|
||||
regex = { version = "1.10" }
|
||||
sysinfo = { version = "0.30" }
|
||||
sys-info = { version = "0.9" }
|
||||
whoami = { version = "1.5" }
|
||||
cocoa = { version = "0.25" }
|
||||
objc = { version = "0.2" }
|
||||
|
||||
[profile.dev]
|
||||
# Make compilation faster on macOS
|
||||
split-debuginfo = "unpacked"
|
||||
# add debug symbols/logic and optimize for reduced build time (parallel)
|
||||
debug = true
|
||||
lto = false
|
||||
codegen-units = 256
|
||||
rpath = false
|
||||
panic = "unwind"
|
||||
|
||||
# Set the settings for build scripts and proc-macros.
|
||||
[profile.dev.build-override]
|
||||
|
|
@ -80,3 +129,11 @@ opt-level = 3
|
|||
[profile.dev.package."*"]
|
||||
opt-level = 3
|
||||
incremental = false
|
||||
|
||||
# optimize for speed and reduce size for release
|
||||
[profile.release]
|
||||
panic = "abort" # strip panic cleanup logic
|
||||
codegen-units = 1 # compile crate one after another for better optimization
|
||||
lto = true
|
||||
opt-level = "s" # optimize binary
|
||||
strip = true # remove debug symbols
|
||||
|
|
|
|||
30
Dockerfile
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
FROM rustlang/rust:nightly-alpine as builder
|
||||
|
||||
WORKDIR /usr/src/polyfrost-api
|
||||
|
||||
# Use sparse registry because it is significantly faster and this already requires nightly
|
||||
ENV CARGO_UNSTABLE_SPARSE_REGISTRY=true
|
||||
|
||||
# Install build tools
|
||||
RUN apk add --no-cache g++
|
||||
|
||||
# Copy source files
|
||||
COPY . .
|
||||
|
||||
# Build actual binary
|
||||
RUN cargo build --package polyfrost_api --release --locked --all-features
|
||||
|
||||
# ---------------------------------------------------------------------------------------------
|
||||
|
||||
# :3 :3 :3
|
||||
FROM alpine:3
|
||||
|
||||
COPY --from=builder /usr/src/polyfrost-api/target/release/polyfrost_api /usr/local/bin/polyfrost_api
|
||||
|
||||
# Use an unprivileged user
|
||||
RUN adduser --home /nonexistent --no-create-home --disabled-password polyfrost-api
|
||||
USER polyfrost-api
|
||||
|
||||
HEALTHCHECK --interval=10s --timeout=3s --retries=5 CMD wget --spider --q http://localhost:$PORT/ || exit 1
|
||||
|
||||
CMD ["polyfrost_api"]
|
||||
674
LICENSE
Normal file
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
11
README.md
|
|
@ -1 +1,12 @@
|
|||
# OneLauncher
|
||||
|
||||
Rust-based Minecraft launcher utilizing Tauri, SolidJS, and Tailwind
|
||||
|
||||
## Project Structure
|
||||
|
||||
* [`desktop`](./desktop/) - Rust-based Minecraft launcher utilizing Tauri, SolidJS, and Tailwind.
|
||||
* [`core`](./core/) - The core for our Minecraft launcher (compilable without Tauri), along with Rust-based utilities for other Polyfrost projects and interactions.
|
||||
* [`backend`](./backend/) - Our `actix-web` based API, accessible at <https://api.polyfrost.org>, with documentation on our [docs^2 website](https://contributing.polyfrost.org/api/).
|
||||
* [`testing`](./testing/) - Testing playground for our Rust core, independant of Tauri.
|
||||
* [`debugger`](./debugger/) - `proc-macro` utilities for our Rust libraries.
|
||||
* [`distribution`](./distribution/) - Distribution utilties and meta files for the [`desktop`](./desktop/) app.
|
||||
|
|
|
|||
34
backend/Cargo.toml
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
[package]
|
||||
name = "polyfrost_api"
|
||||
version = "0.0.0"
|
||||
description = "API and Backend for Polyfrost"
|
||||
license = { workspace = true }
|
||||
edition = { workspace = true }
|
||||
repository = { workspace = true }
|
||||
documentation = { workspace = true }
|
||||
readme = { workspace = true }
|
||||
homepage = { workspace = true }
|
||||
authors = { workspace = true }
|
||||
|
||||
[[bin]]
|
||||
name = "polyfrost_api"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = { version = "4" }
|
||||
actix-rt = { version = "2.9.0" }
|
||||
governor = { version = "0.6" }
|
||||
|
||||
tokio = { workspace = true }
|
||||
tokio-stream = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
reqwest = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
|
||||
log = { version = "0.4" }
|
||||
env_logger = { version = "0.11" }
|
||||
dotenvy = { version = "0.15" }
|
||||
xml = { version = "0.8" }
|
||||
15
backend/src/lib.rs
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
use std::path::Path;
|
||||
|
||||
use actix_web::{get, web::Data, HttpResponse, Responder};
|
||||
|
||||
#[get("/")]
|
||||
pub async fn index() -> impl Responder {
|
||||
HttpResponse::Ok().body("Polyfrost API")
|
||||
}
|
||||
|
||||
#[get("/oneconfig/{version}-{loader}")]
|
||||
pub async fn oneconfig(
|
||||
data: Data<state::AppState>,
|
||||
path: Path<(String, String)>,
|
||||
) -> impl Responder {
|
||||
}
|
||||
41
backend/src/main.rs
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
use actix_web::{web::Data, App, HttpServer};
|
||||
use log::info;
|
||||
|
||||
#[actix_rt::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
dotenvy::dotenv().ok();
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
|
||||
|
||||
info!(
|
||||
"starting polyfrost api on {}",
|
||||
dotenvy::var("BIND_ADDR").unwrap()
|
||||
);
|
||||
|
||||
HttpServer::new(|| {
|
||||
let mut headers = reqwest::header::HeaderMap::new();
|
||||
let header = reqwest::header::HeaderValue::from_str(&format!(
|
||||
"onelauncher/{} (polyfrost.org)",
|
||||
env!("CARGO_PKG_VERSION")
|
||||
))
|
||||
.unwrap();
|
||||
headers.insert(reqwest::header::USER_AGENT, header);
|
||||
|
||||
App::new()
|
||||
.app_data(Data::new(state::AppState {
|
||||
public_maven_url: dotenvy::var("PUBLIC_MAVEN_URL")
|
||||
.unwrap_or("https://repo.polyfrost.org".to_string()),
|
||||
internal_maven_url: dotenvy::var("INTERNAL_MAVEN_URL")
|
||||
.unwrap_or("http://localhost:8000".to_string()),
|
||||
http_client: reqwest::Client::builder()
|
||||
.tcp_keepalive(Some(std::time::Duration::from_secs(15)))
|
||||
.default_headers(headers)
|
||||
.build()
|
||||
.expect("failed to build reqwest client!"),
|
||||
}))
|
||||
.service(index)
|
||||
.service(oneconfig)
|
||||
})
|
||||
.bind(dotenvy::var("BIND_ADDR").unwrap())?
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
0
backend/src/parsing.rs
Normal file
0
backend/src/state.rs
Normal file
0
backend/src/utils.rs
Normal file
77
core/Cargo.toml
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
[package]
|
||||
name = "onelauncher"
|
||||
version = "0.0.0"
|
||||
description = "The core of OneLauncher"
|
||||
license = { workspace = true }
|
||||
edition = { workspace = true }
|
||||
repository = { workspace = true }
|
||||
documentation = { workspace = true }
|
||||
readme = { workspace = true }
|
||||
homepage = { workspace = true }
|
||||
authors = { workspace = true }
|
||||
|
||||
[features]
|
||||
# feature flag allowing us to interact with tauri (for loading animations, errors showing on gui, etc)
|
||||
# also allows us to compile onelauncher core without tauri
|
||||
tauri = [ "dep:tauri" ]
|
||||
cli = [ "dep:indicatif" ]
|
||||
|
||||
[dependencies]
|
||||
onelauncher_debug = { path = "../debugger" }
|
||||
tauri = { workspace = true, optional = true }
|
||||
indicatif = { workspace = true, optional = true }
|
||||
|
||||
interpulse = { workspace = true }
|
||||
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
tracing-error = { workspace = true }
|
||||
tracing-appender = { workspace = true }
|
||||
|
||||
# we use notify to track instance directories (i.e. if a user uses a file manager to change managed files, or if a crash happens)
|
||||
notify = { workspace = true }
|
||||
notify-debouncer-mini = { workspace = true }
|
||||
iota_stronghold = { workspace = true }
|
||||
iota-crypto = { workspace = true }
|
||||
|
||||
hex = { workspace = true }
|
||||
zeroize = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
serde_ini = { workspace = true }
|
||||
flate2 = { workspace = true }
|
||||
paste = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
tar = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
uuid = { workspace = true }
|
||||
async-trait = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
reqwest = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
open = { workspace = true }
|
||||
sha1_smol = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
async_zip = { workspace = true }
|
||||
discord-rich-presence = { workspace = true }
|
||||
regex = { workspace = true }
|
||||
sysinfo = { workspace = true }
|
||||
sys-info = { workspace = true }
|
||||
whoami = { workspace = true }
|
||||
lazy_static = { workspace = true }
|
||||
async-tungstenite = { workspace = true }
|
||||
async-recursion = { workspace = true }
|
||||
tokio-stream = { workspace = true }
|
||||
bytes = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
dunce = { workspace = true }
|
||||
rand = { workspace = true }
|
||||
p256 = { workspace = true }
|
||||
byteorder = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winreg = { workspace = true }
|
||||
0
core/src/api/cluster/create.rs
Normal file
133
core/src/api/cluster/mod.rs
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
//! OneLauncher cluster management
|
||||
|
||||
use crate::proxy::send::send_cluster;
|
||||
use crate::proxy::ClusterPayloadType;
|
||||
use crate::prelude::ClusterPath;
|
||||
use crate::store::{State, PackagePath};
|
||||
use crate::utils::io;
|
||||
pub use crate::store::{JavaOptions, Cluster};
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub mod create;
|
||||
pub mod update;
|
||||
|
||||
/// get a cluster by its specified [`ClusterPath`].
|
||||
#[tracing::instrument]
|
||||
pub async fn get(path: &ClusterPath, clear: Option<bool>) -> crate::Result<Option<Cluster>> {
|
||||
let state = State::get().await?;
|
||||
let clusters = state.clusters.read().await;
|
||||
let mut cluster = clusters.0.get(path).cloned();
|
||||
|
||||
if clear.unwrap_or(false) {
|
||||
if let Some(cluster) = &mut cluster {
|
||||
cluster.packages = HashMap::new();
|
||||
}
|
||||
}
|
||||
|
||||
Ok(cluster)
|
||||
}
|
||||
|
||||
/// remove a specified cluster from it's [`ClusterPath`].
|
||||
#[tracing::instrument]
|
||||
pub async fn remove(path: &ClusterPath) -> crate::Result<()> {
|
||||
let state = State::get().await?;
|
||||
let mut clusters = state.clusters.write().await;
|
||||
|
||||
if let Some(cluster) = clusters.remove(path).await? {
|
||||
send_cluster(cluster.uuid, path, &cluster.meta.name, ClusterPayloadType::Deleted).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// get a cluster by it's [`uuid::Uuid`]
|
||||
#[tracing::instrument]
|
||||
pub async fn get_by_uuid(
|
||||
uuid: uuid::Uuid,
|
||||
clear: Option<bool>,
|
||||
) -> crate::Result<Option<Cluster>> {
|
||||
let state = State::get().await?;
|
||||
let clusters = state.clusters.read().await;
|
||||
let mut cluster = clusters.0.values().find(|c| c.uuid == uuid).cloned();
|
||||
|
||||
if clear.unwrap_or(false) {
|
||||
if let Some(cluster) = &mut cluster {
|
||||
cluster.packages = HashMap::new();
|
||||
}
|
||||
}
|
||||
|
||||
Ok(cluster)
|
||||
}
|
||||
|
||||
/// get a cluster's full path by it's [`ClusterPath`].
|
||||
#[tracing::instrument]
|
||||
pub async fn get_full_path(path: &ClusterPath) -> crate::Result<PathBuf> {
|
||||
let _ = get(path, Some(true)).await?.ok_or_else(|| anyhow::anyhow!("failed to get the full path of profile at path {}", path))?;
|
||||
let full_path = io::canonicalize(path.full_path().await?)?;
|
||||
|
||||
Ok(full_path)
|
||||
}
|
||||
|
||||
/// get a specific mod's full path in the filesystem by it's [`ClusterPath`] and [`PackagePath`].
|
||||
#[tracing::instrument]
|
||||
pub async fn get_mod_path(
|
||||
cluster_path: &ClusterPath,
|
||||
package_path: &PackagePath,
|
||||
) -> crate::Result<PathBuf> {
|
||||
if get(cluster_path, Some(true)).await?.is_some() {
|
||||
let full_path = io::canonicalize(package_path.full_path(cluster_path.clone()).await?)?;
|
||||
|
||||
return Ok(full_path);
|
||||
}
|
||||
|
||||
Err(anyhow::anyhow!("failed to get the full path of a cluster at path {}", package_path.full_path(cluster_path.clone()).await?.display()).into())
|
||||
}
|
||||
|
||||
/// edit a cluster with an async closure and it's [`ClusterPath`]
|
||||
pub async fn edit<FutFn>(
|
||||
path: &ClusterPath,
|
||||
action: impl Fn(&mut Cluster) -> FutFn,
|
||||
) -> crate::Result<()>
|
||||
where
|
||||
FutFn: Future<Output = crate::Result<()>>,
|
||||
{
|
||||
let state = State::get().await?;
|
||||
let mut clusters = state.clusters.write().await;
|
||||
|
||||
match clusters.0.get_mut(path) {
|
||||
Some(ref mut cluster) => {
|
||||
action(cluster).await?;
|
||||
|
||||
send_cluster(cluster.uuid, path, &cluster.meta.name, ClusterPayloadType::Edited).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
None => Err(anyhow::anyhow!("unmanaged profile edited at {}", path.to_string()).into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to update a Cluster's playtime.
|
||||
#[tracing::instrument]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn update_playtime(path: &ClusterPath) -> crate::Result<()> {
|
||||
let state = State::get().await?;
|
||||
let cluster = get(path, None).await?.ok_or_else(|| anyhow::anyhow!("failed to update playtime at path {}", path))?;
|
||||
let recent_playtime = cluster.meta.recently_played;
|
||||
|
||||
/*
|
||||
* todo
|
||||
*/
|
||||
|
||||
let mut clusters = state.clusters.write().await;
|
||||
if let Some(cluster) = clusters.0.get_mut(path) {
|
||||
cluster.meta.overall_played += recent_playtime;
|
||||
cluster.meta.recently_played = 0;
|
||||
}
|
||||
|
||||
State::sync().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
0
core/src/api/cluster/update.rs
Normal file
42
core/src/api/handler.rs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
use std::path::PathBuf;
|
||||
|
||||
use crate::proxy::send::{send_internet, send_message};
|
||||
use crate::utils::io;
|
||||
use crate::api::prelude::InternetPayload;
|
||||
|
||||
pub async fn parse_uri(cmd: &str) -> crate::Result<()> {
|
||||
let cmd = handle_cmd(cmd).await?;
|
||||
send_internet(cmd).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn handle_cmd(cmd: &str) -> crate::Result<InternetPayload> {
|
||||
tracing::debug!("parsing command {}", &cmd);
|
||||
|
||||
if let Some(sub) = cmd.strip_prefix("onelauncher://") {
|
||||
Ok(handle_uri(sub).await?)
|
||||
} else {
|
||||
let path = io::canonicalize(PathBuf::from(cmd))?;
|
||||
if let Some(extension) = path.extension() {
|
||||
if extension == "zip" {
|
||||
return Ok(InternetPayload::InstallPath { path })
|
||||
}
|
||||
}
|
||||
send_message(&format!("invalid command filetype {}", path.display())).await?;
|
||||
Err(anyhow::anyhow!("invalid command filename {}", path.display()).into())
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn handle_uri(sub: &str) -> crate::Result<InternetPayload> {
|
||||
Ok(match sub.split_once('/') {
|
||||
// ://pkg/{id} - installs package id
|
||||
Some(("pkg", id)) => InternetPayload::InstallPackage { id: id.to_string() },
|
||||
// ://pack/{id} - installs pack id
|
||||
Some(("pack", id)) => InternetPayload::InstallPack { id: id.to_string() },
|
||||
// unknown uri command: error
|
||||
_ => {
|
||||
send_message(&format!("invalid command {sub}")).await?;
|
||||
return Err(anyhow::anyhow!("invalid command {sub}").into());
|
||||
}
|
||||
})
|
||||
}
|
||||
5
core/src/api/ingress.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
use crate::store::{IngressProcessType, IngressProcessor};
|
||||
|
||||
pub async fn check_ingress_feeds() -> crate::Result<bool> {
|
||||
IngressProcessor::finished(IngressProcessType::IngressFeed).await
|
||||
}
|
||||
120
core/src/api/java.rs
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
use std::path::PathBuf;
|
||||
|
||||
use reqwest::Method;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::proxy::send::{init_ingress, send_ingress};
|
||||
use crate::utils::{http::{fetch_advanced, fetch_json}, io::{self, IOError}, java::{self, get_java_version, JavaVersion}};
|
||||
use crate::State;
|
||||
|
||||
pub async fn filter_java_version(
|
||||
java_version: Option<u32>,
|
||||
) -> crate::Result<Vec<JavaVersion>> {
|
||||
let java = java::locate_java().await?;
|
||||
Ok(if let Some(java_version) = java_version {
|
||||
java.into_iter().filter(|j| {
|
||||
let jre_version = get_java_version(&j.version);
|
||||
if let Ok(jre_version) = jre_version {
|
||||
jre_version.1 == java_version
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}).collect()
|
||||
} else {
|
||||
java
|
||||
})
|
||||
}
|
||||
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn install_java(java_version: u32) -> crate::Result<PathBuf> {
|
||||
let state = State::get().await?;
|
||||
|
||||
let ingress = init_ingress(
|
||||
crate::IngressType::DownloadJava { version: java_version },
|
||||
100.0, "downloading java version").await?;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Package {
|
||||
pub download_url: String,
|
||||
pub name: PathBuf,
|
||||
}
|
||||
|
||||
send_ingress(&ingress, 0.0, Some("fetching java api")).await?;
|
||||
let packages = fetch_json::<Vec<Package>>(Method::GET, &format!(
|
||||
"https://api.azul.com/metadata/v1/zulu/packages?arch={}&java_version={}&os={}&archive_type=zip&javafx_bundled=false&java_package_type=jre&page_size=1",
|
||||
std::env::consts::ARCH, java_version, std::env::consts::OS,
|
||||
), None, None, &state.fetch_semaphore).await?;
|
||||
send_ingress(&ingress, 10.0, Some("downloading java version")).await?;
|
||||
|
||||
if let Some(download) = packages.first() {
|
||||
let file = fetch_advanced(
|
||||
Method::GET,
|
||||
&download.download_url,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some((&ingress, 80.0)),
|
||||
&state.fetch_semaphore,
|
||||
).await?;
|
||||
|
||||
let path = state.directories.java_dir().await;
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(file))
|
||||
.map_err(|err| IOError::from_zip(err))?;
|
||||
|
||||
if let Some(file) = archive.file_names().next() {
|
||||
if let Some(dir) = file.split('/').next() {
|
||||
let path = path.join(dir);
|
||||
if path.exists() { io::remove_dir_all(path).await?; }
|
||||
}
|
||||
}
|
||||
|
||||
send_ingress(&ingress, 0.0, Some("extracing java binary")).await?;
|
||||
archive.extract(&path).map_err(|err| IOError::from_zip(err))?;
|
||||
send_ingress(&ingress, 10.0, Some("extracted java binary")).await?;
|
||||
let mut base_path = path.join(download.name.file_stem().unwrap_or_default().to_string_lossy().to_string());
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
base_path = base_path
|
||||
.join(format!("zulu-{}.jre", java_version))
|
||||
.join("Contents")
|
||||
.join("Home")
|
||||
.join("bin")
|
||||
.join("java")
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
base_path = base_path.join("bin").join(java::JAVA_BIN)
|
||||
}
|
||||
|
||||
Ok(base_path)
|
||||
} else {
|
||||
Err(anyhow::anyhow!(
|
||||
"no java version found for version {}, os {}, and arch {}",
|
||||
java_version, std::env::consts::OS, std::env::consts::ARCH,
|
||||
).into())
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn check_java(path: PathBuf) -> crate::Result<Option<JavaVersion>> {
|
||||
Ok(java::check_java_instance(&path).await)
|
||||
}
|
||||
|
||||
pub async fn test_java(
|
||||
path: PathBuf,
|
||||
major: u32,
|
||||
) -> crate::Result<bool> {
|
||||
let jvm = match java::check_java_instance(&path).await {
|
||||
Some(jvm) => jvm,
|
||||
None => return Ok(false),
|
||||
};
|
||||
|
||||
let (maj, _) = get_java_version(&jvm.version)?;
|
||||
Ok(maj == major)
|
||||
}
|
||||
|
||||
pub async fn get_max_memory() -> crate::Result<u64> {
|
||||
Ok(sys_info::mem_info()
|
||||
.map_err(|_| anyhow::anyhow!("failed to get computer memory"))?.total)
|
||||
}
|
||||
222
core/src/api/logger.rs
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
//! OneLauncher log management
|
||||
|
||||
use std::io::Read;
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt};
|
||||
use serde::Serialize;
|
||||
use futures::TryFutureExt;
|
||||
use crate::data::{Credentials, Directories, MinecraftCredentials};
|
||||
use crate::prelude::ClusterPath;
|
||||
use crate::utils::io::{self, IOError};
|
||||
|
||||
// TODO: put this in the global store
|
||||
/// Core logging state and reader for OneLauncher.
|
||||
#[derive(Serialize, Debug)]
|
||||
pub struct LogManager {
|
||||
/// The log file to read as a [`String`]
|
||||
pub log_file: String,
|
||||
/// The parsed and censored output of the logfile.
|
||||
pub output: Option<LogOutput>
|
||||
}
|
||||
|
||||
impl LogManager {
|
||||
/// Initialize a new [`LogManager`].
|
||||
async fn initialize(cluster: &ClusterPath, log_file: String, clear: Option<bool>) -> crate::Result<Self> {
|
||||
Ok(Self {
|
||||
output: if clear.unwrap_or(false) {
|
||||
None
|
||||
} else {
|
||||
Some(get_output_by_file(cluster, &log_file).await?)
|
||||
},
|
||||
log_file,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a [`Vec<LogManager>`] for a specific [`ClusterPath`].
|
||||
#[tracing::instrument]
|
||||
pub async fn get_logs(cluster_path: ClusterPath, clear: Option<bool>) -> crate::Result<Vec<LogManager>> {
|
||||
let cluster_path = if let Some(c) = crate::cluster::get(&cluster_path, None).await? {
|
||||
c.cluster_path()
|
||||
} else {
|
||||
return Err(anyhow::anyhow!("cluster {} isn't managed by onelauncher!", cluster_path.to_string()).into());
|
||||
};
|
||||
|
||||
let logs_folder = Directories::cluster_logs_dir(&cluster_path).await?;
|
||||
let mut logs = Vec::new();
|
||||
if logs_folder.exists() {
|
||||
for entry in std::fs::read_dir(&logs_folder).map_err(|e| IOError::with_path(e, &logs_folder))? {
|
||||
let entry: std::fs::DirEntry = entry.map_err(|e| IOError::with_path(e, &logs_folder))?;
|
||||
let path = entry.path();
|
||||
if !path.is_file() { continue; }
|
||||
if let Some(name) = path.file_name() {
|
||||
let name = name.to_string_lossy().to_string();
|
||||
logs.push(LogManager::initialize(&cluster_path, name, clear).await);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut logs = logs.into_iter().collect::<crate::Result<Vec<LogManager>>>()?;
|
||||
logs.sort_by_key(|x| x.log_file.clone());
|
||||
Ok(logs)
|
||||
}
|
||||
|
||||
/// Delete all stored logs from a specific [`ClusterPath`].
|
||||
#[tracing::instrument]
|
||||
pub async fn delete_logs(cluster_path: ClusterPath) -> crate::Result<()> {
|
||||
let cluster_path = if let Some(c) = crate::cluster::get(&cluster_path, None).await? {
|
||||
c.cluster_path()
|
||||
} else {
|
||||
return Err(anyhow::anyhow!("cluster {} isn't managed by onelauncher!", cluster_path.to_string()).into());
|
||||
};
|
||||
|
||||
let logs_folder = Directories::cluster_logs_dir(&cluster_path).await?;
|
||||
for entry in std::fs::read_dir(&logs_folder).map_err(|e| IOError::with_path(e, &logs_folder))? {
|
||||
let entry = entry.map_err(|e| IOError::with_path(e, &logs_folder))?;
|
||||
let path = entry.path();
|
||||
if path.is_dir() { io::remove_dir_all(&path).await? }
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the [`LogManager`] for a specific [`ClusterPath`] log file.
|
||||
#[tracing::instrument]
|
||||
pub async fn get_logs_by_file(cluster_path: ClusterPath, log_file: String) -> crate::Result<LogManager> {
|
||||
let cluster_path = if let Some(c) = crate::cluster::get(&cluster_path, None).await? {
|
||||
c.cluster_path()
|
||||
} else {
|
||||
return Err(anyhow::anyhow!("cluster {} isn't managed by onelauncher!", cluster_path.to_string()).into());
|
||||
};
|
||||
|
||||
Ok(LogManager {
|
||||
output: Some(get_output_by_file(&cluster_path, &log_file).await?),
|
||||
log_file,
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the default [`LogCursor`] for a [`ClusterPath`].
|
||||
#[tracing::instrument]
|
||||
pub async fn get_log_cursor(cluster_path: ClusterPath, cursor: u64) -> crate::Result<LogCursor> {
|
||||
get_live_log_cursor(cluster_path, "latest.log", cursor).await
|
||||
}
|
||||
|
||||
/// Get a live [`LogCursor`] for a [`ClusterPath`]'s log file.
|
||||
#[tracing::instrument]
|
||||
pub async fn get_live_log_cursor(cluster_path: ClusterPath, log_file: &str, mut cursor: u64) -> crate::Result<LogCursor> {
|
||||
let cluster_path = if let Some(c) = crate::cluster::get(&cluster_path, None).await? {
|
||||
c.cluster_path()
|
||||
} else {
|
||||
return Err(anyhow::anyhow!("cluster {} isn't managed by onelauncher!", cluster_path.to_string()).into());
|
||||
};
|
||||
|
||||
let state = crate::State::get().await?;
|
||||
let logs_folder = Directories::cluster_logs_dir(&cluster_path).await?;
|
||||
let path = logs_folder.join(log_file);
|
||||
if !path.exists() { return Ok(LogCursor { cursor: 0, new: false, output: LogOutput("".to_string()) }); }
|
||||
|
||||
let mut file = tokio::fs::File::open(&path).await.map_err(|e| IOError::with_path(e, &path))?;
|
||||
let metadata = file.metadata().await.map_err(|e| IOError::with_path(e, &path))?;
|
||||
let mut new = false;
|
||||
|
||||
if cursor > metadata.len() {
|
||||
cursor = 0;
|
||||
new = true;
|
||||
}
|
||||
|
||||
let mut buf = Vec::new();
|
||||
file.seek(std::io::SeekFrom::Start(cursor)).map_err(|e| IOError::with_path(e, &path)).await?;
|
||||
let bytes_read = file.read_to_end(&mut buf).map_err(|e| IOError::with_path(e, &path)).await?;
|
||||
let output = String::from_utf8_lossy(&buf).to_string();
|
||||
let cursor = cursor + bytes_read as u64;
|
||||
let creds: Vec<MinecraftCredentials> = state.users.read().await.users.clone().into_values().collect();
|
||||
let output = LogOutput::censor_secrets(output, &creds, None);
|
||||
Ok(LogCursor { cursor, new, output })
|
||||
}
|
||||
|
||||
/// Delete a specific minecraft log file.
|
||||
#[tracing::instrument]
|
||||
pub async fn delete_logs_by_file(cluster_path: ClusterPath, log_file: &str) -> crate::Result<()> {
|
||||
let cluster_path = if let Some(c) = crate::cluster::get(&cluster_path, None).await? {
|
||||
c.cluster_path()
|
||||
} else {
|
||||
return Err(anyhow::anyhow!("cluster {} isn't managed by onelauncher!", cluster_path.to_string()).into());
|
||||
};
|
||||
|
||||
let logs_folder = Directories::cluster_logs_dir(&cluster_path).await?;
|
||||
let path = logs_folder.join(log_file);
|
||||
io::remove_dir_all(&path).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get a specific [`ClusterPath`] log file's [`LogOutput`].
|
||||
#[tracing::instrument]
|
||||
pub async fn get_output_by_file(cluster_path: &ClusterPath, log_file: &str) -> crate::Result<LogOutput> {
|
||||
let state = crate::State::get().await?;
|
||||
let logs_folder = Directories::cluster_logs_dir(cluster_path).await?;
|
||||
let path = logs_folder.join(log_file);
|
||||
let credentials: Vec<MinecraftCredentials> = state.users.read().await.users.clone().into_values().collect();
|
||||
|
||||
// todo: make this a utility function
|
||||
if let Some(ext) = path.extension() {
|
||||
let mut file = std::fs::File::open(&path).map_err(|e| IOError::with_path(e, &path))?;
|
||||
let mut contents = [0; 1024];
|
||||
let mut result = String::new();
|
||||
|
||||
if ext == "gz" {
|
||||
let mut gz = flate2::read::GzDecoder::new(std::io::BufReader::new(file));
|
||||
|
||||
while gz.read(&mut contents).map_err(|e| IOError::with_path(e, &path))? > 0 {
|
||||
result.push_str(&String::from_utf8_lossy(&contents));
|
||||
contents = [0; 1024];
|
||||
}
|
||||
|
||||
return Ok(LogOutput::censor_secrets(result, &credentials, None));
|
||||
} else if ext == "log" {
|
||||
while file.read(&mut contents).map_err(|e| IOError::with_path(e, &path))? > 0 {
|
||||
result.push_str(&String::from_utf8_lossy(&contents));
|
||||
contents = [0; 1024];
|
||||
}
|
||||
|
||||
return Ok(LogOutput::censor_secrets(result, &credentials, None));
|
||||
}
|
||||
}
|
||||
|
||||
Err(anyhow::anyhow!("log file extension {} not supported", path.display()).into())
|
||||
}
|
||||
|
||||
/// The log cursor used to parse logs passed into [`LogManager`].
|
||||
#[derive(Serialize, Debug)]
|
||||
pub struct LogCursor {
|
||||
/// The cursor ID.
|
||||
pub cursor: u64,
|
||||
/// The [`LogOutput`] associated with this cursor.
|
||||
pub output: LogOutput,
|
||||
/// Whether or not this corresponds is a new log file.
|
||||
pub new: bool,
|
||||
}
|
||||
|
||||
/// The log output, a wrapper around [`String`], with utilities for parsing and censoring log contents.
|
||||
#[derive(Serialize, Debug)]
|
||||
#[serde(transparent)]
|
||||
pub struct LogOutput(String);
|
||||
|
||||
impl LogOutput {
|
||||
/// Censor user secrets because sometimes mclogs misses them, including username, realname and minecraft credentials.
|
||||
pub fn censor_secrets(mut output: String, credentials: &Vec<MinecraftCredentials>, credentials_store: Option<Credentials>) -> Self {
|
||||
let username = whoami::username();
|
||||
let realname = whoami::realname();
|
||||
output = output.replace(&format!("/{}/", username), "/{ENV_USERNAME}/");
|
||||
output = output.replace(&format!("\\{}\\", username), "\\{ENV_USERNAME}\\");
|
||||
output = output.replace(&format!("/{}/", realname), "/{ENV_REALNAME}/");
|
||||
output = output.replace(&format!("\\{}\\", realname), "\\{ENV_REALNAME}\\");
|
||||
|
||||
for cred in credentials {
|
||||
output = output.replace(&cred.access_token, "{MC_ACCESS_TOKEN}");
|
||||
output = output.replace(&cred.username, "{MC_USERNAME}");
|
||||
output = output.replace(&cred.id.as_simple().to_string(), "{MC_UUID}");
|
||||
output = output.replace(&cred.id.as_hyphenated().to_string(), "{MC_UUID}");
|
||||
}
|
||||
|
||||
Self(output)
|
||||
}
|
||||
}
|
||||
61
core/src/api/metadata.rs
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
//! Metadata management interface
|
||||
|
||||
use crate::State;
|
||||
pub use interpulse::api::minecraft::VersionManifest;
|
||||
pub use interpulse::api::modded::Manifest;
|
||||
|
||||
/// Get a [`VersionManifest`] for all available Minecraft versions.
|
||||
#[tracing::instrument]
|
||||
pub async fn get_minecraft_versions() -> crate::Result<VersionManifest> {
|
||||
let state = State::get().await?;
|
||||
let meta = state.metadata.read().await.minecraft.clone();
|
||||
|
||||
Ok(meta)
|
||||
}
|
||||
|
||||
/// Get a [`Manifest`] for all available Fabric versions.
|
||||
#[tracing::instrument]
|
||||
pub async fn get_fabric_versions() -> crate::Result<Manifest> {
|
||||
let state = State::get().await?;
|
||||
let meta = state.metadata.read().await.fabric.clone();
|
||||
|
||||
Ok(meta)
|
||||
}
|
||||
|
||||
/// Get a [`Manifest`] for all available Quilt versions.
|
||||
#[tracing::instrument]
|
||||
pub async fn get_quilt_versions() -> crate::Result<Manifest> {
|
||||
let state = State::get().await?;
|
||||
let meta = state.metadata.read().await.quilt.clone();
|
||||
|
||||
Ok(meta)
|
||||
}
|
||||
|
||||
/// Get a [`Manifest`] for all available Forge versions.
|
||||
#[tracing::instrument]
|
||||
pub async fn get_forge_versions() -> crate::Result<Manifest> {
|
||||
let state = State::get().await?;
|
||||
let meta = state.metadata.read().await.forge.clone();
|
||||
|
||||
Ok(meta)
|
||||
}
|
||||
|
||||
/// Get a [`Manifest`] for all available NeoForge versions.
|
||||
#[tracing::instrument]
|
||||
pub async fn get_neoforge_versions() -> crate::Result<Manifest> {
|
||||
let state = State::get().await?;
|
||||
let meta = state.metadata.read().await.neoforge.clone();
|
||||
|
||||
Ok(meta)
|
||||
}
|
||||
|
||||
/// Get a [`Manifest`] for all available Legacy Fabric versions.
|
||||
#[tracing::instrument]
|
||||
pub async fn get_legacy_fabric_versions() -> crate::Result<Manifest> {
|
||||
let state = State::get().await?;
|
||||
let meta = state.metadata.read().await.legacy_fabric.clone();
|
||||
|
||||
Ok(meta)
|
||||
}
|
||||
|
||||
|
||||
77
core/src/api/minecraft.rs
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
//! Authentication flow manager
|
||||
|
||||
use crate::store::{MinecraftCredentials, MinecraftLogin, State};
|
||||
|
||||
/// Begin a Microsoft authentication flow.
|
||||
#[tracing::instrument]
|
||||
pub async fn begin() -> crate::Result<MinecraftLogin> {
|
||||
let state = State::get().await?;
|
||||
let mut users = state.users.write().await;
|
||||
|
||||
users.begin().await
|
||||
}
|
||||
|
||||
/// Complete a Microsoft authentication flow to recieve [`MinecraftCredentials`].
|
||||
#[tracing::instrument]
|
||||
pub async fn finish(code: &str, flow: MinecraftLogin) -> crate::Result<MinecraftCredentials> {
|
||||
let state = State::get().await?;
|
||||
let mut users = state.users.write().await;
|
||||
|
||||
users.finish(code, flow).await
|
||||
}
|
||||
|
||||
/// Get the current default user if it exists by [`uuid::Uuid`].
|
||||
#[tracing::instrument]
|
||||
pub async fn get_default_user() -> crate::Result<Option<uuid::Uuid>> {
|
||||
let state = State::get().await?;
|
||||
let users = state.users.read().await;
|
||||
|
||||
Ok(users.default_user)
|
||||
}
|
||||
|
||||
/// Set the current default user by [`uuid::Uuid`].
|
||||
#[tracing::instrument]
|
||||
pub async fn set_default_user(user: uuid::Uuid) -> crate::Result<()> {
|
||||
let user = get_user(user).await?;
|
||||
let state = State::get().await?;
|
||||
let mut users = state.users.write().await;
|
||||
|
||||
users.default_user = Some(user.id);
|
||||
users.save().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove a user account by its [`uuid::Uuid`] from the global store.
|
||||
#[tracing::instrument]
|
||||
pub async fn remove_user(user: uuid::Uuid) -> crate::Result<()> {
|
||||
let state = State::get().await?;
|
||||
let mut users = state.users.write().await;
|
||||
|
||||
users.remove(user).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// TODO: Store this securely in stronghold
|
||||
/// Get a list of user [`MinecraftCredentials`].
|
||||
#[tracing::instrument]
|
||||
pub async fn users() -> crate::Result<Vec<MinecraftCredentials>> {
|
||||
let state = State::get().await?;
|
||||
let users = state.users.read().await;
|
||||
|
||||
Ok(users.users.values().cloned().collect())
|
||||
}
|
||||
|
||||
/// Get a specifc user's [`MinecraftCredentials`] by their [`uuid::Uuid`].
|
||||
/// Use [`crate::store::MinecraftState#refresh`] instead.
|
||||
#[tracing::instrument]
|
||||
pub async fn get_user(user: uuid::Uuid) -> crate::Result<MinecraftCredentials> {
|
||||
let state = State::get().await?;
|
||||
let users = state.users.read().await;
|
||||
|
||||
let user = users.users.get(&user)
|
||||
.ok_or_else(|| anyhow::anyhow!("failed to get nonexistent user with uuid {user}"))?.clone();
|
||||
|
||||
Ok(user)
|
||||
}
|
||||
34
core/src/api/mod.rs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
//! **OneLauncher API**
|
||||
//!
|
||||
//! API for interacting with our Rust core.
|
||||
|
||||
pub mod java;
|
||||
pub mod proxy;
|
||||
pub mod handler;
|
||||
pub mod settings;
|
||||
pub mod ingress;
|
||||
pub mod processor;
|
||||
pub mod minecraft;
|
||||
pub mod metadata;
|
||||
pub mod logger;
|
||||
pub mod package;
|
||||
pub mod cluster;
|
||||
|
||||
pub mod data {
|
||||
pub use crate::store::{
|
||||
Credentials, MinecraftCredentials, Directories, InitHooks, JavaOptions,
|
||||
PackageData, Memory, Loader, ClusterMeta, Settings, Theme, Resolution,
|
||||
PackageType, ManagedDependency, ManagedPackage, ManagedUser, ManagedVersion,
|
||||
};
|
||||
}
|
||||
|
||||
pub mod prelude {
|
||||
pub use crate::{
|
||||
data::*,
|
||||
proxy::InternetPayload,
|
||||
java, metadata, minecraft, package, processor,
|
||||
settings, store::JavaVersions, store::ClusterPath,
|
||||
utils::io::{canonicalize, IOError}, utils::java::JavaVersion,
|
||||
State,
|
||||
};
|
||||
}
|
||||
110
core/src/api/processor.rs
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
//! Process management interface
|
||||
|
||||
use uuid::Uuid;
|
||||
use crate::store::{ProcessorChild, ClusterPath};
|
||||
pub use crate::store::{InitHooks, JavaOptions, Memory, Cluster, Settings, Resolution, State};
|
||||
|
||||
/// check whether or not a process has completed by its [`Uuid`].
|
||||
#[tracing::instrument]
|
||||
pub async fn uuid_is_finished(uuid: &Uuid) -> crate::Result<bool> {
|
||||
Ok(uuid_exit_status(uuid).await?.is_some())
|
||||
}
|
||||
|
||||
/// check the exit status of a process by its [`Uuid`].
|
||||
#[tracing::instrument]
|
||||
pub async fn uuid_exit_status(uuid: &Uuid) -> crate::Result<Option<i32>> {
|
||||
let state = State::get().await?;
|
||||
let processor = state.processor.read().await;
|
||||
processor.exit_status(uuid).await
|
||||
}
|
||||
|
||||
/// get all process [`Uuid`]s.
|
||||
#[tracing::instrument]
|
||||
pub async fn get_uuids() -> crate::Result<Vec<Uuid>> {
|
||||
let state = State::get().await?;
|
||||
let processor = state.processor.read().await;
|
||||
Ok(processor.keys())
|
||||
}
|
||||
|
||||
/// get all running process [`Uuid`]s.
|
||||
#[tracing::instrument]
|
||||
pub async fn get_running() -> crate::Result<Vec<Uuid>> {
|
||||
let state = State::get().await?;
|
||||
let processor = state.processor.read().await;
|
||||
processor.running().await
|
||||
}
|
||||
|
||||
/// get all running process' [`ClusterPath`]s.
|
||||
#[tracing::instrument]
|
||||
pub async fn get_running_cluster_paths() -> crate::Result<Vec<ClusterPath>>
|
||||
{
|
||||
let state = State::get().await?;
|
||||
let processor = state.processor.read().await;
|
||||
processor.running_cluster_paths().await
|
||||
}
|
||||
|
||||
/// get all running process' [`Cluster`]s.
|
||||
#[tracing::instrument]
|
||||
pub async fn get_running_clusters() -> crate::Result<Vec<Cluster>> {
|
||||
let state = State::get().await?;
|
||||
let processor = state.processor.read().await;
|
||||
processor.running_clusters().await
|
||||
}
|
||||
|
||||
/// get all processes by a [`ClusterPath`].
|
||||
#[tracing::instrument]
|
||||
pub async fn get_uuids_by_cluster_path(
|
||||
cluster_path: ClusterPath,
|
||||
) -> crate::Result<Vec<Uuid>> {
|
||||
let state = State::get().await?;
|
||||
let processor = state.processor.read().await;
|
||||
processor.running_cluster(cluster_path).await
|
||||
}
|
||||
|
||||
/// kill an existing and running process by its [`Uuid`]
|
||||
#[tracing::instrument]
|
||||
pub async fn kill_by_uuid(uuid: &Uuid) -> crate::Result<()> {
|
||||
let state = State::get().await?;
|
||||
let processor = state.processor.read().await;
|
||||
|
||||
if let Some(process) = processor.get(uuid) {
|
||||
let mut process = process.write().await;
|
||||
kill(&mut process).await
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// wait for a child process to finish running its manager by its [`Uuid`].
|
||||
#[tracing::instrument]
|
||||
pub async fn wait_for_by_uuid(uuid: &Uuid) -> crate::Result<()> {
|
||||
let state = State::get().await?;
|
||||
let processor = state.processor.read().await;
|
||||
|
||||
if let Some(process) = processor.get(uuid) {
|
||||
let mut process = process.write().await;
|
||||
wait_for(&mut process).await
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// kill an existing and running process
|
||||
#[tracing::instrument(skip(process))]
|
||||
pub async fn kill(process: &mut ProcessorChild) -> crate::Result<()> {
|
||||
process.current_child.write().await.kill().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// wait for a child process to finish running its manager
|
||||
#[tracing::instrument(skip(process))]
|
||||
pub async fn wait_for(process: &mut ProcessorChild) -> crate::Result<()> {
|
||||
process
|
||||
.manager
|
||||
.take()
|
||||
.ok_or_else(||anyhow::anyhow!("manager already completed for process {}", process.uuid))?
|
||||
.await?
|
||||
.map_err(|err| anyhow::anyhow!("failed to run minecraft: {err}"))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
254
core/src/api/proxy/mod.rs
Normal file
|
|
@ -0,0 +1,254 @@
|
|||
//! Proxy for Tauri/CLI specific features and communication
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::{OnceCell, RwLock};
|
||||
use uuid::Uuid;
|
||||
use std::{collections::HashMap, path::PathBuf, sync::Arc};
|
||||
|
||||
use crate::store::{ClusterPath, IngressProcessor};
|
||||
|
||||
pub mod send;
|
||||
pub mod utils;
|
||||
pub use utils::*;
|
||||
|
||||
static PROXY_STATE: OnceCell<Arc<ProxyState>> = OnceCell::const_new();
|
||||
pub struct ProxyState {
|
||||
#[cfg(feature = "tauri")]
|
||||
pub app: tauri::AppHandle,
|
||||
pub ingress_feeds: RwLock<HashMap<Uuid, Ingress>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, Clone)]
|
||||
pub struct Ingress {
|
||||
pub ingress_uuid: Uuid,
|
||||
pub message: String,
|
||||
pub ingress_type: IngressType,
|
||||
pub total: f64,
|
||||
pub current: f64,
|
||||
#[serde(skip)]
|
||||
pub last_sent: f64,
|
||||
#[cfg(feature = "cli")]
|
||||
#[serde(skip)]
|
||||
pub cli: indicatif::ProgressBar,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, Clone)]
|
||||
pub struct IngressId(Uuid);
|
||||
|
||||
impl Drop for IngressId {
|
||||
fn drop(&mut self) {
|
||||
let ingress_uuid = self.0;
|
||||
tokio::spawn(async move {
|
||||
if let Ok(proxy_state) = ProxyState::get().await {
|
||||
let mut ingress_feeds = proxy_state.ingress_feeds.write().await;
|
||||
#[cfg(any(feature = "tauri", feature = "cli"))]
|
||||
if let Some(ingress) = ingress_feeds.remove(&ingress_uuid) {
|
||||
#[cfg(feature = "cli")]
|
||||
{
|
||||
let cli = ingress.cli;
|
||||
cli.finish();
|
||||
}
|
||||
|
||||
#[cfg(feature = "tauri")]
|
||||
{
|
||||
let ingress_feed_uuid = ingress.ingress_uuid;
|
||||
let event = ingress.ingress_type.clone();
|
||||
let fraction = ingress.current / ingress.total;
|
||||
|
||||
use tauri::Manager;
|
||||
let _ = proxy_state.app.emit("ingress", IngressPayload {
|
||||
fraction: None,
|
||||
message: "Complete".to_string(),
|
||||
event,
|
||||
ingress_uuid,
|
||||
});
|
||||
|
||||
tracing::trace!("exited at {fraction} for ingress: {:?}", ingress_uuid);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "tauri", feature = "cli")))]
|
||||
ingress_feeds.remove(&ingress_uuid);
|
||||
}
|
||||
|
||||
if crate::State::initalized() {
|
||||
let _ = IngressProcessor::finish(
|
||||
crate::store::IngressProcessType::IngressFeed,
|
||||
ingress_uuid,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl ProxyState {
|
||||
#[cfg(feature = "tauri")]
|
||||
pub async fn initialize(app: tauri::AppHandle) -> crate::Result<Arc<Self>> {
|
||||
PROXY_STATE
|
||||
.get_or_try_init(|| async {
|
||||
Ok(Arc::new(Self {
|
||||
app,
|
||||
ingress_feeds: RwLock::new(HashMap::new()),
|
||||
}))
|
||||
})
|
||||
.await
|
||||
.cloned()
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "tauri"))]
|
||||
pub async fn initialize() -> crate::Result<Arc<Self>> {
|
||||
PROXY_STATE
|
||||
.get_or_try_init(|| async {
|
||||
Ok(Arc::new(Self {
|
||||
ingress_feeds: RwLock::new(HashMap::new()),
|
||||
}))
|
||||
})
|
||||
.await
|
||||
.cloned()
|
||||
}
|
||||
|
||||
#[cfg(feature = "tauri")]
|
||||
pub async fn get_main_window() -> crate::Result<tauri::WebviewWindow> {
|
||||
use tauri::Manager;
|
||||
let value = Self::get().await?;
|
||||
Ok(value.app.get_webview_window("main").unwrap())
|
||||
}
|
||||
|
||||
#[cfg(feature = "tauri")]
|
||||
pub async fn get() -> crate::Result<Arc<Self>> {
|
||||
Ok(PROXY_STATE.get().ok_or(ProxyError::NotInitialized)?.clone())
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "tauri"))]
|
||||
pub async fn get() -> crate::Result<Arc<Self>> {
|
||||
Self::initialize().await
|
||||
}
|
||||
|
||||
pub async fn list_ingress_feeds() -> crate::Result<HashMap<Uuid, Ingress>> {
|
||||
let value = Self::get().await?;
|
||||
let read = value.ingress_feeds.read().await;
|
||||
|
||||
let mut display_list: HashMap<Uuid, Ingress> = HashMap::new();
|
||||
for (uuid, ingress) in read.iter() {
|
||||
display_list.insert(*uuid, ingress.clone());
|
||||
}
|
||||
|
||||
Ok(display_list)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, Hash, PartialEq, Eq)]
|
||||
#[serde(tag = "type")]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum IngressType {
|
||||
Initialize,
|
||||
DownloadJava {
|
||||
version: u32,
|
||||
},
|
||||
DownloadLoader {
|
||||
cluster_path: PathBuf,
|
||||
cluster_name: String,
|
||||
},
|
||||
SyncCluster {
|
||||
cluster_path: PathBuf,
|
||||
cluster_name: String,
|
||||
},
|
||||
CopyCluster {
|
||||
import: PathBuf,
|
||||
cluster_name: String,
|
||||
},
|
||||
SyncConfig {
|
||||
new_path: PathBuf,
|
||||
},
|
||||
Archival {
|
||||
cluster_path: PathBuf,
|
||||
cluster_name: String,
|
||||
},
|
||||
DownloadPackage {
|
||||
cluster_path: PathBuf,
|
||||
package_name: String,
|
||||
icon: Option<PathBuf>,
|
||||
package_id: Option<String>,
|
||||
package_version: Option<String>
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone)]
|
||||
pub struct IngressPayload {
|
||||
pub event: IngressType,
|
||||
pub ingress_uuid: Uuid,
|
||||
pub fraction: Option<f64>,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone)]
|
||||
pub struct OfflinePayload {
|
||||
pub offline: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone)]
|
||||
pub struct MessagePayload {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone)]
|
||||
#[serde(tag = "event")]
|
||||
pub enum InternetPayload {
|
||||
InstallPackage {
|
||||
id: String,
|
||||
},
|
||||
InstallPack {
|
||||
id: String,
|
||||
},
|
||||
InstallPath {
|
||||
path: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone)]
|
||||
pub struct ProcessPayload {
|
||||
pub uuid: Uuid,
|
||||
pub pid: u32,
|
||||
pub event: ProcessPayloadType,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ProcessPayloadType {
|
||||
Started,
|
||||
Modified,
|
||||
Finished,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone)]
|
||||
pub struct ClusterPayload {
|
||||
pub uuid: Uuid,
|
||||
pub cluster_path: ClusterPath,
|
||||
pub path: PathBuf,
|
||||
pub name: String,
|
||||
pub event: ClusterPayloadType,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ClusterPayloadType {
|
||||
Created,
|
||||
Inserted,
|
||||
Synced,
|
||||
Edited,
|
||||
Deleted,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ProxyError {
|
||||
#[error("event state was not initialized!")]
|
||||
NotInitialized,
|
||||
|
||||
#[error("non-existant ingress of key: {0}")]
|
||||
NoIngressFound(Uuid),
|
||||
|
||||
#[cfg(feature = "tauri")]
|
||||
#[error("Tauri error: {0}")]
|
||||
TauriError(#[from] tauri::Error),
|
||||
}
|
||||
207
core/src/api/proxy/send.rs
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
use super::IngressId;
|
||||
use crate::api::proxy::{ProxyError, Ingress, IngressType, ProcessPayloadType, ClusterPayloadType, InternetPayload};
|
||||
use crate::store::{ClusterPath, IngressProcessType, IngressProcessor};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[cfg(feature = "tauri")]
|
||||
use crate::api::proxy::{IngressPayload, ProcessPayload, ClusterPayload, MessagePayload};
|
||||
|
||||
#[cfg(feature = "tauri")]
|
||||
use tauri::Manager;
|
||||
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn init_ingress(
|
||||
ingress_type: IngressType,
|
||||
total: f64,
|
||||
title: &str,
|
||||
) -> crate::Result<IngressId> {
|
||||
let key = init_ingress_internal(ingress_type, total, title).await?;
|
||||
IngressProcessor::add_ingress(IngressProcessType::IngressFeed, key.0).await?;
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
#[cfg(feature = "cli")]
|
||||
const CLI_TOTAL_INGRESS: u64 = 1000;
|
||||
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn init_ingress_internal(
|
||||
ingress_type: IngressType,
|
||||
total: f64,
|
||||
title: &str,
|
||||
) -> crate::Result<IngressId> {
|
||||
let proxy_state = crate::ProxyState::get().await?;
|
||||
let key = IngressId(Uuid::new_v4());
|
||||
|
||||
proxy_state.ingress_feeds.write().await.insert(key.0, Ingress {
|
||||
ingress_uuid: key.0,
|
||||
message: title.to_string(),
|
||||
total,
|
||||
current: 0.0,
|
||||
last_sent: 0.0,
|
||||
ingress_type,
|
||||
#[cfg(feature = "cli")]
|
||||
cli: {
|
||||
let pb = indicatif::ProgressBar::new(CLI_TOTAL_INGRESS);
|
||||
pb.set_position(0);
|
||||
pb.set_style(indicatif::ProgressStyle::default_bar().template(
|
||||
"{spinner:.green}, [{elapsed_precise}] [{bar:.lime/green}] {pos}/{len} {msg}"
|
||||
).unwrap().progress_chars("#>-"));
|
||||
pb
|
||||
},
|
||||
});
|
||||
|
||||
send_ingress(&key, 0.0, None).await?;
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
pub async fn init_or_edit_ingress(
|
||||
id: Option<IngressId>,
|
||||
ingress_type: IngressType,
|
||||
total: f64,
|
||||
title: &str,
|
||||
) -> crate::Result<IngressId> {
|
||||
if let Some(id) = id {
|
||||
edit_ingress(&id, ingress_type, total, title).await?;
|
||||
|
||||
Ok(id)
|
||||
} else {
|
||||
init_ingress(ingress_type, total, title).await
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn edit_ingress(
|
||||
id: &IngressId,
|
||||
ingress_type: IngressType,
|
||||
total: f64,
|
||||
title: &str,
|
||||
) -> crate::Result<()> {
|
||||
let proxy_state = crate::ProxyState::get().await?;
|
||||
|
||||
if let Some(ingress) = proxy_state.ingress_feeds.write().await.get_mut(&id.0) {
|
||||
ingress.ingress_type = ingress_type;
|
||||
ingress.total = total;
|
||||
ingress.message = title.to_string();
|
||||
ingress.current = 0.0;
|
||||
ingress.last_sent = 0.0;
|
||||
#[cfg(feature = "cli")]
|
||||
{ ingress.cli.reset(); }
|
||||
};
|
||||
|
||||
send_ingress(id, 0.0, None).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(unused_variables)]
|
||||
#[tracing::instrument(level = "debug")]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn send_ingress(
|
||||
key: &IngressId,
|
||||
increment: f64,
|
||||
message: Option<&str>,
|
||||
) -> crate::Result<()> {
|
||||
let proxy_state = crate::ProxyState::get().await?;
|
||||
let mut ingress = proxy_state.ingress_feeds.write().await;
|
||||
let ingress = match ingress.get_mut(&key.0) {
|
||||
Some(f) => f,
|
||||
None => {
|
||||
return Err(ProxyError::NoIngressFound(key.0).into());
|
||||
}
|
||||
};
|
||||
|
||||
ingress.current += increment;
|
||||
let display = ingress.current / ingress.total;
|
||||
let display_conv = if display >= 1.0 {
|
||||
None
|
||||
} else {
|
||||
Some(display)
|
||||
};
|
||||
|
||||
if f64::abs(display - ingress.last_sent) > 0.005 {
|
||||
#[cfg(feature = "cli")]
|
||||
{
|
||||
ingress.cli.set_message(message.map(|x| x.to_string()).unwrap_or(ingress.message.clone()));
|
||||
ingress.cli.set_position((display * CLI_TOTAL_INGRESS as f64).round() as u64);
|
||||
}
|
||||
|
||||
#[cfg(feature = "tauri")]
|
||||
proxy_state.app.emit("ingress", IngressPayload {
|
||||
fraction: display_conv,
|
||||
message: message.unwrap_or(&ingress.message).to_string(),
|
||||
event: ingress.ingress_type.clone(),
|
||||
ingress_uuid: ingress.ingress_uuid,
|
||||
}).map_err(ProxyError::from)?;
|
||||
|
||||
ingress.last_sent = display;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn send_message(message: &str) -> crate::Result<()> {
|
||||
#[cfg(feature = "tauri")]
|
||||
{
|
||||
let proxy_state = crate::ProxyState::get().await?;
|
||||
proxy_state.app.emit("message", MessagePayload { message: message.to_string() }).map_err(ProxyError::from)?;
|
||||
}
|
||||
|
||||
tracing::warn!("{}", message);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn send_offline(offline: bool) -> crate::Result<()> {
|
||||
#[cfg(feature = "tauri")]
|
||||
{
|
||||
let proxy_state = crate::ProxyState::get().await?;
|
||||
proxy_state.app.emit("offline", offline).map_err(ProxyError::from)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn send_internet(internet: InternetPayload) -> crate::Result<()> {
|
||||
tracing::debug!("operation {}", serde_json::to_string(&internet)?);
|
||||
#[cfg(feature = "tauri")]
|
||||
{
|
||||
let proxy_state = crate::ProxyState::get().await?;
|
||||
proxy_state.app.emit("internet", internet).map_err(ProxyError::from)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn send_process(
|
||||
uuid: Uuid,
|
||||
pid: u32,
|
||||
event: ProcessPayloadType,
|
||||
message: &str,
|
||||
) -> crate::Result<()> {
|
||||
#[cfg(feature = "tauri")]
|
||||
{
|
||||
let proxy_state = crate::ProxyState::get().await?;
|
||||
proxy_state.app.emit("process", ProcessPayload { uuid, pid, event, message: message.to_string() }).map_err(ProxyError::from)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn send_cluster(
|
||||
uuid: Uuid,
|
||||
cluster_path: &ClusterPath,
|
||||
name: &str,
|
||||
event: ClusterPayloadType,
|
||||
) -> crate::Result<()> {
|
||||
#[cfg(feature = "tauri")]
|
||||
{
|
||||
let path = cluster_path.full_path().await?;
|
||||
let proxy_state = crate::ProxyState::get().await?;
|
||||
proxy_state.app.emit("cluster", ClusterPayload {
|
||||
uuid,
|
||||
cluster_path: cluster_path.clone(),
|
||||
path,
|
||||
name: name.to_string(),
|
||||
event,
|
||||
}).map_err(ProxyError::from)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
77
core/src/api/proxy/utils.rs
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
use futures::prelude::*;
|
||||
|
||||
use crate::proxy::send::send_ingress;
|
||||
use crate::proxy::IngressId;
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! count {
|
||||
() => (0usize);
|
||||
( $x:tt $($xs:tt)* ) => (1usize + $crate::count!($($xs)*));
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! ingress_join {
|
||||
($key:expr, $total:expr, $msg:expr; $($task:expr $(,)?)+) => {
|
||||
{
|
||||
let key = $key;
|
||||
let msg: Option<&str> = $msg;
|
||||
let num_futures = $crate::count!($($task)*);
|
||||
let i = $total / num_futures as f64;
|
||||
|
||||
paste::paste! {
|
||||
$( let [ <unique_name $task> ] = {
|
||||
{
|
||||
let key = key.clone();
|
||||
let msg = msg.clone();
|
||||
async move {
|
||||
let res = $task.await;
|
||||
if let Some(key) = key {
|
||||
$crate::api::proxy::send::send_ingress(key, i, msg).await?;
|
||||
}
|
||||
res
|
||||
}
|
||||
}
|
||||
};)+
|
||||
}
|
||||
|
||||
paste::paste! {
|
||||
tokio::try_join! (
|
||||
$( [ <unique_name $task>] ),+
|
||||
)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// TryStreamExt concurrently for Ingress feeds
|
||||
#[tracing::instrument(skip(stream, f))]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn ingress_try_for_each<I, F, Fut, T>(
|
||||
stream: I,
|
||||
limit: Option<usize>,
|
||||
key: Option<&IngressId>,
|
||||
total: f64,
|
||||
num_futs: usize,
|
||||
message: Option<&str>,
|
||||
f: F,
|
||||
) -> crate::Result<()>
|
||||
where
|
||||
I: futures::TryStreamExt<Error = crate::Error> + TryStream<Ok = T>,
|
||||
F: FnMut(T) -> Fut + Send,
|
||||
Fut: Future<Output = crate::Result<()>> + Send,
|
||||
T: Send,
|
||||
{
|
||||
let mut f = f;
|
||||
stream.try_for_each_concurrent(limit, |item| {
|
||||
let f = f(item);
|
||||
async move {
|
||||
f.await?;
|
||||
if let Some(key) = key {
|
||||
send_ingress(key, total / (num_futs as f64), message).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
180
core/src/api/settings.rs
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
//! Settings Management
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use tokio::sync::RwLock;
|
||||
use crate::proxy::send::{init_ingress, send_ingress};
|
||||
use crate::store::{self, Clusters, Directories, Settings};
|
||||
use crate::State;
|
||||
|
||||
/// gets a [`Settings`] object state.
|
||||
#[tracing::instrument]
|
||||
pub async fn get() -> crate::Result<Settings> {
|
||||
let state = State::get().await?;
|
||||
let settings = state.settings.read().await;
|
||||
Ok(settings.clone())
|
||||
}
|
||||
|
||||
/// sets a [`Settings`] object state.
|
||||
#[tracing::instrument]
|
||||
pub async fn set(settings: Settings) -> crate::Result<()> {
|
||||
let state = State::get().await?;
|
||||
|
||||
if settings.config_dir != state.settings.read().await.config_dir {
|
||||
return Err(anyhow::anyhow!("ccannot change config directory as a setting").into());
|
||||
}
|
||||
|
||||
let (io, fetch) = async {
|
||||
let read = state.settings.read().await;
|
||||
(
|
||||
settings.max_async_io_operations != read.max_async_io_operations,
|
||||
settings.max_async_fetches != read.max_async_fetches,
|
||||
)
|
||||
}.await;
|
||||
|
||||
let discord_rpc = {
|
||||
let read = state.settings.read().await;
|
||||
settings.disable_discord != read.disable_discord
|
||||
};
|
||||
|
||||
{
|
||||
*state.settings.write().await = settings;
|
||||
}
|
||||
|
||||
if discord_rpc {
|
||||
state.discord_rpc.clear(true).await?;
|
||||
}
|
||||
|
||||
if io {
|
||||
state.reset_io_semaphore().await;
|
||||
}
|
||||
|
||||
if fetch {
|
||||
state.reset_fetch_semaphore().await;
|
||||
}
|
||||
|
||||
State::sync().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// sets the config and caches directory, this can have side effects.
|
||||
pub async fn set_directory(new: PathBuf) -> crate::Result<()> {
|
||||
tracing::trace!("changing config directory to {}", new.display());
|
||||
|
||||
if !new.is_dir() {
|
||||
return Err(anyhow::anyhow!("new config directory {} is not a folder!", new.display()).into());
|
||||
}
|
||||
|
||||
if !is_writable(new.clone()).await? {
|
||||
return Err(anyhow::anyhow!("new config directory {} is not writeable", new.display()).into());
|
||||
}
|
||||
|
||||
let ingress = init_ingress(
|
||||
crate::IngressType::SyncConfig { new_path: new.clone() },
|
||||
100.0, "syncing and changing configuration directory",
|
||||
).await?;
|
||||
|
||||
tracing::trace!("changing config directory, overriding state write access");
|
||||
let mut state_write = State::get_and_write().await?;
|
||||
let old = state_write.directories.config_dir.read().await.clone();
|
||||
|
||||
tracing::trace!("resetting file watcher after changing config directory");
|
||||
let fs_watcher = crate::utils::watcher::initialize_watcher().await?;
|
||||
state_write.watcher = RwLock::new(fs_watcher);
|
||||
|
||||
tracing::trace!("collecting all config files to be transfered");
|
||||
let mut cfg_entries = crate::utils::io::read_dir(&old).await?;
|
||||
let across_filesystems = is_different_fs(&old, &new);
|
||||
let mut entries = vec![];
|
||||
let mut cleanable = vec![];
|
||||
|
||||
while let Some(e) = cfg_entries.next_entry().await.map_err(|err| crate::utils::io::IOError::with_path(err, &old))? {
|
||||
let epath = e.path();
|
||||
if let Some(file_name) = epath.file_name() {
|
||||
if file_name == store::CLUSTERS_FOLDER
|
||||
|| file_name == store::METADATA_FOLDER
|
||||
{
|
||||
if across_filesystems {
|
||||
entries.extend(crate::package::import::sub(&epath).await?);
|
||||
cleanable.push(epath.clone());
|
||||
} else {
|
||||
entries.push(epath.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracing::trace!("transferring configuration files");
|
||||
let io_semaphore = &state_write.io_semaphore;
|
||||
let nentries = entries.len() as f64;
|
||||
for epath in entries {
|
||||
let relpath = epath.strip_prefix(&old).map_err(|err| anyhow::anyhow!("failed to strip prefix {err}"))?;
|
||||
let newpath = new.join(relpath);
|
||||
if across_filesystems {
|
||||
crate::utils::http::copy(&epath, &newpath, io_semaphore).await?;
|
||||
} else {
|
||||
crate::utils::io::rename(epath.clone(), newpath.clone()).await?;
|
||||
}
|
||||
|
||||
send_ingress(&ingress, 80.0 * (1.0 / nentries), None).await?;
|
||||
}
|
||||
|
||||
tracing::trace!("re-setting configuration settings");
|
||||
let settings = {
|
||||
let mut settings = state_write.settings.write().await;
|
||||
settings.config_dir = Some(new.clone());
|
||||
|
||||
tracing::trace!("updating java paths and keys");
|
||||
for j in settings.java_versions.keys() {
|
||||
if let Some(java) = settings.java_versions.get_mut(&j) {
|
||||
if let Ok(relpath) = PathBuf::from(java.path.clone()).strip_prefix(&old) {
|
||||
java.path = new.join(relpath).to_string_lossy().to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracing::trace!("re-syncing settings file");
|
||||
settings.sync(&state_write.directories.settings_file()).await?;
|
||||
settings.clone()
|
||||
};
|
||||
|
||||
tracing::trace!("re-initializing the config directory");
|
||||
state_write.directories = Directories::initalize(&settings)?;
|
||||
let cleanable_nentries = cleanable.len();
|
||||
if cleanable_nentries > 0 { tracing::trace!("deleting old config files"); }
|
||||
for ce in cleanable {
|
||||
crate::utils::io::remove_dir_all(ce).await?;
|
||||
send_ingress(&ingress, 10.0 * (1.0 / cleanable_nentries as f64), None).await?;
|
||||
}
|
||||
|
||||
tracing::trace!("re-resetting file watching system");
|
||||
let mut file_watcher = crate::utils::watcher::initialize_watcher().await?;
|
||||
state_write.clusters = RwLock::new(Clusters::initialize(&state_write.directories, &mut file_watcher).await?);
|
||||
state_write.watcher = RwLock::new(file_watcher);
|
||||
send_ingress(&ingress, 10.0, None).await?;
|
||||
|
||||
tracing::info!("successfully switched configuration directory to {}", new.display());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// checks if two paths are on different data storage devices
|
||||
fn is_different_fs(a: &Path, b: &Path) -> bool {
|
||||
let roota = a.components().next();
|
||||
let rootb = b.components().next();
|
||||
roota != rootb
|
||||
}
|
||||
|
||||
/// checks if a [`PathBuf`] is writable or locked.
|
||||
pub async fn is_writable(path: PathBuf) -> crate::Result<bool> {
|
||||
let tmp = path.join(".tmp");
|
||||
match crate::utils::io::write(tmp.clone(), "test").await {
|
||||
Ok(_) => {
|
||||
crate::utils::io::remove_file(tmp).await?;
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("failed to write to config directory: {}", e);
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,21 +1,23 @@
|
|||
//! **OneLauncher Constants**
|
||||
//!
|
||||
//! Public constant variables and strings that are used throughout the launcher.
|
||||
//! Can be shared publically, any encrypted secrets should be stored in [`crate::store::credentials`].
|
||||
|
||||
// Basic Metadata
|
||||
pub const NAME: &str = "OneLauncher";
|
||||
pub const VERSION: &str = "0.1.0";
|
||||
|
||||
|
||||
// Authentication and HTTP (TODO: env?)
|
||||
pub const APP_CONFIG_DIR: &str = "org.polyfrost.launcher";
|
||||
pub const USER_AGENT: &str = "OneLauncher/1.0.0 (polyfrost.org)";
|
||||
|
||||
pub const DISCORD_RPC_CLIENT_ID: &str = "1234567890000000";
|
||||
|
||||
// Microsoft Authentication
|
||||
pub const CLIENT_ID: &str = "9419b7ee-1448-4d1b-b52a-550d8f36ab56";
|
||||
pub const MSA_PORT: u16 = 13523;
|
||||
|
||||
|
||||
// Minecraft
|
||||
pub const MINECRAFT_VERSIONS_MANIFEST: &str = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json";
|
||||
|
||||
pub const MINECRAFT_VERSIONS_MANIFEST: &str =
|
||||
"https://piston-meta.mojang.com/mc/game/version_manifest_v2.json";
|
||||
|
||||
// OS constants which match Minecraft's/Mojang's scheme
|
||||
#[cfg(target_os = "windows")]
|
||||
|
|
@ -37,7 +39,6 @@ pub const NATIVE_ARCH: &str = "64";
|
|||
#[cfg(all(not(target_arch = "x86_64"), not(target_arch = "x86")))]
|
||||
pub const NATIVE_ARCH: &str = "64";
|
||||
|
||||
|
||||
// Minecraft library splitter
|
||||
#[cfg(target_os = "windows")]
|
||||
pub const LIBRARY_SPLITTER: &str = ";";
|
||||
|
|
@ -1,3 +1,7 @@
|
|||
//! **OneLauncher Errors**
|
||||
//!
|
||||
//! Public wrappers around common OneLauncher errors.
|
||||
|
||||
use tracing_error::InstrumentError;
|
||||
|
||||
/// A standardized [`thiserror::Error`] type that is used across the launcher
|
||||
|
|
@ -35,9 +39,9 @@ pub enum ErrorKind {
|
|||
#[error("failed to manage serialization of json: {0}")]
|
||||
SerdeError(#[from] serde_json::Error),
|
||||
|
||||
/// Wrapper around [`std::io::Error`] only to be used if a more defined error isn't available (e.g. when using `zip`)
|
||||
#[error("failed to manage writing and reading of files: {0}")]
|
||||
IOError(#[from] std::io::Error),
|
||||
/// Wrapper around [`serde_ini::de::Error`] to handle Serde INI parsing errors.
|
||||
#[error("failed to manage deserialization of ini: {0}")]
|
||||
INIError(#[from] serde_ini::de::Error),
|
||||
|
||||
/// Wrapper around [`reqwest::Error`] to handle HTTP errors.
|
||||
#[error("failed to establish a HTTP connection: {0}")]
|
||||
|
|
@ -47,6 +51,10 @@ pub enum ErrorKind {
|
|||
#[error("failed to manage zip files: {0}")]
|
||||
ZipError(#[from] zip::result::ZipError),
|
||||
|
||||
/// Wrapper around [`async_zip::error::ZipError`] to handle async zip errors.
|
||||
#[error("failed to manage zip files asynchronously: {0}")]
|
||||
AsyncZipError(#[from] async_zip::error::ZipError),
|
||||
|
||||
/// Wrapper around [`anyhow::Error`] to handle generic errors.
|
||||
#[error(transparent)]
|
||||
AnyhowError(#[from] anyhow::Error),
|
||||
|
|
@ -55,25 +63,54 @@ pub enum ErrorKind {
|
|||
#[error("failed to parse a date: {0}")]
|
||||
ChronoError(#[from] chrono::ParseError),
|
||||
|
||||
/// Wrapper around [`crate::game::java::JavaDownloadError`] to handle Java executable downloading.
|
||||
#[error("failed to download java: {0}")]
|
||||
JavaError(#[from] crate::game::java::JavaDownloadError),
|
||||
|
||||
/// Wrapper around [`crate::auth::AuthenticationError`] to handle authentication errors.
|
||||
#[error("failed to authenticate: {0}")]
|
||||
AuthError(#[from] crate::auth::AuthenticationError),
|
||||
|
||||
/// Wrapper around [`crate::utils::dirs::DirectoryError`] to handle directory errors.
|
||||
/// Wrapper around [`crate::state::DirectoryError`] to handle directory errors.
|
||||
#[error("failed to get directory: {0}")]
|
||||
DirectoryError(#[from] crate::utils::dirs::DirectoryError),
|
||||
DirectoryError(#[from] crate::store::DirectoryError),
|
||||
|
||||
/// Wrapper around [`crate::game::client::ClientManagerError`] to handle directory errors.
|
||||
#[error("failed to manage clients: {0}")]
|
||||
ClientManagerError(#[from] crate::game::client_manager::ClientManagerError),
|
||||
/// Wrapper around [`crate::api::proxy::ProxyError`] to handle ingress errors.
|
||||
#[error("failed to handle api communication: {0}")]
|
||||
ProxyError(#[from] crate::api::proxy::ProxyError),
|
||||
|
||||
/// Wrapper around [`reqwest::header::ToStrError`] to handle header conversion errors.
|
||||
#[error("failed to convert header to string: {0}")]
|
||||
HeaderToStrError(#[from] reqwest::header::ToStrError),
|
||||
/// Wrapper around [`crate::store::MinecraftAuthError`] to handle Minecraft auth errors.
|
||||
#[error("failed to authenticate with microsoft: {0}")]
|
||||
AuthError(#[from] crate::store::MinecraftAuthError),
|
||||
|
||||
/// Wrapper around [`notify:Error`] to handle file watching errors.
|
||||
#[error("failed to watch file {0}")]
|
||||
NotifyError(#[from] notify::Error),
|
||||
|
||||
/// Wrapper around [`reqwest::header::ToStrError`] to handle header conversion errors.
|
||||
#[error("failed to convert header to string: {0}")]
|
||||
HeaderToStrError(#[from] reqwest::header::ToStrError),
|
||||
|
||||
/// Wrapper around [`async_tungstenite::tungstenite::Error`] to handle WebSocket errors.
|
||||
#[error("failed to handle websocket connection: {0}")]
|
||||
WebSocketError(#[from] async_tungstenite::tungstenite::Error),
|
||||
|
||||
/// Indicates an error with SHA checksum.
|
||||
#[error("checksum {0} did not match {1}!")]
|
||||
HashError(String, String),
|
||||
|
||||
/// Wrapper around [`crate::utils::io::IOError`] to handle wrapped std::io errors.
|
||||
#[error("error handling IO operations: {0}")]
|
||||
IOError(#[from] crate::utils::io::IOError),
|
||||
|
||||
/// Wrapper around [`std::io::Error`] to handle non-wrapped std::io errors.
|
||||
#[error("I/O (std) error: {0}")]
|
||||
StdIOError(#[from] std::io::Error),
|
||||
|
||||
/// Wrapper around [`crate::utils::java::JavaError`] to handle java errors.
|
||||
#[error("there was an error managing java installations: {0}")]
|
||||
JavaError(#[from] crate::utils::java::JavaError),
|
||||
|
||||
/// Wrapper around [`crate::store::StrongholdError`] to handle stronghold errors.
|
||||
#[error("failed to manage credentials with IOTA stronghold: {0}")]
|
||||
StrongholdError(#[from] crate::store::StrongholdError),
|
||||
|
||||
/// Wrapper around [`tauri::Error`] to handle Tauri errors when the feature flag is enabled
|
||||
#[cfg(feature = "tauri")]
|
||||
#[error("Tauri error: {0}")]
|
||||
TauriError(#[from] tauri::Error),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
22
core/src/lib.rs
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
//! # OneLauncher
|
||||
//!
|
||||
//! A library used as a core for our launcher and Rust APIs.
|
||||
|
||||
#![warn(unused_import_braces, missing_debug_implementations)]
|
||||
#![deny(unused_must_use)]
|
||||
|
||||
#[macro_use]
|
||||
pub mod utils;
|
||||
|
||||
pub mod api;
|
||||
pub mod constants;
|
||||
pub mod error;
|
||||
pub mod game;
|
||||
pub mod logger;
|
||||
pub mod store;
|
||||
|
||||
pub use api::*;
|
||||
pub use error::*;
|
||||
pub use api::proxy::{ProxyState, Ingress, IngressType};
|
||||
pub use logger::start_logger;
|
||||
pub use store::State;
|
||||
|
|
@ -1,5 +1,10 @@
|
|||
//! **OneLauncher Logger**
|
||||
//!
|
||||
//! Public utilities for [`tracing`] logging in OneLauncher.
|
||||
|
||||
use tracing_appender::non_blocking::WorkerGuard;
|
||||
|
||||
/// Start the global [`tracing`] logger in development.
|
||||
#[cfg(debug_assertions)]
|
||||
pub fn start_logger() -> Option<WorkerGuard> {
|
||||
use tracing_subscriber::prelude::*;
|
||||
|
|
@ -18,14 +23,15 @@ pub fn start_logger() -> Option<WorkerGuard> {
|
|||
None
|
||||
}
|
||||
|
||||
/// Start the global [`tracing`] logger in production.
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub fn start_logger() -> Option<WorkerGuard> {
|
||||
use crate::game::client::DirectoryInfo;
|
||||
use crate::store::Directories;
|
||||
use tracing_appender::rolling::{RollingFileAppender, Rotation};
|
||||
use tracing_subscriber::fmt::time::ChronoLocal;
|
||||
use tracing_subscriber::prelude::*;
|
||||
|
||||
let logs_dir = if let Some(directory) = DirectoryInfo::logs_dir() {
|
||||
let logs_dir = if let Some(directory) = Directories::logs_dir() {
|
||||
directory
|
||||
} else {
|
||||
eprintln!("failed to start logger");
|
||||
|
|
@ -43,12 +49,12 @@ pub fn start_logger() -> Option<WorkerGuard> {
|
|||
tracing_subscriber::fmt::layer()
|
||||
.with_writer(non_blocking)
|
||||
.with_ansi(false)
|
||||
.with_timer(ChronoLocal::rfc3339()),
|
||||
.with_timer(ChronoLocal::rfc_3339()),
|
||||
)
|
||||
.with(filter)
|
||||
.with(tracing_error::ErrorLayer::default());
|
||||
|
||||
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
|
||||
|
||||
Some(guard);
|
||||
Some(guard)
|
||||
}
|
||||
697
core/src/store/clusters.rs
Normal file
|
|
@ -0,0 +1,697 @@
|
|||
//! Core cluster state management
|
||||
|
||||
use std::{collections::HashMap, path::{Path, PathBuf}};
|
||||
use chrono::{DateTime, Utc};
|
||||
use futures::prelude::*;
|
||||
use interpulse::api::modded::LoaderVersion;
|
||||
use notify::RecommendedWatcher;
|
||||
use notify_debouncer_mini::Debouncer;
|
||||
use serde::{Serialize, Deserialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::proxy::{send::{send_cluster, send_message}, ClusterPayloadType};
|
||||
use crate::utils::{http::IoSemaphore, io::{self, IOError}};
|
||||
use crate::utils::http::write_icon;
|
||||
use crate::utils::java::JavaVersion;
|
||||
use crate::State;
|
||||
|
||||
use super::{Directories, InitHooks, Memory, Package, PackageType, Resolution};
|
||||
|
||||
/// The public `cluster.json` file used to store the global [`Clusters`] state.
|
||||
const CLUSTER_JSON: &str = "cluster.json";
|
||||
|
||||
/// Core Cluster state manager with a [`HashMap<ClusterPath, Cluster>`].
|
||||
pub(crate) struct Clusters(pub HashMap<ClusterPath, Cluster>);
|
||||
|
||||
/// Core Cluster stages used in package logic.
|
||||
#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ClusterStage {
|
||||
/// Installed with no downloads left.
|
||||
Installed,
|
||||
/// Downloading any sort of core metadata or mod file.
|
||||
Downloading,
|
||||
/// Downloading a full pack file, which is granted lower priority due to the high network demand.
|
||||
PackDownloading,
|
||||
/// Not installed at all.
|
||||
#[default]
|
||||
NotInstalled,
|
||||
}
|
||||
|
||||
/// Relative Path wrapper to be used as an identifer for a cluster path.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, Hash)]
|
||||
#[serde(transparent)]
|
||||
pub struct ClusterPath(pub PathBuf);
|
||||
|
||||
impl ClusterPath {
|
||||
/// Get a new [`ClusterPath`] instance from an [`Into<PathBuf>`].
|
||||
pub fn new(path: impl Into<PathBuf>) -> Self {
|
||||
ClusterPath(path.into())
|
||||
}
|
||||
|
||||
/// Get the full [`PathBuf`] of the current cluster path.
|
||||
pub async fn full_path(&self) -> crate::Result<PathBuf> {
|
||||
let state = State::get().await?;
|
||||
let clusters_dir = state.directories.clusters_dir().await;
|
||||
Ok(clusters_dir.join(&self.0))
|
||||
}
|
||||
|
||||
/// Validate the UTF of a cluster path.
|
||||
pub fn validate(&self) -> crate::Result<&Self> {
|
||||
self.0.to_str().ok_or(anyhow::anyhow!("invalid file path string {}!", self.0.clone().to_string_lossy()));
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Create a [`ClusterPath`] from a full [`PathBuf`].
|
||||
pub async fn from_path(path: PathBuf) -> crate::Result<Self> {
|
||||
let path: PathBuf = io::canonicalize(path)?;
|
||||
let clusters_dir = io::canonicalize(State::get().await?.directories.clusters_dir().await)?;
|
||||
path.strip_prefix(clusters_dir).ok().and_then(|f| f.file_name()).ok_or_else(|| anyhow::anyhow!("path {} is not a cluster path", path.to_string_lossy()))?;
|
||||
|
||||
Ok(Self(path))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ClusterPath {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.0.display().fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
/// Used for backwards compatibility for modpacks which handle windows paths strangely.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, Hash)]
|
||||
#[serde(into = "RawPackagePath", from = "RawPackagePath")]
|
||||
pub struct InnerPathLinux(pub String);
|
||||
|
||||
impl InnerPathLinux {
|
||||
/// Get the first 2 components of the inner path.
|
||||
pub fn get_components(&self) -> String {
|
||||
self.to_string()
|
||||
.split('/')
|
||||
.take(2)
|
||||
.collect::<Vec<_>>()
|
||||
.join("/")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for InnerPathLinux {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RawPackagePath> for InnerPathLinux {
|
||||
fn from(value: RawPackagePath) -> Self {
|
||||
InnerPathLinux(value.0.replace('\\', "/"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Used for backwards compatibility for modpacks which handle windows paths strangely.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
struct RawPackagePath(pub String);
|
||||
|
||||
impl From<InnerPathLinux> for RawPackagePath {
|
||||
fn from(value: InnerPathLinux) -> Self {
|
||||
RawPackagePath(value.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Relative [`PathBuf`] for a specific [`Package`] of a [`Cluster`].
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, Hash)]
|
||||
#[serde(transparent)]
|
||||
pub struct PackagePath(pub PathBuf);
|
||||
|
||||
impl PackagePath {
|
||||
/// Transform a full [`PathBuf`] into a relative [`PackagePath`].
|
||||
pub async fn from_path(path: &PathBuf) -> crate::Result<Self> {
|
||||
let clusters_dir: PathBuf = std::fs::canonicalize(
|
||||
State::get().await?.directories.clusters_dir().await
|
||||
)?;
|
||||
let path: PathBuf = std::fs::canonicalize(path)?;
|
||||
let path = path
|
||||
.strip_prefix(clusters_dir)
|
||||
.ok()
|
||||
.map(|p| p.components().skip(1).collect::<PathBuf>())
|
||||
.ok_or_else(|| anyhow::anyhow!("path {path:?} does not exist in a cluster!", path = path))?;
|
||||
|
||||
Ok(Self(path))
|
||||
}
|
||||
|
||||
/// Get the full [`PathBuf`] of the current package path.
|
||||
pub async fn full_path(&self, cluster: ClusterPath) -> crate::Result<PathBuf> {
|
||||
let cluster_dir = cluster.full_path().await?;
|
||||
Ok(cluster_dir.join(&self.0))
|
||||
}
|
||||
|
||||
/// Get the [`InnerPathLinux`] of a [`PackagePath`].
|
||||
pub fn inner_path(&self) -> InnerPathLinux {
|
||||
InnerPathLinux(self.0.components().map(|c| c.as_os_str().to_string_lossy().to_string()).collect::<Vec<_>>().join("/"))
|
||||
}
|
||||
|
||||
/// Create a new PackagePath from a relative path.
|
||||
pub fn new(path: &Path) -> Self {
|
||||
PackagePath(PathBuf::from(path))
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a single Instance and installation of Minecraft
|
||||
/// Contains settings and identifiers on a per-Cluster basis, falling back to default settings for Options<>
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct Cluster {
|
||||
/// The Uuid of a specific cluster.
|
||||
pub uuid: Uuid,
|
||||
/// The download stage that of a cluster.
|
||||
#[serde(default)]
|
||||
pub stage: ClusterStage,
|
||||
/// The core path of the cluster.
|
||||
#[serde(default)]
|
||||
pub path: PathBuf,
|
||||
/// The associated cluster metadata.
|
||||
pub meta: ClusterMeta,
|
||||
/// The per-cluster JVM memory allocation options.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub memory: Option<Memory>,
|
||||
/// The per-cluster JVM options.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub java: Option<JavaOptions>,
|
||||
/// The per-cluster Minecraft window default resolution.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub resolution: Option<Resolution>,
|
||||
/// The per-cluster Minecraft window fullscreen status.
|
||||
pub force_fullscreen: Option<bool>,
|
||||
// The per-cluster initialization hooks.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub init_hooks: Option<InitHooks>,
|
||||
pub packages: HashMap<PackagePath, Package>,
|
||||
#[serde(default)]
|
||||
pub update: Option<String>,
|
||||
}
|
||||
|
||||
/// Represents core Cluster metadata ([`Cluster#meta`]).
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct ClusterMeta {
|
||||
/// The user-facing name of the cluster stored as a string.
|
||||
pub name: String,
|
||||
|
||||
/// The user-facing group of the cluster stored as a string.
|
||||
#[serde(default)]
|
||||
pub group: Vec<String>,
|
||||
/// The associated Minecraft version of the cluster as last updated.
|
||||
pub mc_version: String,
|
||||
|
||||
/// The associated mod [`Loader`] as specified in the cluster.
|
||||
#[serde(default)]
|
||||
pub loader: Loader,
|
||||
/// The associated mod [`LoaderVersion`] if available.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub loader_version: Option<LoaderVersion>,
|
||||
|
||||
/// The time that the cluster was created in [`DateTime<Utc>`].
|
||||
#[serde(default)]
|
||||
pub created_at: DateTime<Utc>,
|
||||
/// The time the cluster was last modified in [`DateTime<Utc>`].
|
||||
#[serde(default)]
|
||||
pub modified_at: DateTime<Utc>,
|
||||
/// The last time the cluster was played in [`DateTime<Utc>`].
|
||||
/// (Defaults to None if the cluster has never been played)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub played_at: Option<DateTime<Utc>>,
|
||||
/// The overall time played stored as a [`u64`].
|
||||
#[serde(default)]
|
||||
pub overall_played: u64,
|
||||
/// The recent time played stored as a [`u64`].
|
||||
#[serde(default)]
|
||||
pub recently_played: u64,
|
||||
|
||||
/// The associated [`PackageData`] and modpack data for the cluster.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub package_data: Option<PackageData>,
|
||||
|
||||
/// The user-facing cluster icon as a [`PathBuf`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub icon: Option<PathBuf>,
|
||||
/// The user-facing cluster icon as a URL string.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub icon_url: Option<String>
|
||||
}
|
||||
|
||||
/// Optional data used to link a specific cluster to a package project.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct PackageData {
|
||||
/// The package ID as a String.
|
||||
pub package_id: Option<String>,
|
||||
/// The version of the package as a String.
|
||||
pub version_id: Option<String>,
|
||||
/// Whether or not the current package is locked (for legacy modpack support).
|
||||
#[serde(default = "default_locked")]
|
||||
pub locked: Option<bool>,
|
||||
}
|
||||
|
||||
pub fn default_locked() -> Option<bool> { Some(true) }
|
||||
|
||||
/// Available mod loaders to be used for a cluster.
|
||||
#[derive(Debug, Eq, PartialEq, Clone, Copy, Deserialize, Serialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Loader {
|
||||
/// The default vanilla loader, no modding supported.
|
||||
#[default]
|
||||
Vanilla,
|
||||
/// The MinecraftForge Minecraft mod loader.
|
||||
Forge,
|
||||
/// The FabircMC Minecraft mod loader.
|
||||
Fabric,
|
||||
/// The NeoForge Minecraft mod loader.
|
||||
NeoForge,
|
||||
/// The Quilt Minecraft mod loader.
|
||||
Quilt,
|
||||
/// The Legacy Fabric port mod loader.
|
||||
LegacyFabric
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Loader {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match *self {
|
||||
Self::Vanilla => "Vanilla",
|
||||
Self::Forge => "Forge",
|
||||
Self::Fabric => "Fabric",
|
||||
Self::NeoForge => "NeoForge",
|
||||
Self::Quilt => "Quilt",
|
||||
Self::LegacyFabric => "LegacyFabric",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Loader {
|
||||
/// Get the loader version to lowercase for metadata fetching.
|
||||
pub(crate) fn as_meta(&self) -> &'static str {
|
||||
match *self {
|
||||
Self::Vanilla => "vanilla",
|
||||
Self::Forge => "forge",
|
||||
Self::Fabric => "fabric",
|
||||
Self::NeoForge => "neoforge",
|
||||
Self::Quilt => "quilt",
|
||||
Self::LegacyFabric => "legacyfabric",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Custom Java arguments on a per-cluster basis.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct JavaOptions {
|
||||
/// A custom java version from the global java store, if specified.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub custom_version: Option<JavaVersion>,
|
||||
/// Custom runtime arguments when running the cluster.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub custom_arguments: Option<Vec<String>>,
|
||||
/// Custom environment variables when running the cluster.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub custom_env_arguments: Option<Vec<(String, String)>>,
|
||||
}
|
||||
|
||||
impl Cluster {
|
||||
/// Create a new Cluster
|
||||
#[tracing::instrument]
|
||||
pub async fn new(uuid: Uuid, name: String, version: String) -> crate::Result<Self> {
|
||||
if name.trim().is_empty() {
|
||||
return Err(anyhow::anyhow!("invalid instance name (empty)").into());
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
uuid,
|
||||
stage: ClusterStage::NotInstalled,
|
||||
path: PathBuf::new().join(&name),
|
||||
meta: ClusterMeta {
|
||||
name,
|
||||
group: vec![],
|
||||
mc_version: version,
|
||||
loader: Loader::Vanilla,
|
||||
loader_version: None,
|
||||
created_at: Utc::now(),
|
||||
modified_at: Utc::now(),
|
||||
package_data: None,
|
||||
played_at: None,
|
||||
overall_played: 0,
|
||||
recently_played: 0,
|
||||
icon: None,
|
||||
icon_url: None,
|
||||
},
|
||||
java: None,
|
||||
memory: None,
|
||||
resolution: None,
|
||||
force_fullscreen: None,
|
||||
init_hooks: None,
|
||||
packages: HashMap::new(),
|
||||
update: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the [`ClusterPath`] of the specified [`Cluster`].
|
||||
#[inline]
|
||||
pub fn cluster_path(&self) -> ClusterPath {
|
||||
ClusterPath::new(&self.path)
|
||||
}
|
||||
|
||||
/// Set the icon [`bytes::Bytes`] for this cluster.
|
||||
#[tracing::instrument(skip(self, io_semaphore, icon))]
|
||||
pub async fn set_icon<'a>(
|
||||
&'a mut self,
|
||||
cache_path: &Path,
|
||||
io_semaphore: &IoSemaphore,
|
||||
icon: bytes::Bytes,
|
||||
file_name: &str,
|
||||
) -> crate::Result<()> {
|
||||
let file = write_icon(file_name, cache_path, icon, io_semaphore).await?;
|
||||
self.meta.icon = Some(file);
|
||||
self.meta.modified_at = Utc::now();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Handle a cluster crash.
|
||||
pub fn handle_crash(path: ClusterPath) {
|
||||
tokio::task::spawn(async move {
|
||||
let mut res = async {
|
||||
let cluster = crate::api::cluster::get(&path, None).await?;
|
||||
if let Some(cluster) = cluster {
|
||||
if cluster.stage == ClusterStage::Installed {
|
||||
send_message(&format!("cluster {} has crashed! visit the logs page for a crash report.", cluster.meta.name)).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok::<(), crate::Error>(())
|
||||
}.await;
|
||||
|
||||
match res {
|
||||
Ok(()) => {}
|
||||
Err(err) => tracing::warn!("failed to send crash report to frontend {err}")
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/// sync all packages
|
||||
pub fn sync_packages(cluster_path: ClusterPath, force: bool) {
|
||||
let span = tracing::span!(tracing::Level::INFO, "sync_packages", ?cluster_path, ?force);
|
||||
tokio::task::spawn(async move {
|
||||
let result = async {
|
||||
let _span = span.enter();
|
||||
let state = State::get().await?;
|
||||
let cluster = crate::api::cluster::get(&cluster_path, None).await?;
|
||||
|
||||
if let Some(cluster) = cluster {
|
||||
if cluster.stage != ClusterStage::PackDownloading || force {
|
||||
let paths = cluster.get_full_subs().await?;
|
||||
let caches_dir = state.directories.caches_dir().await;
|
||||
let packages = crate::store::generate_context(
|
||||
cluster.clone(),
|
||||
paths,
|
||||
caches_dir,
|
||||
&state.io_semaphore,
|
||||
&state.fetch_semaphore,
|
||||
).await?;
|
||||
|
||||
let mut new_clusters = state.clusters.write().await;
|
||||
if let Some(cluster) = new_clusters.0.get_mut(&cluster_path) {
|
||||
cluster.packages = packages;
|
||||
}
|
||||
|
||||
send_cluster(cluster.uuid, &cluster_path, &cluster.meta.name, ClusterPayloadType::Synced).await?;
|
||||
}
|
||||
} else {
|
||||
tracing::warn!("failed to fetch cluster packages: path {cluster_path} invalid.");
|
||||
}
|
||||
Ok::<(), crate::Error>(())
|
||||
}.await;
|
||||
|
||||
match result {
|
||||
Ok(()) => {}
|
||||
Err(err) => tracing::warn!("failed to fetch cluster packages: {err}")
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/// get the full path to the current cluster.
|
||||
pub async fn get_full_path(&self) -> crate::Result<PathBuf> {
|
||||
let state = State::get().await?;
|
||||
let clusters_dir = state.directories.clusters_dir().await;
|
||||
Ok(clusters_dir.join(&self.path))
|
||||
}
|
||||
|
||||
/// get full paths and subpaths
|
||||
pub async fn get_full_subs(&self) -> crate::Result<Vec<PathBuf>> {
|
||||
let mut files = Vec::new();
|
||||
let cluster_path = self.get_full_path().await?;
|
||||
let mut paths = |path: &str| {
|
||||
let new = cluster_path.join(path);
|
||||
if new.exists() {
|
||||
for sub in std::fs::read_dir(&new).map_err(|e| IOError::with_path(e, &new))? {
|
||||
let sub = sub.map_err(IOError::from)?.path();
|
||||
if sub.is_file() { files.push(sub); }
|
||||
}
|
||||
}
|
||||
Ok::<(), crate::Error>(())
|
||||
};
|
||||
|
||||
paths(PackageType::Mod.get_folder())?;
|
||||
paths(PackageType::Shader.get_folder())?;
|
||||
paths(PackageType::Resource.get_folder())?;
|
||||
paths(PackageType::DataPack.get_folder())?;
|
||||
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
/// watch the filesystem for changes with [`notify`].
|
||||
#[tracing::instrument(skip(watcher))]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn watch(cluster_path: &Path, watcher: &mut Debouncer<RecommendedWatcher>) -> crate::Result<()> {
|
||||
async fn watch_path(cluster_path: &Path, watcher: &mut Debouncer<RecommendedWatcher>, path: &str) -> crate::Result<()> {
|
||||
let path = cluster_path.join(path);
|
||||
io::create_dir_all(&path).await?;
|
||||
watcher.watcher().watch(&cluster_path.join(path), notify::RecursiveMode::Recursive)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
watch_path(cluster_path, watcher, PackageType::Mod.get_folder()).await?;
|
||||
watch_path(cluster_path, watcher, PackageType::Shader.get_folder()).await?;
|
||||
watch_path(cluster_path, watcher, PackageType::Resource.get_folder()).await?;
|
||||
watch_path(cluster_path, watcher, PackageType::DataPack.get_folder()).await?;
|
||||
watch_path(cluster_path, watcher, "crash-reports").await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Clusters {
|
||||
/// Initialize the cluster manager and HashMap.
|
||||
#[tracing::instrument(skip(watcher))]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn initialize(
|
||||
dirs: &Directories,
|
||||
watcher: &mut Debouncer<RecommendedWatcher>,
|
||||
) -> crate::Result<Self> {
|
||||
let mut clusters = HashMap::new();
|
||||
let clusters_dir = dirs.clusters_dir().await;
|
||||
io::create_dir_all(&&clusters_dir).await?;
|
||||
watcher.watcher().watch(&clusters_dir, notify::RecursiveMode::NonRecursive)?;
|
||||
let mut files = io::read_dir(&dirs.clusters_dir().await).await?;
|
||||
|
||||
while let Some(file) = files.next_entry().await.map_err(IOError::from)? {
|
||||
let path = file.path();
|
||||
if path.is_dir() {
|
||||
let cluster = match Self::from_dir(&path, dirs).await {
|
||||
Ok(cluster) => Some(cluster),
|
||||
Err(err) => {
|
||||
tracing::warn!("failed to load cluster {err}. skipping");
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(cluster_) = cluster {
|
||||
let path = io::canonicalize(path)?;
|
||||
Cluster::watch(&path, watcher).await?;
|
||||
clusters.insert(cluster_.cluster_path(), cluster_);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Self(clusters))
|
||||
}
|
||||
|
||||
/// update registered packages
|
||||
#[tracing::instrument]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn update_packages() {
|
||||
let res = async {
|
||||
let state = State::get().await?;
|
||||
let mut files: Vec<(Cluster, Vec<PathBuf>)> = Vec::new();
|
||||
|
||||
{
|
||||
let clusters = state.clusters.read().await;
|
||||
for (_cluster_path, cluster) in clusters.0.iter() {
|
||||
let paths = cluster.get_full_subs().await?;
|
||||
files.push((cluster.clone(), paths));
|
||||
}
|
||||
}
|
||||
|
||||
let caches_dir = state.directories.caches_dir().await;
|
||||
future::try_join_all(files.into_iter().map(|(cluster, files)| async {
|
||||
let cluster_name = cluster.cluster_path();
|
||||
let packages = super::generate_context(
|
||||
cluster,
|
||||
files,
|
||||
caches_dir.clone(),
|
||||
&state.io_semaphore,
|
||||
&state.fetch_semaphore,
|
||||
).await?;
|
||||
|
||||
let mut new_clusters = state.clusters.write().await;
|
||||
if let Some(cluster) = new_clusters.0.get_mut(&cluster_name) {
|
||||
cluster.packages = packages;
|
||||
}
|
||||
|
||||
drop(new_clusters);
|
||||
|
||||
Ok::<(), crate::Error>(())
|
||||
})).await?;
|
||||
|
||||
{
|
||||
let clusters = state.clusters.read().await;
|
||||
clusters.sync().await?;
|
||||
}
|
||||
|
||||
Ok::<(), crate::Error>(())
|
||||
}.await;
|
||||
|
||||
match res {
|
||||
Ok(()) => {}
|
||||
Err(err) => tracing::warn!("failed to fetch cluster packages: {err}")
|
||||
};
|
||||
}
|
||||
|
||||
/// update all available package versions
|
||||
#[tracing::instrument]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn update_versions() {
|
||||
let res = async {
|
||||
let state = State::get().await?;
|
||||
let mut updateable: Vec<(ClusterPath, String)> = Vec::new();
|
||||
|
||||
{
|
||||
let clusters = state.clusters.read().await;
|
||||
for (cluster_path, cluster) in clusters.0.iter() {
|
||||
if let Some(package_data) = &cluster.meta.package_data {
|
||||
if let Some(linked_package) = &package_data.package_id {
|
||||
updateable.push((cluster_path.clone(), linked_package.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO
|
||||
|
||||
{
|
||||
let clusters = state.clusters.read().await;
|
||||
clusters.sync().await?;
|
||||
}
|
||||
|
||||
Ok::<(), crate::Error>(())
|
||||
}.await;
|
||||
|
||||
match res {
|
||||
Ok(()) => {}
|
||||
Err(err) => tracing::warn!("failed to update managed packages: {err}")
|
||||
};
|
||||
}
|
||||
|
||||
/// insert a cluster into the HashMap
|
||||
#[tracing::instrument(skip(self, cluster))]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn insert(&mut self, cluster: Cluster, dont_watch: bool) -> crate::Result<&Self> {
|
||||
send_cluster(
|
||||
cluster.uuid,
|
||||
&cluster.cluster_path(),
|
||||
&cluster.meta.name,
|
||||
crate::proxy::ClusterPayloadType::Inserted
|
||||
).await?;
|
||||
|
||||
if !dont_watch {
|
||||
let state = State::get().await?;
|
||||
let mut watcher = state.watcher.write().await;
|
||||
Cluster::watch(&cluster.get_full_path().await?, &mut watcher).await?;
|
||||
}
|
||||
|
||||
let cluster_name = cluster.cluster_path();
|
||||
cluster_name.validate()?;
|
||||
self.0.insert(cluster_name, cluster);
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// remove a cluster from the HashMap
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub async fn remove(&mut self, cluster_path: &ClusterPath) -> crate::Result<Option<Cluster>> {
|
||||
let cluster = self.0.remove(cluster_path);
|
||||
let path = cluster_path.full_path().await?;
|
||||
if path.exists() { io::remove_dir_all(&path).await?; }
|
||||
|
||||
Ok(cluster)
|
||||
}
|
||||
|
||||
/// sync all available clusters
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn sync(&self) -> crate::Result<&Self> {
|
||||
let _state = State::get().await?;
|
||||
stream::iter(self.0.iter())
|
||||
.map(Ok::<_, crate::Error>)
|
||||
.try_for_each_concurrent(None, |(_, cluster)| async move {
|
||||
let json = serde_json::to_vec(&cluster)?;
|
||||
let json_path = cluster.get_full_path().await?.join(CLUSTER_JSON);
|
||||
io::write(&json_path, &json).await?;
|
||||
Ok::<_, crate::Error>(())
|
||||
}).await?;
|
||||
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// read a cluster from a directory
|
||||
async fn from_dir(path: &Path, dirs: &Directories) -> crate::Result<Cluster> {
|
||||
let json = io::read(&path.join(CLUSTER_JSON)).await?;
|
||||
let mut cluster = serde_json::from_slice::<Cluster>(&json)?;
|
||||
cluster.path = PathBuf::from(path.strip_prefix(dirs.clusters_dir().await).map_err(|err| anyhow::anyhow!("failed to strip prefix {err}"))?);
|
||||
Ok(cluster)
|
||||
}
|
||||
|
||||
/// sync all available clusters
|
||||
pub fn sync_clusters(cluster_path: ClusterPath) {
|
||||
tokio::task::spawn(async move {
|
||||
let span = tracing::span!(tracing::Level::INFO, "sync_clusters");
|
||||
let res = async {
|
||||
let _span = span.enter();
|
||||
let state = State::get().await?;
|
||||
let dirs = &state.directories;
|
||||
let mut clusters = state.clusters.write().await;
|
||||
|
||||
if let Some(cluster) = clusters.0.get_mut(&cluster_path) {
|
||||
if !cluster.get_full_path().await?.exists() {
|
||||
send_cluster(
|
||||
cluster.uuid,
|
||||
&cluster_path,
|
||||
&cluster.meta.name,
|
||||
crate::proxy::ClusterPayloadType::Deleted
|
||||
).await?;
|
||||
tracing::debug!("removed non-existant fs cluster!");
|
||||
clusters.0.remove(&cluster_path);
|
||||
}
|
||||
} else if cluster_path.full_path().await?.exists() {
|
||||
clusters.insert(Self::from_dir(&cluster_path.full_path().await?, dirs).await?, false).await?;
|
||||
Cluster::sync_packages(cluster_path, false);
|
||||
}
|
||||
Ok::<(), crate::Error>(())
|
||||
}.await;
|
||||
|
||||
match res {
|
||||
Ok(()) => {}
|
||||
Err(err) => tracing::warn!("failed to fetch a cluster: {err}")
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
69
core/src/store/credentials.rs
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
//! Core credential management and storage with IOTA Stronghold.
|
||||
|
||||
use crate::utils::http::IoSemaphore;
|
||||
use serde::{Serialize, Serializer};
|
||||
use iota_stronghold::{KeyProvider, SnapshotPath};
|
||||
use zeroize::Zeroizing;
|
||||
use std::{ops::Deref, path::Path};
|
||||
use super::Directories;
|
||||
|
||||
/// A K/V encrypted store to handle digital secrets using IOTA Stronghold.
|
||||
#[derive(Debug)]
|
||||
pub struct Credentials {
|
||||
inner: iota_stronghold::Stronghold,
|
||||
path: iota_stronghold::SnapshotPath,
|
||||
keyprovider: iota_stronghold::KeyProvider,
|
||||
}
|
||||
|
||||
impl Credentials {
|
||||
/// Initialize the K/V encrypted stronghold.
|
||||
pub fn new<P: AsRef<Path>>(
|
||||
path: P,
|
||||
password: Zeroizing<Vec<u8>>,
|
||||
dirs: &Directories,
|
||||
io_semaphore: &IoSemaphore,
|
||||
) -> crate::Result<Self> {
|
||||
let path = SnapshotPath::from_path(path);
|
||||
let stronghold = iota_stronghold::Stronghold::default();
|
||||
let keyprovider = KeyProvider::try_from(password).map_err(|e| StrongholdError::MemoryError(e))?;
|
||||
if path.exists() { stronghold.load_snapshot(&keyprovider, &path).map_err(|e| StrongholdError::ClientError(e))?; }
|
||||
Ok(Self { inner: stronghold, path, keyprovider })
|
||||
}
|
||||
|
||||
pub fn save(&self) -> crate::Result<()> {
|
||||
self.inner.commit_with_keyprovider(&self.path, &self.keyprovider).map_err(|e| StrongholdError::ClientError(e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn inner(&self) -> &iota_stronghold::Stronghold {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Credentials {
|
||||
type Target = iota_stronghold::Stronghold;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum StrongholdError {
|
||||
#[error("stronghold not initialized")]
|
||||
StrongholdNotInitialized,
|
||||
#[error(transparent)]
|
||||
ClientError(#[from] iota_stronghold::ClientError),
|
||||
#[error(transparent)]
|
||||
MemoryError(#[from] iota_stronghold::MemoryError),
|
||||
#[error(transparent)]
|
||||
ProcedureError(#[from] iota_stronghold::procedures::ProcedureError),
|
||||
}
|
||||
|
||||
impl Serialize for StrongholdError {
|
||||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(self.to_string().as_str())
|
||||
}
|
||||
}
|
||||
186
core/src/store/dirs.rs
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
//! Handles core directory management
|
||||
use std::path::PathBuf;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use crate::constants;
|
||||
use super::Settings;
|
||||
|
||||
/// The public `settings.json` file used to store the [`Settings`] state.
|
||||
pub const SETTINGS_FILE: &str = "settings.json";
|
||||
/// The constant core caches folder.
|
||||
pub const CACHES_FOLDER: &str = "caches";
|
||||
/// The constant core clusters folder.
|
||||
pub const CLUSTERS_FOLDER: &str = "clusters";
|
||||
/// The constant core metadata folder.
|
||||
pub const METADATA_FOLDER: &str = "metadata";
|
||||
|
||||
/// Directory management and utilities.
|
||||
#[derive(Debug)]
|
||||
pub struct Directories {
|
||||
/// Settings: All small caches and the core settings.json
|
||||
pub settings_dir: PathBuf,
|
||||
/// Base Configuration: Clusters and all Assets (should be changable as a setting that can go across file systems)
|
||||
/// By default this should be the same as the `settings_dir`
|
||||
pub config_dir: RwLock<PathBuf>,
|
||||
/// The current working directory of the directory manager.
|
||||
pub cwd: PathBuf,
|
||||
}
|
||||
|
||||
impl Directories {
|
||||
/// Bootstrap the initial settings directory on first startup.
|
||||
pub fn init_settings_dir() -> Option<PathBuf> {
|
||||
Self::env_path("ONELAUNCHER_CONFIG").or_else(|| Some(dirs::config_dir()?.join(constants::APP_CONFIG_DIR)))
|
||||
}
|
||||
|
||||
/// Bootstrap the initial settings directory on first startup.
|
||||
#[inline]
|
||||
pub fn init_settings_file() -> crate::Result<PathBuf> {
|
||||
let settings_dir = Self::init_settings_dir().ok_or(DirectoryError::ConfigDir)?;
|
||||
Ok(settings_dir.join("settings.json"))
|
||||
}
|
||||
|
||||
/// Initialize the core directory manager
|
||||
#[tracing::instrument]
|
||||
pub fn initalize(settings: &Settings) -> crate::Result<Self> {
|
||||
let cwd = std::env::current_dir().map_err(|err| DirectoryError::WorkingDir(err))?;
|
||||
let settings_dir = Self::init_settings_dir().ok_or(DirectoryError::ConfigDir)?;
|
||||
let config_dir = settings.config_dir.clone().ok_or(DirectoryError::ConfigDir)?;
|
||||
Ok(Self {
|
||||
settings_dir,
|
||||
config_dir: RwLock::new(config_dir),
|
||||
cwd,
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the `config_dir/metadata` folder within the core config directory.
|
||||
#[inline]
|
||||
pub async fn metadata_dir(&self) -> PathBuf {
|
||||
self.config_dir.read().await.join(METADATA_FOLDER)
|
||||
}
|
||||
|
||||
/// Get the `config_dir/metadata/libraries` folder for Minecraft libraries.
|
||||
#[inline]
|
||||
pub async fn libraries_dir(&self) -> PathBuf {
|
||||
self.metadata_dir().await.join("libraries")
|
||||
}
|
||||
|
||||
/// Get the `config_dir/metadata/java` directory.
|
||||
#[inline]
|
||||
pub async fn java_dir(&self) -> PathBuf {
|
||||
self.metadata_dir().await.join("java_versions")
|
||||
}
|
||||
|
||||
/// Get the `config_dir/metadata/caches` directory.
|
||||
#[inline]
|
||||
pub async fn caches_dir(&self) -> PathBuf {
|
||||
self.metadata_dir().await.join("caches")
|
||||
}
|
||||
|
||||
/// Bootstrap the core logs directory and get it as a [`PathBuf`].
|
||||
#[inline]
|
||||
pub fn logs_dir() -> Option<PathBuf> {
|
||||
Self::init_settings_dir()
|
||||
.map(|d| d.join("logs"))
|
||||
}
|
||||
|
||||
/// Get the `settings_dir/settings.json` file as a [`PathBuf`].
|
||||
#[inline]
|
||||
pub fn settings_file(&self) -> PathBuf {
|
||||
self.settings_dir.join(SETTINGS_FILE)
|
||||
}
|
||||
|
||||
/// Get a [`PathBuf`] from a provided environment variable.
|
||||
#[inline]
|
||||
fn env_path(name: &str) -> Option<PathBuf> {
|
||||
std::env::var_os(name).map(PathBuf::from)
|
||||
}
|
||||
|
||||
/// Get the `config_dir/metadata/assets` directory.
|
||||
#[inline]
|
||||
pub async fn assets_dir(&self) -> PathBuf {
|
||||
self.metadata_dir().await.join("assets")
|
||||
}
|
||||
|
||||
/// Get the `config_dir/metadata/assets/indexes` directory.
|
||||
#[inline]
|
||||
pub async fn index_dir(&self) -> PathBuf {
|
||||
self.assets_dir().await.join("indexes")
|
||||
}
|
||||
|
||||
/// Get the `config_dir/metadata/assets/objects` directory.
|
||||
#[inline]
|
||||
pub async fn objects_dir(&self) -> PathBuf {
|
||||
self.assets_dir().await.join("objects")
|
||||
}
|
||||
|
||||
/// Get the `config_dir/metadata/assets/objects/{hash}` directory.
|
||||
#[inline]
|
||||
pub async fn object_dir(&self, hash: &str) -> PathBuf {
|
||||
self.objects_dir().await.join(&hash[..2]).join(hash)
|
||||
}
|
||||
|
||||
/// Get the `config_dir/clusters` directory.
|
||||
#[inline]
|
||||
pub async fn clusters_dir(&self) -> PathBuf {
|
||||
self.config_dir.read().await.join("clusters")
|
||||
}
|
||||
|
||||
/// Get the `config_dir/clusters/{uuid}` directory.
|
||||
#[inline]
|
||||
pub async fn cluster_dir(&self, uuid: uuid::Uuid) -> PathBuf {
|
||||
self.clusters_dir().await.join(uuid.to_string())
|
||||
}
|
||||
|
||||
/// Get the `{cluster_path}/logs` directory.
|
||||
#[inline]
|
||||
pub async fn cluster_logs_dir(cluster_path: &super::ClusterPath) -> crate::Result<PathBuf> {
|
||||
Ok(cluster_path.full_path().await?.join("logs"))
|
||||
}
|
||||
|
||||
/// Get the `config_dir/metadata/resources` directory.
|
||||
#[inline]
|
||||
pub async fn legacy_assets_dir(&self) -> PathBuf {
|
||||
self.metadata_dir().await.join("resources")
|
||||
}
|
||||
|
||||
/// Get the `config_dir/metadata/natives` directory.
|
||||
#[inline]
|
||||
pub async fn natives_dir(&self) -> PathBuf {
|
||||
self.metadata_dir().await.join("natives")
|
||||
}
|
||||
|
||||
/// Get the `config_dir/metadata/natives/{version}` directory.
|
||||
#[inline]
|
||||
pub async fn version_natives_dir(&self, version: &str) -> PathBuf {
|
||||
self.natives_dir().await.join(version)
|
||||
}
|
||||
|
||||
/// Get the Minecraft `config_dir/metadata/versions` directory.
|
||||
#[inline]
|
||||
pub async fn versions_dir(&self) -> PathBuf {
|
||||
self.metadata_dir().await.join("versions")
|
||||
}
|
||||
|
||||
/// Get the Minecraft `config_dir/metadata/versions/{version}` directory.
|
||||
#[inline]
|
||||
pub async fn version_dir(&self, version: &str) -> PathBuf {
|
||||
self.versions_dir().await.join(version)
|
||||
}
|
||||
|
||||
/// Get the `config_dir/icons` directory.
|
||||
#[inline]
|
||||
pub async fn icons_dir(&self) -> PathBuf {
|
||||
self.config_dir.read().await.join("icons")
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a core directory management error.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum DirectoryError {
|
||||
/// An error for when a config directory cannot be initialized.
|
||||
#[error("failed to get the user's config directory")]
|
||||
ConfigDir,
|
||||
/// A wrapper over [`std::io::Error`] for cwd fetching errors.
|
||||
#[error("could not open working directory {0}")]
|
||||
WorkingDir(std::io::Error),
|
||||
}
|
||||
150
core/src/store/discord.rs
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
//! Handles Discord rich prescence integration
|
||||
use std::sync::{atomic::AtomicBool, Arc};
|
||||
|
||||
use discord_rich_presence::activity::{Activity, Assets};
|
||||
use discord_rich_presence::{DiscordIpc, DiscordIpcClient};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use crate::constants::DISCORD_RPC_CLIENT_ID;
|
||||
use crate::State;
|
||||
|
||||
/// A structure used to manage a Discord IPC client.
|
||||
pub struct DiscordRPC {
|
||||
/// The managed [`DiscordIpcClient`] used for this IPC client.
|
||||
client: Arc<RwLock<DiscordIpcClient>>,
|
||||
/// Whether or not we are connected to the IPC server and internet.
|
||||
connected: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl DiscordRPC {
|
||||
/// Initialize the Discord IPC client and attempt to connect to the server.
|
||||
/// If an error is returned, it will be ignored since Discord RPC isnt essential for the launcher to load.
|
||||
pub async fn initialize(is_offline: bool) -> crate::Result<Self> {
|
||||
let mut discord_ipc =
|
||||
DiscordIpcClient::new(DISCORD_RPC_CLIENT_ID).map_err(|e| {
|
||||
anyhow::anyhow!("failed to create discord client {}", e)
|
||||
})?;
|
||||
|
||||
let connected = if !is_offline {
|
||||
let result = discord_ipc.connect();
|
||||
if result.is_ok() {
|
||||
Arc::new(AtomicBool::new(true))
|
||||
} else {
|
||||
Arc::new(AtomicBool::new(false))
|
||||
}
|
||||
} else {
|
||||
Arc::new(AtomicBool::new(false))
|
||||
};
|
||||
|
||||
let client = Arc::new(RwLock::new(discord_ipc));
|
||||
Ok(DiscordRPC { client, connected })
|
||||
}
|
||||
|
||||
/// Set the Discord IPC activity with a message and try to reconnect if the initial connection fails.
|
||||
pub async fn set_activity(&self, msg: &str, reconnect_if_fail: bool) -> crate::Result<()> {
|
||||
if !self.retry_online().await { return Ok(()); }
|
||||
let state = State::get().await?;
|
||||
let settings = state.settings.read().await;
|
||||
if settings.disable_discord {
|
||||
Ok(self.clear_activity(true).await?)
|
||||
} else {
|
||||
Ok(self.apply_activity(msg, reconnect_if_fail).await?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Do not use this function, use [`DiscordRPC#set_activity`]
|
||||
pub async fn apply_activity(&self, msg: &str, reconnect_if_fail: bool) -> crate::Result<()> {
|
||||
if !self.retry_connection().await { return Ok(()); }
|
||||
|
||||
let activity = Activity::new().state(msg).assets(
|
||||
Assets::new().large_image("polyfrost").large_text("Polyfrost Logo")
|
||||
);
|
||||
|
||||
let mut client: tokio::sync::RwLockWriteGuard<'_, DiscordIpcClient> = self.client.write().await;
|
||||
let result = client.set_activity(activity.clone());
|
||||
let could_not_set = |e: Box<dyn serde::ser::StdError>| {
|
||||
anyhow::anyhow!("failed to apply discord activity {}", e)
|
||||
};
|
||||
|
||||
if reconnect_if_fail {
|
||||
if let Err(_e) = result {
|
||||
client.reconnect().map_err(|e| {
|
||||
anyhow::anyhow!("failed to reconnect to Discord RPC {}", e)
|
||||
})?;
|
||||
|
||||
return Ok(client.set_activity(activity).map_err(could_not_set)?);
|
||||
}
|
||||
} else {
|
||||
result.map_err(could_not_set)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Attempt to check if we are still in an offline environment.
|
||||
pub async fn retry_online(&self) -> bool {
|
||||
let state = match State::get().await {
|
||||
Ok(s) => s,
|
||||
Err(_) => return false,
|
||||
};
|
||||
|
||||
let offline = state.offline.read().await;
|
||||
if *offline { return false; }
|
||||
true
|
||||
}
|
||||
|
||||
/// Retry the Discord IPC connection.
|
||||
pub async fn retry_connection(&self) -> bool {
|
||||
let mut client = self.client.write().await;
|
||||
if !self.connected.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
if client.connect().is_ok() {
|
||||
self.connected.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Clear the current Discord IPC activity, reconnecting if requested.
|
||||
pub async fn clear_activity(&self, reconnect_if_fail: bool) -> crate::Result<()> {
|
||||
if !self.retry_online().await || !self.retry_connection().await { return Ok(()); }
|
||||
|
||||
let mut client = self.client.write().await;
|
||||
let result = client.clear_activity();
|
||||
let could_not_clear = |e: Box<dyn serde::ser::StdError>| {
|
||||
anyhow::anyhow!("failed to clear discord activity {}", e)
|
||||
};
|
||||
|
||||
if reconnect_if_fail {
|
||||
if result.is_err() {
|
||||
client.reconnect().map_err(|e| {
|
||||
anyhow::anyhow!("failed to reconnect to Discord RPC {}", e)
|
||||
})?;
|
||||
|
||||
return Ok(client.clear_activity().map_err(could_not_clear)?);
|
||||
}
|
||||
} else {
|
||||
result.map_err(could_not_clear)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Clear and disable the Discord IPC, reconnecting if requested.
|
||||
pub async fn clear(&self, reconnect_if_fail: bool) -> crate::Result<()> {
|
||||
let state: Arc<tokio::sync::RwLockReadGuard<'_, State>> = State::get().await?;
|
||||
|
||||
{
|
||||
let settings = state.settings.read().await;
|
||||
if settings.disable_discord {
|
||||
println!("discord is disabled.. clearing");
|
||||
return self.clear_activity(true).await;
|
||||
}
|
||||
}
|
||||
|
||||
self.set_activity("Idling...", reconnect_if_fail).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
2
core/src/store/flags.rs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
//! Global Package Metadata management.
|
||||
|
||||
73
core/src/store/java_versions.rs
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
//! Handles all available Java installations
|
||||
|
||||
use std::collections::HashMap;
|
||||
use serde::{Serialize, Deserialize};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::utils::java::JavaVersion;
|
||||
use crate::utils::java;
|
||||
|
||||
/// A HashMap of all located and installed available Java versions
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct JavaVersions(HashMap<String, JavaVersion>);
|
||||
|
||||
impl Default for JavaVersions {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl JavaVersions {
|
||||
/// Create an empty JavaVersions `HashMap`.
|
||||
pub fn new() -> JavaVersions {
|
||||
JavaVersions(HashMap::new())
|
||||
}
|
||||
|
||||
/// Inserts a key-value pair into the map.
|
||||
pub fn insert(&mut self, key: String, java: JavaVersion) {
|
||||
self.0.insert(key, java);
|
||||
}
|
||||
|
||||
/// Removes a key from the map, returning the value at the key if the key was previously in the map.
|
||||
pub fn remove(&mut self, key: &String) {
|
||||
self.0.remove(key);
|
||||
}
|
||||
|
||||
/// Returns a reference to the value corresponding to the key.
|
||||
pub fn get(&self, key: &String) -> Option<&JavaVersion> {
|
||||
self.0.get(key)
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to the value corresponding to the key.
|
||||
pub fn get_mut(&mut self, key: &String) -> Option<&mut JavaVersion> {
|
||||
self.0.get_mut(key)
|
||||
}
|
||||
|
||||
/// Returns the number of elements in the map.
|
||||
pub fn count(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
/// A collection visiting all keys in arbitrary order.
|
||||
pub fn keys(&self) -> Vec<String> {
|
||||
self.0.keys().cloned().collect()
|
||||
}
|
||||
|
||||
/// Validates all stored java versions.
|
||||
pub async fn validate(&self) -> bool {
|
||||
for (_, java) in self.0.iter() {
|
||||
let runtime = java::check_java_instance(
|
||||
PathBuf::from(&java.path).as_path()
|
||||
).await;
|
||||
if let Some(runtime) = runtime {
|
||||
if runtime.version != java.version {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
156
core/src/store/metadata.rs
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
//! Handles fetching metadata via interpulse.
|
||||
|
||||
use interpulse::api::minecraft::{fetch_version_manifest, VersionManifest as MinecraftManifest};
|
||||
use interpulse::api::modded::{fetch_manifest as fetch_modded_manifest, Manifest as ModdedManifest};
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
use crate::utils::http::{read_json, write, IoSemaphore};
|
||||
use crate::utils::io::copy;
|
||||
use crate::State;
|
||||
|
||||
use super::Directories;
|
||||
|
||||
/// The metadata url used in production.
|
||||
#[cfg(not(debug_assertions))]
|
||||
const METADATA_URL: &str = "https://meta.polyfrost.org";
|
||||
|
||||
/// The metadata url used in development.
|
||||
#[cfg(debug_assertions)]
|
||||
const METADATA_URL: &str = "localhost:5543";
|
||||
|
||||
/// A structure of manifests and metadata fetching utilities.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct Metadata {
|
||||
/// The [`MinecraftManifest`] associated with core Minecraft versions.
|
||||
pub minecraft: MinecraftManifest,
|
||||
/// The [`ModdedManifest`] associated with core Fabric versions.
|
||||
pub fabric: ModdedManifest,
|
||||
/// The [`ModdedManifest`] associated with core Quilt versions.
|
||||
pub quilt: ModdedManifest,
|
||||
/// The [`ModdedManifest`] associated with core NeoForge versions.
|
||||
pub neoforge: ModdedManifest,
|
||||
/// The [`ModdedManifest`] associated with core Forge versions.
|
||||
pub forge: ModdedManifest,
|
||||
/// The [`ModdedManifest`] associated with core Legacy Fabric versions.
|
||||
pub legacy_fabric: ModdedManifest,
|
||||
}
|
||||
|
||||
impl Metadata {
|
||||
/// Get the formatted manifest for a specific [`Metadata`] type.
|
||||
fn get_manifest(name: &str) -> String {
|
||||
format!("{METADATA_URL}/{name}/v0/manifest.json")
|
||||
}
|
||||
|
||||
/// Fetch all available metadata types and get a new [`Metadata`] structure.
|
||||
pub async fn fetch() -> crate::Result<Self> {
|
||||
let (minecraft, fabric, quilt, neoforge, forge, legacy_fabric) = tokio::try_join! {
|
||||
async {
|
||||
let url = Self::get_manifest("minecraft");
|
||||
fetch_version_manifest(Some(&url)).await
|
||||
},
|
||||
async {
|
||||
let url = Self::get_manifest("fabric");
|
||||
fetch_modded_manifest(&url).await
|
||||
},
|
||||
async {
|
||||
let url = Self::get_manifest("quilt");
|
||||
fetch_modded_manifest(&url).await
|
||||
},
|
||||
async {
|
||||
let url = Self::get_manifest("neo");
|
||||
fetch_modded_manifest(&url).await
|
||||
},
|
||||
async {
|
||||
let url = Self::get_manifest("forge");
|
||||
fetch_modded_manifest(&url).await
|
||||
},
|
||||
async {
|
||||
let url = Self::get_manifest("legacy-fabric");
|
||||
fetch_modded_manifest(&url).await
|
||||
},
|
||||
}?;
|
||||
|
||||
Ok(Self {
|
||||
minecraft,
|
||||
fabric,
|
||||
quilt,
|
||||
neoforge,
|
||||
forge,
|
||||
legacy_fabric,
|
||||
})
|
||||
}
|
||||
|
||||
/// Initialize the core Metadata manager.
|
||||
#[tracing::instrument(skip(io_semaphore))]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn initialize(dirs: &Directories, online: bool, io_semaphore: &IoSemaphore) -> crate::Result<Self> {
|
||||
let mut metadata = None;
|
||||
let path = dirs.caches_dir().await.join("metadata.json");
|
||||
let backup = dirs.caches_dir().await.join("metadata.json.bak");
|
||||
|
||||
if let Ok(metadata_json) = read_json::<Metadata>(&path, io_semaphore).await {
|
||||
metadata = Some(metadata_json);
|
||||
} else if online {
|
||||
let res = async {
|
||||
let fetch_data = Self::fetch().await?;
|
||||
|
||||
write(&path, &serde_json::to_vec(&fetch_data).unwrap_or_default(), io_semaphore).await?;
|
||||
write(&backup, &serde_json::to_vec(&fetch_data).unwrap_or_default(), io_semaphore).await?;
|
||||
|
||||
metadata = Some(fetch_data);
|
||||
Ok::<(), crate::Error>(())
|
||||
}.await;
|
||||
|
||||
match res {
|
||||
Ok(()) => {}
|
||||
Err(err) => { tracing::warn!("failed to fetch metadata: {err}") }
|
||||
}
|
||||
} else if let Ok(metadata_json) = read_json::<Metadata>(&backup, io_semaphore).await {
|
||||
metadata = Some(metadata_json);
|
||||
copy(&backup, &path).await?;
|
||||
}
|
||||
|
||||
if let Some(meta) = metadata {
|
||||
Ok(meta)
|
||||
} else {
|
||||
Err(anyhow::anyhow!("failed to fetch launcher metadata").into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Update and backup all available metadata.
|
||||
pub async fn update() {
|
||||
let res = async {
|
||||
let fetch_data = Metadata::fetch().await?;
|
||||
let state = State::get().await?;
|
||||
|
||||
let path = state
|
||||
.directories
|
||||
.caches_dir()
|
||||
.await
|
||||
.join("metadata.json");
|
||||
let backup = state
|
||||
.directories
|
||||
.caches_dir()
|
||||
.await
|
||||
.join("metadata.json.bak");
|
||||
|
||||
if path.exists() {
|
||||
copy(&path, &backup).await?;
|
||||
}
|
||||
|
||||
write(&path, &serde_json::to_vec(&fetch_data)?, &state.io_semaphore).await?;
|
||||
|
||||
let mut old_metadata = state.metadata.write().await;
|
||||
*old_metadata = fetch_data;
|
||||
|
||||
Ok::<(), crate::Error>(())
|
||||
}.await;
|
||||
|
||||
match res {
|
||||
Ok(()) => {}
|
||||
Err(err) => {
|
||||
tracing::warn!("failed to update launcher metadata: {err}")
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
783
core/src/store/minecraft.rs
Normal file
|
|
@ -0,0 +1,783 @@
|
|||
//! Handles MSA Authentication flow.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use base64::Engine;
|
||||
use rand::Rng;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use uuid::Uuid;
|
||||
use chrono::{DateTime, Utc};
|
||||
use p256::ecdsa::signature::Signer;
|
||||
use p256::ecdsa::SigningKey;
|
||||
use p256::pkcs8::{DecodePrivateKey, EncodePrivateKey};
|
||||
use sha2::Digest;
|
||||
|
||||
const AUTH_STORE: &str = "authentication.json";
|
||||
|
||||
/// The core state of Microsoft authentication for the launcher
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct MinecraftState {
|
||||
/// A [`HashMap`] of all logged in users by [`Uuid`] and their Minecraft credentials.
|
||||
pub users: HashMap<Uuid, MinecraftCredentials>,
|
||||
/// The current stored device token to be used while logging in.
|
||||
pub token: Option<SaveDeviceToken>,
|
||||
/// The default Minecraft user which the launcher uses, by [`Uuid`].
|
||||
pub default_user: Option<Uuid>,
|
||||
}
|
||||
|
||||
impl MinecraftState {
|
||||
/// Initialize a new Minecraft global state.
|
||||
#[tracing::instrument]
|
||||
pub async fn initialize(dirs: &super::Directories, io_semaphore: &crate::utils::http::IoSemaphore) -> crate::Result<Self> {
|
||||
let path = dirs.caches_dir().await.join(AUTH_STORE);
|
||||
let store = crate::utils::http::read_json(&path, io_semaphore).await.ok();
|
||||
|
||||
if let Some(store) = store {
|
||||
Ok(store)
|
||||
} else {
|
||||
Ok(Self {
|
||||
users: HashMap::new(),
|
||||
token: None,
|
||||
default_user: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Save the current Minecraft credentials.
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub async fn save(&self) -> crate::Result<()> {
|
||||
let state = crate::State::get().await?;
|
||||
let path = state.directories.caches_dir().await.join(AUTH_STORE);
|
||||
crate::utils::http::write(&path, &serde_json::to_vec(&self)?, &state.io_semaphore).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Refresh all tokens in the global state.
|
||||
#[tracing::instrument(skip(self))]
|
||||
async fn refresh(&mut self) -> crate::Result<(DeviceKey, DeviceToken)> {
|
||||
macro_rules! device_key {
|
||||
($self:ident, $device_key:expr, $device_token:expr, $SaveDeviceToken:path) => {{
|
||||
let key = device_key()?;
|
||||
let token = device_token(&key).await?;
|
||||
|
||||
self.token = Some(SaveDeviceToken {
|
||||
id: key.id.clone(),
|
||||
private_key: key
|
||||
.key
|
||||
.to_pkcs8_pem(p256::pkcs8::LineEnding::default())
|
||||
.map_err(|err| MinecraftAuthError::PKCS8Error(err))?
|
||||
.to_string(),
|
||||
x: key.x.clone(),
|
||||
y: key.y.clone(),
|
||||
token: token.clone(),
|
||||
modern: true,
|
||||
});
|
||||
self.save().await?;
|
||||
|
||||
(key, token)
|
||||
}};
|
||||
}
|
||||
|
||||
let (key, token) = if let Some(ref token) = self.token {
|
||||
if token.token.not_after > Utc::now() {
|
||||
if let Ok(private_key) = SigningKey::from_pkcs8_pem(&token.private_key) {
|
||||
(
|
||||
DeviceKey {
|
||||
id: token.id.clone(),
|
||||
key: private_key,
|
||||
x: token.x.clone(),
|
||||
y: token.y.clone(),
|
||||
},
|
||||
token.token.clone(),
|
||||
)
|
||||
} else {
|
||||
device_key!(self, device_key, device_token, SaveDeviceToken)
|
||||
}
|
||||
} else {
|
||||
device_key!(self, device_key, device_token, SaveDeviceToken)
|
||||
}
|
||||
} else {
|
||||
device_key!(self, device_key, device_token, SaveDeviceToken)
|
||||
};
|
||||
|
||||
Ok((key, token))
|
||||
}
|
||||
|
||||
/// Begin a Microsoft authentication flow.
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub async fn begin(&mut self) -> crate::Result<MinecraftLogin> {
|
||||
let (key, token) = self.refresh().await?;
|
||||
let verify = generate_oauth_challenge();
|
||||
let mut hash = sha2::Sha256::new();
|
||||
hash.update(&verify);
|
||||
let hash_result = hash.finalize();
|
||||
let challenge = base64::prelude::BASE64_URL_SAFE_NO_PAD.encode(&hash_result);
|
||||
let (sid, ruri) = sisu_authenticate(&token.token, &challenge, &key).await?;
|
||||
Ok(MinecraftLogin { verify, challenge, session_id: sid, redirect_uri: ruri.msa_oauth_redirect })
|
||||
}
|
||||
|
||||
/// Finish a Microsoft authentication flow.
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub async fn finish(&mut self, code: &str, flow: MinecraftLogin) -> crate::Result<MinecraftCredentials> {
|
||||
let (key, token) = self.refresh().await?;
|
||||
let oauth_token = oauth_token(code, &flow.verify).await?;
|
||||
let sisu_authorize = sisu_authorize(Some(&flow.session_id), &oauth_token.access_token, &token.token, &key).await?;
|
||||
let xbox_token = xsts_authorize(sisu_authorize, &token.token, &key).await?;
|
||||
let minecraft_token = minecraft_token(xbox_token).await?;
|
||||
minecraft_entitlements(&minecraft_token.access_token).await?;
|
||||
let profile = minecraft_profile(&minecraft_token.access_token).await?;
|
||||
let profile_id = profile.id.unwrap_or_default();
|
||||
let credentials = MinecraftCredentials {
|
||||
id: profile_id,
|
||||
username: profile.name,
|
||||
access_token: minecraft_token.access_token,
|
||||
refresh_token: oauth_token.refresh_token,
|
||||
#[allow(deprecated)] expires: Utc::now() + chrono::TimeDelta::seconds(oauth_token.expires_in as i64),
|
||||
};
|
||||
|
||||
self.users.insert(profile_id, credentials.clone());
|
||||
|
||||
if self.default_user.is_none() {
|
||||
self.default_user = Some(profile_id);
|
||||
}
|
||||
|
||||
self.save().await?;
|
||||
|
||||
Ok(credentials)
|
||||
}
|
||||
|
||||
/// Get the default user account as a set of optional [`MinecraftCredentials`].
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub async fn get_default(&mut self) -> crate::Result<Option<MinecraftCredentials>> {
|
||||
let credentials = if let Some(default_user) = self.default_user {
|
||||
if let Some(creds) = self.users.get(&default_user) {
|
||||
Some(creds)
|
||||
} else {
|
||||
self.users.values().next()
|
||||
}
|
||||
} else {
|
||||
self.users.values().next()
|
||||
};
|
||||
|
||||
if let Some(creds) = credentials {
|
||||
if self.default_user != Some(creds.id) {
|
||||
self.default_user = Some(creds.id);
|
||||
self.save().await?;
|
||||
}
|
||||
|
||||
if creds.expires < Utc::now() {
|
||||
let cred_id = creds.id;
|
||||
let profile_name = creds.username.clone();
|
||||
|
||||
let oauth_token = oauth_refresh(&creds.refresh_token).await?;
|
||||
let (key, token) = self.refresh().await?;
|
||||
let sisu_authorize = sisu_authorize(
|
||||
None,
|
||||
&oauth_token.access_token,
|
||||
&token.token,
|
||||
&key,
|
||||
).await?;
|
||||
|
||||
let xbox_token = xsts_authorize(sisu_authorize, &token.token, &key).await?;
|
||||
let minecraft_token = minecraft_token(xbox_token).await?;
|
||||
let val = MinecraftCredentials {
|
||||
id: cred_id,
|
||||
username: profile_name,
|
||||
access_token: minecraft_token.access_token,
|
||||
refresh_token: oauth_token.refresh_token,
|
||||
#[allow(deprecated)] expires: Utc::now() + chrono::TimeDelta::seconds(oauth_token.expires_in as i64),
|
||||
};
|
||||
|
||||
self.users.insert(val.id, val.clone());
|
||||
self.save().await?;
|
||||
|
||||
Ok(Some(val))
|
||||
} else {
|
||||
Ok(Some(creds.clone()))
|
||||
}
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a set of [`MinecraftCredentials`] from a Uuid.
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub async fn remove(&mut self, id: Uuid) -> crate::Result<Option<MinecraftCredentials>> {
|
||||
let val = self.users.remove(&id);
|
||||
self.save().await?;
|
||||
Ok(val)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: get MICROSOFT_CLIENT_ID
|
||||
/// Publically used Minecraft client ID for OneLauncher.
|
||||
const MICROSOFT_CLIENT_ID: &str = "";
|
||||
/// Microsoft login redirect URI.
|
||||
const REDIRECT_URL: &str = "https://login.live.com/oauth20_desktop.srf";
|
||||
/// Microsoft login xboxlive scopes to get tokens.
|
||||
const SCOPES: &str = "service::user.auth.xboxlive.com::MBI_SSL";
|
||||
|
||||
/// A device token used for Microsoft authentication.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
pub struct DeviceToken {
|
||||
/// The time that the token was issued in [`DateTime<Utc>`].
|
||||
pub issue_instant: DateTime<Utc>,
|
||||
/// The expiration date of this token in [`DateTime<Utc>`].
|
||||
pub not_after: DateTime<Utc>,
|
||||
/// The token as a string.
|
||||
pub token: String,
|
||||
/// The JSON-encoded [`HashMap<String, Value>`] of display claims.
|
||||
pub display_claims: HashMap<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
/// A transferrable EC key translated to a [`SaveDeviceToken`]
|
||||
#[derive(Debug)]
|
||||
pub struct DeviceKey {
|
||||
/// The ID of this device key.
|
||||
pub id: String,
|
||||
/// The EC private key.
|
||||
pub key: SigningKey,
|
||||
/// The EC `x` value.
|
||||
pub x: String,
|
||||
/// The EC `y` value.
|
||||
pub y: String,
|
||||
}
|
||||
|
||||
/// A serializable device token that is used to finish authenticaton.
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct SaveDeviceToken {
|
||||
/// The ID of the token.
|
||||
pub id: String,
|
||||
/// The private key associated with the token.
|
||||
pub private_key: String,
|
||||
/// The EC `x` value of the key.
|
||||
pub x: String,
|
||||
/// The EC `y` value of the key.
|
||||
pub y: String,
|
||||
/// The assocated [`DeviceToken`].
|
||||
pub token: DeviceToken,
|
||||
/// Whether or not we should patch the auth device token to use a modern auth flow
|
||||
#[serde(default)]
|
||||
modern: bool,
|
||||
}
|
||||
|
||||
/// Core variables passed throughout the Minecraft login flow.
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct MinecraftLogin {
|
||||
pub verify: String,
|
||||
/// The OAuth challenge generated at the start of the flow.
|
||||
pub challenge: String,
|
||||
/// The generated session id.
|
||||
pub session_id: String,
|
||||
/// The xboxlive redirect URI.
|
||||
pub redirect_uri: String,
|
||||
}
|
||||
|
||||
/// A structure of all needed Minecraft credentials for logging in and account management.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct MinecraftCredentials {
|
||||
/// The uuid of the credentials.
|
||||
pub id: Uuid,
|
||||
/// The username of the Minecraft account.
|
||||
pub username: String,
|
||||
/// The access token as a String.
|
||||
pub access_token: String,
|
||||
/// The refresh token as a string for [`MinecraftState#refresh`].
|
||||
pub refresh_token: String,
|
||||
/// The time that the access token expires as a [`DateTime<Utc>`].
|
||||
pub expires: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(key))]
|
||||
pub async fn device_token(key: &DeviceKey) -> Result<DeviceToken, MinecraftAuthError> {
|
||||
Ok(send_signed_request(
|
||||
None,
|
||||
"https://device.auth.xboxlive.com/device/authenticate",
|
||||
"/device/authenticate",
|
||||
json!({
|
||||
"Properties": {
|
||||
"AuthMethod": "ProofOfPossession",
|
||||
"Id": format!("{{{}}}", key.id),
|
||||
"DeviceType": "Win32",
|
||||
"Version": "10.16.0",
|
||||
"ProofKey": {
|
||||
"kty": "EC",
|
||||
"x": key.x,
|
||||
"y": key.y,
|
||||
"crv": "P-256",
|
||||
"alg": "ES256",
|
||||
"use": "sig"
|
||||
}
|
||||
},
|
||||
"RelyingParty": "http://auth.xboxlive.com",
|
||||
"TokenType": "JWT"
|
||||
}),
|
||||
key,
|
||||
MinecraftAuthStep::DeviceToken,
|
||||
).await?.1)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct RedirectUri {
|
||||
pub msa_oauth_redirect: String,
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(key))]
|
||||
async fn sisu_authenticate(
|
||||
token: &str,
|
||||
challenge: &str,
|
||||
key: &DeviceKey,
|
||||
) -> Result<(String, RedirectUri), MinecraftAuthError> {
|
||||
// what was microsoft on when writing this??????????
|
||||
let (headers, res) = send_signed_request(
|
||||
None,
|
||||
"https://sisu.xboxlive.com/authenticate",
|
||||
"/authenticate",
|
||||
json!({
|
||||
"AppId": MICROSOFT_CLIENT_ID,
|
||||
"DeviceToken": token,
|
||||
"Offers": [SCOPES],
|
||||
"Query": {
|
||||
"code_challenge": challenge,
|
||||
"code_challenge_method": "S256",
|
||||
"state": generate_oauth_challenge(),
|
||||
"prompt": "select_account"
|
||||
},
|
||||
"RedirectUri": REDIRECT_URL,
|
||||
"Sandbox": "RETAIL",
|
||||
"TokenType": "code",
|
||||
"TitleId": "1794566092"
|
||||
}),
|
||||
key,
|
||||
MinecraftAuthStep::SisuAuthenicate,
|
||||
).await?;
|
||||
|
||||
let session_id = headers
|
||||
.get("X-SessionId")
|
||||
.and_then(|x| x.to_str().ok())
|
||||
.ok_or_else(|| MinecraftAuthError::SessionIdError)?
|
||||
.to_string();
|
||||
|
||||
Ok((session_id, res))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct OAuthToken {
|
||||
// pub token_type: String,
|
||||
pub expires_in: u64,
|
||||
// pub scope: String,
|
||||
pub access_token: String,
|
||||
pub refresh_token: String,
|
||||
// pub user_id: String,
|
||||
// pub foci: String,
|
||||
}
|
||||
|
||||
#[tracing::instrument]
|
||||
async fn oauth_token(code: &str, verify: &str) -> Result<OAuthToken, MinecraftAuthError> {
|
||||
let mut query = HashMap::new();
|
||||
query.insert("client_id", MICROSOFT_CLIENT_ID);
|
||||
query.insert("code", code);
|
||||
query.insert("code_verifier", &*verify);
|
||||
query.insert("grant_type", "authorization_code");
|
||||
query.insert("redirect_uri", REDIRECT_URL);
|
||||
query.insert("scope", SCOPES);
|
||||
let res = auth_retry(|| {
|
||||
crate::utils::http::REQWEST_CLIENT
|
||||
.post(REDIRECT_URL)
|
||||
.header("Accept", "application/json")
|
||||
.form(&query)
|
||||
.send()
|
||||
})
|
||||
.await
|
||||
.map_err(|source| MinecraftAuthError::RequestError {
|
||||
source,
|
||||
step: MinecraftAuthStep::OAuthToken,
|
||||
})?;
|
||||
|
||||
let status = res.status();
|
||||
let text = res.text().await.map_err(|source| {
|
||||
MinecraftAuthError::RequestError { step: MinecraftAuthStep::OAuthToken, source }
|
||||
})?;
|
||||
|
||||
serde_json::from_str(&text).map_err(|source| {
|
||||
MinecraftAuthError::DeserializeError { step: MinecraftAuthStep::OAuthToken, raw: text, source, status_code: status }
|
||||
})
|
||||
}
|
||||
|
||||
#[tracing::instrument]
|
||||
async fn oauth_refresh(refresh_token: &str) -> Result<OAuthToken, MinecraftAuthError> {
|
||||
let mut query = HashMap::new();
|
||||
query.insert("client_id", MICROSOFT_CLIENT_ID);
|
||||
query.insert("refresh_token", refresh_token);
|
||||
query.insert("grant_type", "refresh_token");
|
||||
query.insert("redirect_uri", REDIRECT_URL);
|
||||
query.insert("scope", SCOPES);
|
||||
let res = auth_retry(|| {
|
||||
crate::utils::http::REQWEST_CLIENT
|
||||
.post(REDIRECT_URL)
|
||||
.header("Accept", "application/json")
|
||||
.form(&query)
|
||||
.send()
|
||||
})
|
||||
.await
|
||||
.map_err(|source| MinecraftAuthError::RequestError { step: MinecraftAuthStep::RefreshOAuthToken, source })?;
|
||||
|
||||
let status = res.status();
|
||||
let text = res.text().await.map_err(|source| {
|
||||
MinecraftAuthError::RequestError { step: MinecraftAuthStep::RefreshOAuthToken, source }
|
||||
})?;
|
||||
|
||||
serde_json::from_str(&text).map_err(|source| {
|
||||
MinecraftAuthError::DeserializeError { step: MinecraftAuthStep::RefreshOAuthToken, raw: text, source, status_code: status }
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct SisuAuthorize {
|
||||
// pub authorization_token: DeviceToken,
|
||||
// pub device_token: String,
|
||||
// pub sandbox: String,
|
||||
pub title_token: DeviceToken,
|
||||
pub user_token: DeviceToken,
|
||||
// pub web_page: string,
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(key))]
|
||||
async fn sisu_authorize(
|
||||
session_id: Option<&str>,
|
||||
access_token: &str,
|
||||
device_token: &str,
|
||||
key: &DeviceKey,
|
||||
) -> Result<SisuAuthorize, MinecraftAuthError> {
|
||||
Ok(send_signed_request(
|
||||
None,
|
||||
"https://sisu.xboxlive.com/authorize",
|
||||
"/authorize",
|
||||
json!({
|
||||
"AccessToken": format!("t={access_token}"),
|
||||
"AppId": MICROSOFT_CLIENT_ID,
|
||||
"DeviceToken": device_token,
|
||||
"ProofKey": {
|
||||
// kibty (kty)
|
||||
"kty": "EC",
|
||||
"x": key.x,
|
||||
"y": key.y,
|
||||
"crv": "P-256",
|
||||
"alg": "ES256",
|
||||
"use": "sig"
|
||||
},
|
||||
"Sandbox": "RETAIL",
|
||||
"SessionId": session_id,
|
||||
"SiteName": "user.auth.xboxlive.com",
|
||||
"RelyingParty": "http://xboxlive.com",
|
||||
"UseModernGamertag": true
|
||||
}),
|
||||
key,
|
||||
MinecraftAuthStep::SisuAuthorize,
|
||||
).await?.1)
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(key))]
|
||||
async fn xsts_authorize(
|
||||
authorize: SisuAuthorize,
|
||||
device_token: &str,
|
||||
key: &DeviceKey,
|
||||
) -> Result<DeviceToken, MinecraftAuthError> {
|
||||
Ok(send_signed_request(
|
||||
None,
|
||||
"https://xsts.auth.xboxlive.com/xsts/authorize",
|
||||
"/xsts/authorize",
|
||||
json!({
|
||||
"RelyingParty": "rp://api.minecraftservices.com/",
|
||||
"TokenType": "JWT",
|
||||
"Properties": {
|
||||
"SandboxId": "RETAIL",
|
||||
"UserTokens": [authorize.user_token.token],
|
||||
"DeviceTokens": device_token,
|
||||
"TitleToken": authorize.title_token.token,
|
||||
},
|
||||
}),
|
||||
key,
|
||||
MinecraftAuthStep::XstsAuthorize,
|
||||
).await?.1)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct MinecraftToken {
|
||||
// pub username: String,
|
||||
pub access_token: String,
|
||||
// pub token_type: String,
|
||||
// pub expires_in: u64,
|
||||
}
|
||||
|
||||
#[tracing::instrument]
|
||||
async fn minecraft_token(token: DeviceToken) -> Result<MinecraftToken, MinecraftAuthError> {
|
||||
let uhs = token
|
||||
.display_claims
|
||||
.get("xui")
|
||||
.and_then(|x| x.get(0))
|
||||
.and_then(|x| x.get("uhs"))
|
||||
.and_then(|x| x.as_str().map(String::from))
|
||||
.ok_or_else(|| MinecraftAuthError::HashError)?;
|
||||
|
||||
let token = token.token;
|
||||
let res = auth_retry(|| {
|
||||
crate::utils::http::REQWEST_CLIENT
|
||||
.post("https://api.minecraftservices.com/launcher/login")
|
||||
.header("Accept", "application/json")
|
||||
.json(&json!({
|
||||
"platform": "PC_LAUNCHER",
|
||||
"xtoken": format!("XBL3.0 x={uhs};{token}"),
|
||||
}))
|
||||
.send()
|
||||
}).await
|
||||
.map_err(|source| MinecraftAuthError::RequestError { step: MinecraftAuthStep::MinecraftToken, source })?;
|
||||
|
||||
let status = res.status();
|
||||
let text = res.text().await.map_err(|source| MinecraftAuthError::RequestError { step: MinecraftAuthStep::MinecraftToken, source })?;
|
||||
|
||||
serde_json::from_str(&text).map_err(|source| {
|
||||
MinecraftAuthError::DeserializeError { step: MinecraftAuthStep::MinecraftToken, raw: text, source, status_code: status }
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct MinecraftProfile {
|
||||
pub id: Option<Uuid>,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[tracing::instrument]
|
||||
async fn minecraft_profile(token: &str) -> Result<MinecraftProfile, MinecraftAuthError> {
|
||||
let res = auth_retry(|| {
|
||||
crate::utils::http::REQWEST_CLIENT
|
||||
.get("https//api.minecraftservices.com/minecraft/profile")
|
||||
.header("Accept", "application/json")
|
||||
.bearer_auth(token)
|
||||
.send()
|
||||
})
|
||||
.await
|
||||
.map_err(|source| MinecraftAuthError::RequestError { step: MinecraftAuthStep::MinecraftProfile, source })?;
|
||||
|
||||
let status = res.status();
|
||||
let text = res.text().await.map_err(|source| MinecraftAuthError::RequestError { step: MinecraftAuthStep::MinecraftProfile, source })?;
|
||||
|
||||
serde_json::from_str(&text).map_err(|source| {
|
||||
MinecraftAuthError::DeserializeError { step: MinecraftAuthStep::MinecraftProfile, raw: text, source, status_code: status }
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct MinecraftEntitlements {}
|
||||
|
||||
#[tracing::instrument]
|
||||
async fn minecraft_entitlements(token: &str) -> Result<MinecraftEntitlements, MinecraftAuthError> {
|
||||
let res = auth_retry(|| {
|
||||
crate::utils::http::REQWEST_CLIENT
|
||||
.get("https://api.minecraftservices.com/entitlements/mcstore")
|
||||
.header("Accept", "application/json")
|
||||
.bearer_auth(token)
|
||||
.send()
|
||||
})
|
||||
.await
|
||||
.map_err(|source| MinecraftAuthError::RequestError { step: MinecraftAuthStep::MinecraftEntitlements, source })?;
|
||||
|
||||
let status = res.status();
|
||||
let text = res.text().await.map_err(|source| MinecraftAuthError::RequestError { step: MinecraftAuthStep::MinecraftEntitlements, source })?;
|
||||
|
||||
serde_json::from_str(&text).map_err(|source| {
|
||||
MinecraftAuthError::DeserializeError { step: MinecraftAuthStep::MinecraftEntitlements, raw: text, source, status_code: status }
|
||||
})
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(request_fn))]
|
||||
async fn auth_retry<F>(
|
||||
request_fn: impl Fn() -> F,
|
||||
) -> Result<reqwest::Response, reqwest::Error>
|
||||
where
|
||||
F: std::future::Future<Output = Result<reqwest::Response, reqwest::Error>>,
|
||||
{
|
||||
const RETRY_COUNT: usize = 5;
|
||||
const RETRY_WAIT: tokio::time::Duration = tokio::time::Duration::from_millis(250);
|
||||
let mut resp = request_fn().await;
|
||||
|
||||
for i in 0..RETRY_COUNT {
|
||||
match &resp {
|
||||
Ok(_) => {
|
||||
break;
|
||||
}
|
||||
Err(err) => {
|
||||
if err.is_connect() || err.is_timeout() {
|
||||
if i < RETRY_COUNT - 1 {
|
||||
tracing::debug!("request failed due to a connection error, retrying request...");
|
||||
tokio::time::sleep(RETRY_WAIT).await;
|
||||
resp = request_fn().await;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
resp
|
||||
}
|
||||
|
||||
#[tracing::instrument]
|
||||
fn device_key() -> Result<DeviceKey, MinecraftAuthError> {
|
||||
let id = Uuid::new_v4().to_string().to_uppercase();
|
||||
let signing_key = SigningKey::random(&mut rand::rngs::OsRng);
|
||||
let public_key = p256::ecdsa::VerifyingKey::from(&signing_key);
|
||||
let encoded_point = public_key.to_encoded_point(false);
|
||||
|
||||
Ok(DeviceKey {
|
||||
id,
|
||||
key: signing_key,
|
||||
x: base64::prelude::BASE64_STANDARD_NO_PAD.encode(
|
||||
encoded_point.x().ok_or_else(|| {
|
||||
MinecraftAuthError::PublicKeyReading
|
||||
})?,
|
||||
),
|
||||
y: base64::prelude::BASE64_STANDARD_NO_PAD.encode(
|
||||
encoded_point.y().ok_or_else(|| {
|
||||
MinecraftAuthError::PublicKeyReading
|
||||
})?,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
async fn send_signed_request<T: serde::de::DeserializeOwned>(
|
||||
authorization: Option<&str>,
|
||||
url: &str,
|
||||
url_path: &str,
|
||||
raw_body: serde_json::Value,
|
||||
key: &DeviceKey,
|
||||
step: MinecraftAuthStep,
|
||||
) -> Result<(reqwest::header::HeaderMap, T), MinecraftAuthError> {
|
||||
let auth = authorization.clone().map_or(Vec::new(), |v| v.as_bytes().to_vec());
|
||||
let body = serde_json::to_vec(&raw_body).map_err(|source| {
|
||||
MinecraftAuthError::SerializeError { step, source }
|
||||
})?;
|
||||
let time: u128 = { ((Utc::now().timestamp() as u128) + 11644473600) * 10000000 };
|
||||
|
||||
use byteorder::WriteBytesExt;
|
||||
let mut buffer = Vec::new();
|
||||
buffer.write_u32::<byteorder::BigEndian>(1).map_err(|source| {
|
||||
MinecraftAuthError::SigningError { step, source }
|
||||
})?;
|
||||
buffer.write_u8(0).map_err(|source| {
|
||||
MinecraftAuthError::SigningError { step, source }
|
||||
})?;
|
||||
buffer.write_u64::<byteorder::BigEndian>(time as u64).map_err(|source| {
|
||||
MinecraftAuthError::SigningError { step, source }
|
||||
})?;
|
||||
buffer.write_u8(0).map_err(|source| {
|
||||
MinecraftAuthError::SigningError { step, source }
|
||||
})?;
|
||||
buffer.extend_from_slice("POST".as_bytes());
|
||||
buffer.write_u8(0).map_err(|source| {
|
||||
MinecraftAuthError::SigningError { step, source }
|
||||
})?;
|
||||
buffer.extend_from_slice(url_path.as_bytes());
|
||||
buffer.write_u8(0).map_err(|source| {
|
||||
MinecraftAuthError::SigningError { step, source }
|
||||
})?;
|
||||
buffer.extend_from_slice(&auth);
|
||||
buffer.write_u8(0).map_err(|source| {
|
||||
MinecraftAuthError::SigningError { step, source }
|
||||
})?;
|
||||
buffer.extend_from_slice(&body);
|
||||
buffer.write_u8(0).map_err(|source| {
|
||||
MinecraftAuthError::SigningError { step, source }
|
||||
})?;
|
||||
|
||||
let ecdsa_sig: p256::ecdsa::Signature = key.key.sign(&buffer);
|
||||
let mut sig_buffer = Vec::new();
|
||||
|
||||
sig_buffer.write_i32::<byteorder::BigEndian>(1).map_err(|source| {
|
||||
MinecraftAuthError::SigningError { step, source }
|
||||
})?;
|
||||
sig_buffer.write_u64::<byteorder::BigEndian>(time as u64).map_err(|source| {
|
||||
MinecraftAuthError::SigningError { step, source }
|
||||
})?;
|
||||
sig_buffer.extend_from_slice(&ecdsa_sig.r().to_bytes());
|
||||
sig_buffer.extend_from_slice(&ecdsa_sig.s().to_bytes());
|
||||
|
||||
let signature = base64::prelude::BASE64_STANDARD.encode(&sig_buffer);
|
||||
|
||||
let res = auth_retry(|| {
|
||||
let mut request = crate::utils::http::REQWEST_CLIENT
|
||||
.post(url)
|
||||
.header("Content-Type", "application/json; charset=utf-8")
|
||||
.header("Accept", "application/json")
|
||||
.header("Signature", &signature);
|
||||
|
||||
if url != "https://sisu.xboxlive.com/authorize" {
|
||||
request = request.header("x-xbl-contract-version", "1");
|
||||
}
|
||||
|
||||
if let Some(auth) = authorization {
|
||||
request = request.header("Authorization", auth);
|
||||
}
|
||||
|
||||
request.body(body.clone()).send()
|
||||
}).await
|
||||
.map_err(|source| MinecraftAuthError::RequestError { step, source })?;
|
||||
|
||||
let status = res.status();
|
||||
let headers = res.headers().clone();
|
||||
let body = res.text().await.map_err(|source| {
|
||||
MinecraftAuthError::RequestError { step, source }
|
||||
})?;
|
||||
|
||||
let body = serde_json::from_str(&body).map_err(|source| {
|
||||
MinecraftAuthError::DeserializeError { step, raw: body, source, status_code: status }
|
||||
})?;
|
||||
Ok((headers, body))
|
||||
}
|
||||
|
||||
#[tracing::instrument]
|
||||
fn generate_oauth_challenge() -> String {
|
||||
let mut rng = rand::thread_rng();
|
||||
let bytes: Vec<u8> = (0..64).map(|_| rng.gen::<u8>()).collect();
|
||||
bytes.iter().map(|b| format!("{:02x}", b)).collect()
|
||||
}
|
||||
|
||||
/// An ordered list of all MSA authentication steps.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum MinecraftAuthStep {
|
||||
DeviceToken,
|
||||
SisuAuthenicate,
|
||||
OAuthToken,
|
||||
RefreshOAuthToken,
|
||||
SisuAuthorize,
|
||||
XstsAuthorize,
|
||||
MinecraftToken,
|
||||
MinecraftEntitlements,
|
||||
MinecraftProfile,
|
||||
}
|
||||
|
||||
/// Wrapper around all `Error`s that can occur during the Microsoft authentication process.
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum MinecraftAuthError {
|
||||
#[error("failed to read public key during key generation")]
|
||||
PublicKeyReading,
|
||||
#[error("failed to serialize private key using PKCS8: {0}")]
|
||||
PKCS8Error(#[from] p256::pkcs8::Error),
|
||||
#[error("failed to serialize JSON during MSA step {step:?}: {source}")]
|
||||
SerializeError { step: MinecraftAuthStep, #[source] source: serde_json::Error },
|
||||
#[error("failed to deserialize JSON during MSA step {step:?}: {source}! status code {status_code} - body: {raw}")]
|
||||
DeserializeError { step: MinecraftAuthStep, raw: String, #[source] source: serde_json::Error, status_code: reqwest::StatusCode },
|
||||
#[error("failed to request using HTTP during MSA step {step:?}: {source}")]
|
||||
RequestError { step: MinecraftAuthStep, #[source] source: reqwest::Error },
|
||||
#[error("failed to create signed buffer during MSA step {step:?}: {source}")]
|
||||
SigningError { step: MinecraftAuthStep, #[source] source: std::io::Error },
|
||||
#[error("failed to read user hash")]
|
||||
HashError,
|
||||
#[error("failed to read user xbox session ID")]
|
||||
SessionIdError,
|
||||
}
|
||||
275
core/src/store/mod.rs
Normal file
|
|
@ -0,0 +1,275 @@
|
|||
//! **OneLauncher Store**
|
||||
//!
|
||||
//! Core state and storage management for the launcher, managing all states.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use notify::RecommendedWatcher;
|
||||
use notify_debouncer_mini::Debouncer;
|
||||
use tokio::sync::OnceCell;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use crate::proxy::send::init_ingress_internal;
|
||||
use crate::proxy::send::send_ingress;
|
||||
use crate::proxy::send::send_offline;
|
||||
use crate::utils::http;
|
||||
use crate::utils::http::FetchSemaphore;
|
||||
use crate::utils::http::IoSemaphore;
|
||||
|
||||
mod dirs;
|
||||
pub use self::dirs::*;
|
||||
|
||||
mod minecraft;
|
||||
pub use self::minecraft::*;
|
||||
|
||||
mod credentials;
|
||||
pub use self::credentials::*;
|
||||
|
||||
mod discord;
|
||||
pub use self::discord::*;
|
||||
|
||||
mod metadata;
|
||||
pub use self::metadata::*;
|
||||
|
||||
mod settings;
|
||||
pub use self::settings::*;
|
||||
|
||||
mod java_versions;
|
||||
pub use self::java_versions::*;
|
||||
|
||||
mod processor;
|
||||
pub use self::processor::*;
|
||||
|
||||
mod clusters;
|
||||
pub use self::clusters::*;
|
||||
|
||||
mod package;
|
||||
pub use self::package::*;
|
||||
|
||||
mod oneconfig;
|
||||
pub use self::oneconfig::*;
|
||||
|
||||
mod flags;
|
||||
|
||||
/// The static [`OnceCell<RwLock<State>>`] for storing the global runtime launcher state.
|
||||
static LAUNCHER_STATE: OnceCell<RwLock<State>> = OnceCell::const_new();
|
||||
|
||||
/// The public OneLauncher state structure.
|
||||
pub struct State {
|
||||
/// Handles a boolean to check if the launcher is connected to the internet
|
||||
pub offline: RwLock<bool>,
|
||||
/// Handles core launcher directory and files
|
||||
pub directories: Directories,
|
||||
|
||||
/// Semaphore used to handle concurrent network requests
|
||||
pub fetch_semaphore: FetchSemaphore,
|
||||
/// Maximum number of semaphore permits to limit the amount of network requests at one time
|
||||
pub fetch_semaphore_max: RwLock<u32>,
|
||||
/// Semaphore used to handle concurrent IO requests
|
||||
pub io_semaphore: IoSemaphore,
|
||||
/// Maximum number of semaphore permits to limit the amount of IO requests at one time
|
||||
pub io_semaphore_max: RwLock<u32>,
|
||||
|
||||
/// Handles launcher metadata via [`interpulse`]
|
||||
pub metadata: RwLock<Metadata>,
|
||||
/// Handles launcher configuration and settings
|
||||
pub settings: RwLock<Settings>,
|
||||
/// Handles minecraft auth flows and users
|
||||
pub users: RwLock<MinecraftState>,
|
||||
/// Handles processes
|
||||
pub processor: RwLock<Processor>,
|
||||
/// Handles OneConfig integration with [`async-tungstenite`]
|
||||
pub oneconfig: RwLock<Option<OneConfig>>,
|
||||
/// Handles secure credential management with [`iota_stronghold`].
|
||||
pub credentials: RwLock<Option<Credentials>>,
|
||||
/// Handles clusters
|
||||
pub(crate) clusters: RwLock<Clusters>,
|
||||
/// Handles internal ingress processes
|
||||
pub(crate) ingress_processor: RwLock<IngressProcessor>,
|
||||
/// Handles file system watching for cluster manager
|
||||
pub(crate) watcher: RwLock<Debouncer<RecommendedWatcher>>,
|
||||
/// Handles Discord rich prescence
|
||||
pub discord_rpc: DiscordRPC,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// Get the current global launcher state (or initialize it)
|
||||
pub async fn get() -> crate::Result<Arc<tokio::sync::RwLockReadGuard<'static, Self>>> {
|
||||
Ok(Arc::new(LAUNCHER_STATE.get_or_try_init(Self::initialize).await?.read().await))
|
||||
}
|
||||
|
||||
/// Get and lock writing to the current global launcher state (or initalize it)
|
||||
pub async fn get_and_write() -> crate::Result<tokio::sync::RwLockWriteGuard<'static, Self>> {
|
||||
Ok(LAUNCHER_STATE.get_or_try_init(Self::initialize).await?.write().await)
|
||||
}
|
||||
|
||||
/// Initializes the core OneLauncher state fully.
|
||||
#[tracing::instrument]
|
||||
#[onelauncher_debug::debugger]
|
||||
async fn initialize() -> crate::Result<RwLock<State>> {
|
||||
let ingress = init_ingress_internal(
|
||||
crate::IngressType::Initialize,
|
||||
100.0,
|
||||
"initializing state",
|
||||
).await?;
|
||||
|
||||
let settings = Settings::initialize(&Directories::init_settings_file()?).await?;
|
||||
let directories = Directories::initalize(&settings)?;
|
||||
send_ingress(&ingress, 10.0, None).await?;
|
||||
let mut watcher = crate::utils::watcher::initialize_watcher().await?;
|
||||
let fetch_semaphore = FetchSemaphore(RwLock::new(Semaphore::new(settings.max_async_fetches)));
|
||||
let io_semaphore = IoSemaphore(RwLock::new(Semaphore::new(settings.max_async_io_operations)));
|
||||
send_ingress(&ingress, 10.0, None).await?;
|
||||
|
||||
let is_offline = !http::check_internet_connection(3).await;
|
||||
|
||||
let metadata_in = Metadata::initialize(&directories, !is_offline, &io_semaphore);
|
||||
let clusters_in = Clusters::initialize(&directories, &mut watcher);
|
||||
let users_in = MinecraftState::initialize(&directories, &io_semaphore);
|
||||
let (metadata, clusters, users) = crate::ingress_join! {
|
||||
Some(&ingress), 70.0, Some("loading core");
|
||||
metadata_in,
|
||||
clusters_in,
|
||||
users_in,
|
||||
}?;
|
||||
|
||||
let ingress_processor = IngressProcessor::new();
|
||||
let discord_rpc = DiscordRPC::initialize(is_offline).await?;
|
||||
if !settings.disable_discord && !is_offline {
|
||||
let _ = discord_rpc.apply_activity("Idling...", true).await;
|
||||
}
|
||||
|
||||
let processor = Processor::new();
|
||||
|
||||
Self::status_loop();
|
||||
send_ingress(&ingress, 10.0, None).await?;
|
||||
|
||||
Ok::<RwLock<Self>, crate::Error>(RwLock::new(Self {
|
||||
offline: RwLock::new(is_offline),
|
||||
directories,
|
||||
fetch_semaphore,
|
||||
fetch_semaphore_max: RwLock::new(settings.max_async_fetches as u32),
|
||||
io_semaphore,
|
||||
io_semaphore_max: RwLock::new(settings.max_async_io_operations as u32),
|
||||
metadata: RwLock::new(metadata),
|
||||
settings: RwLock::new(settings),
|
||||
users: RwLock::new(users),
|
||||
processor: RwLock::new(processor),
|
||||
oneconfig: RwLock::new(None),
|
||||
credentials: RwLock::new(None),
|
||||
clusters: RwLock::new(clusters),
|
||||
ingress_processor: RwLock::new(ingress_processor),
|
||||
watcher: RwLock::new(watcher),
|
||||
discord_rpc,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Initalizes a "game loop" which checks for updates and if we are online.
|
||||
pub fn status_loop() {
|
||||
tokio::task::spawn(async {
|
||||
loop {
|
||||
let state = Self::get().await;
|
||||
if let Ok(state) = state {
|
||||
let _ = state.check_status().await;
|
||||
}
|
||||
|
||||
tokio::time::sleep(Duration::from_secs(10)).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Updates all data if we are connected to the internet.
|
||||
pub fn update() {
|
||||
tokio::task::spawn(async {
|
||||
if let Ok(state) = crate::State::get().await {
|
||||
if !*state.offline.read().await {
|
||||
let version_up = Clusters::update_versions();
|
||||
let meta_up = Metadata::update();
|
||||
let package_up = Clusters::update_packages();
|
||||
|
||||
let _ = tokio::join!(version_up, meta_up, package_up);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Synchronizes data that can change outside of our control.
|
||||
#[tracing::instrument]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn sync() -> crate::Result<()> {
|
||||
let state = Self::get().await?;
|
||||
let sync_settings = async {
|
||||
let state = Arc::clone(&state);
|
||||
tokio::spawn(async move {
|
||||
let reader = state.settings.read().await;
|
||||
reader.sync(&state.directories.settings_file()).await?;
|
||||
Ok::<_, crate::Error>(())
|
||||
})
|
||||
.await?
|
||||
};
|
||||
|
||||
let sync_clusters = async {
|
||||
let state = Arc::clone(&state);
|
||||
|
||||
tokio::spawn(async move {
|
||||
let clusters = state.clusters.read().await;
|
||||
|
||||
clusters.sync().await?;
|
||||
Ok::<_, crate::Error>(())
|
||||
}).await?
|
||||
};
|
||||
|
||||
tokio::try_join!(sync_settings, sync_clusters)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resets the IO [`Semaphore`] to clear all tasks.
|
||||
/// # This should ONLY be called when we can ensure
|
||||
/// # that there are no current tasks running!!
|
||||
pub async fn reset_io_semaphore(&self) {
|
||||
let settings = self.settings.read().await;
|
||||
let mut io_semaphore = self.io_semaphore.0.write().await;
|
||||
let mut total_permits = self.io_semaphore_max.write().await;
|
||||
// block ALL semaphore permits - this can be destructive
|
||||
let _ = io_semaphore.acquire_many(*total_permits).await;
|
||||
|
||||
io_semaphore.close();
|
||||
*total_permits = settings.max_async_io_operations as u32;
|
||||
*io_semaphore = Semaphore::new(settings.max_async_io_operations);
|
||||
}
|
||||
|
||||
/// Resets the Fetch [`Semaphore`] to clear all tasks.
|
||||
/// # This should ONLY be called when we can ensure
|
||||
/// # that there are no current tasks running!!
|
||||
pub async fn reset_fetch_semaphore(&self) {
|
||||
let settings = self.settings.read().await;
|
||||
let mut fetch_semaphore = self.fetch_semaphore.0.write().await;
|
||||
let mut total_permits = self.fetch_semaphore_max.write().await;
|
||||
// block ALL semaphore permits - this can be destructive
|
||||
let _ = fetch_semaphore.acquire_many(*total_permits).await;
|
||||
|
||||
fetch_semaphore.close();
|
||||
*total_permits = settings.max_async_io_operations as u32;
|
||||
*fetch_semaphore = Semaphore::new(settings.max_async_fetches);
|
||||
}
|
||||
|
||||
/// Checks if we are online used in a loop.
|
||||
pub async fn check_status(&self) -> crate::Result<()> {
|
||||
let is_online = http::check_internet_connection(3).await;
|
||||
let mut offline = self.offline.write().await;
|
||||
if *offline != is_online {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
send_offline(!is_online).await?;
|
||||
*offline = !is_online;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Determine if the global state is initalized or not (wrapper)
|
||||
pub fn initalized() -> bool {
|
||||
LAUNCHER_STATE.initialized()
|
||||
}
|
||||
}
|
||||
34
core/src/store/oneconfig.rs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
//! OneConfig state using [`async_tungstenite`] to communicate to the OneConfig server
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
use super::ClusterPath;
|
||||
|
||||
/// Wrapper over an [`async_tungstenite::WebSocketStream`] to connect to the OneConfig server.
|
||||
pub struct OneConfig {
|
||||
/// The public tokio socket connection.
|
||||
socket: async_tungstenite::WebSocketStream<
|
||||
async_tungstenite::tokio::ConnectStream,
|
||||
>,
|
||||
}
|
||||
|
||||
/// A WebSocket packet while updating a mod to display a GUI in game.
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ModUpdatePacket {
|
||||
/// The ID of the packet.
|
||||
id: Uuid,
|
||||
/// The ID of the mod being updated.
|
||||
mod_id: Uuid,
|
||||
/// The [`ClusterPath`] associated with this event.
|
||||
cluster_path: ClusterPath,
|
||||
}
|
||||
|
||||
impl OneConfig {
|
||||
/// Initializes a OneConfig socket connection on localhost port `4023`.
|
||||
pub async fn new(cluster: ClusterPath) -> crate::Result<Self> {
|
||||
let (socket, _) = async_tungstenite::tokio::connect_async(format!(
|
||||
"wss://localhost:4023/oneconfig/ws?cluster={cluster}"
|
||||
)).await?;
|
||||
Ok(Self { socket })
|
||||
}
|
||||
}
|
||||
287
core/src/store/package.rs
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
//! Handlers for Mod metadata that can be displayed in a GUI mod list or exported as a mod pack
|
||||
|
||||
use std::{collections::HashMap, path::{Path, PathBuf}};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use async_zip::tokio::read::fs::ZipFileReader;
|
||||
use sha2::Digest;
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
use crate::{prelude::IOError, utils::http::{write_icon, FetchSemaphore, IoSemaphore}};
|
||||
|
||||
use super::{Cluster, PackagePath};
|
||||
|
||||
// TODO: move all of this to prisma, it would be perfect for it
|
||||
// TODO: Curseforge, Modrinth, SkyClient integration
|
||||
|
||||
/// Creates [`Package`] data for a given [`Cluster`] from on-device files and APIs.
|
||||
/// Paths must be the full paths and not relative paths.
|
||||
#[tracing::instrument(skip(paths, cluster, io_semaphore, fetch_semaphore))]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn generate_context(
|
||||
cluster: Cluster,
|
||||
paths: Vec<PathBuf>,
|
||||
cache_path: PathBuf,
|
||||
io_semaphore: &IoSemaphore,
|
||||
fetch_semaphore: &FetchSemaphore,
|
||||
// credentials: &Credentials,
|
||||
) -> crate::Result<HashMap<PackagePath, Package>> {
|
||||
let mut hashes = HashMap::new();
|
||||
|
||||
for path in paths {
|
||||
if !path.exists() { continue; }
|
||||
if let Some(ext) = path.extension() { if ext == "txt" { continue; } }
|
||||
let mut file = tokio::fs::File::open(path.clone()).await.map_err(|e| IOError::with_path(e, &path))?;
|
||||
let mut buffer = [0u8; 4096];
|
||||
let mut sha512 = sha2::Sha512::new();
|
||||
|
||||
loop {
|
||||
let read = file.read(&mut buffer).await.map_err(IOError::from)?;
|
||||
if read == 0 { break; }
|
||||
sha512.update(&buffer[..read]);
|
||||
}
|
||||
|
||||
let hash = format!("{:x}", sha512.finalize());
|
||||
hashes.insert(hash, path.clone());
|
||||
}
|
||||
|
||||
let mut result = HashMap::new();
|
||||
let mut stream = tokio_stream::iter(result_packages);
|
||||
while let Some((k, v)) = stream.next().await {
|
||||
let k = PackagePath::from_path(k).await?;
|
||||
result.insert(k, v);
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Represents types of packages handled by the launcher.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum PackageType {
|
||||
/// represents a mod jarfile
|
||||
Mod,
|
||||
/// represents a datapack file
|
||||
DataPack,
|
||||
/// represents a resourcepack file
|
||||
Resource,
|
||||
/// represents a shaderpack file
|
||||
Shader,
|
||||
}
|
||||
|
||||
impl PackageType {
|
||||
/// attempt to get a [`PackageType`] from a loader string.
|
||||
pub fn from_loader(loaders: Vec<String>) -> Option<Self> {
|
||||
if loaders.iter().any(|x| ["fabric", "forge", "quilt"].contains(&&**x)) {
|
||||
Some(PackageType::Mod)
|
||||
} else if loaders.iter().any(|x| x == "datapack") {
|
||||
Some(PackageType::DataPack)
|
||||
} else if loaders.iter().any(|x| ["iris", "optifine"].contains(&&**x)) {
|
||||
Some(PackageType::Shader)
|
||||
} else if loaders.iter().any(|x| ["vanilla", "canvas", "minecraft"].contains(&&**x)) {
|
||||
Some(PackageType::Resource)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_parent(path: PathBuf) -> Option<Self> {
|
||||
let path = path.parent()?.file_name()?;
|
||||
match path.to_str()? {
|
||||
"mods" => Some(PackageType::Mod),
|
||||
"datapacks" => Some(PackageType::DataPack),
|
||||
"resourcepacks" => Some(PackageType::Resource),
|
||||
"shaderpacks" => Some(PackageType::Shader),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_name(&self) -> &'static str {
|
||||
match self {
|
||||
PackageType::Mod => "mod",
|
||||
PackageType::DataPack => "datapack",
|
||||
PackageType::Resource => "resourcepack",
|
||||
PackageType::Shader => "shaderpack",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_folder(&self) -> &'static str {
|
||||
match self {
|
||||
PackageType::Mod => "mods",
|
||||
PackageType::DataPack => "datapacks",
|
||||
PackageType::Resource => "resourcepacks",
|
||||
PackageType::Shader => "shaderpacks",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A struct that represents a Package.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct Package {
|
||||
pub sha512: String,
|
||||
pub meta: PackageMetadata,
|
||||
pub file_name: String,
|
||||
pub disabled: bool,
|
||||
}
|
||||
|
||||
/// Metadata that represents a [`Package`].
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum PackageMetadata {
|
||||
Managed {
|
||||
package: Box<ManagedPackage>,
|
||||
version: Box<ManagedVersion>,
|
||||
users: Box<ManagedUser>,
|
||||
update: Option<Box<ManagedVersion>>,
|
||||
incompatible: bool,
|
||||
},
|
||||
Mapped {
|
||||
title: Option<String>,
|
||||
description: Option<String>,
|
||||
authors: Vec<String>,
|
||||
version: Option<String>,
|
||||
icon: Option<PathBuf>,
|
||||
package_type: Option<String>,
|
||||
},
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Universal metadata for any managed package from a Mod distribution platform.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct ManagedPackage {
|
||||
// Core Metadata
|
||||
|
||||
pub id: String,
|
||||
pub uid: Option<String>,
|
||||
pub package_type: String,
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub main: String,
|
||||
pub versions: Vec<String>,
|
||||
pub game_versions: Vec<String>,
|
||||
pub loaders: Vec<String>,
|
||||
pub icon_url: Option<String>,
|
||||
|
||||
pub created: DateTime<Utc>,
|
||||
pub updated: DateTime<Utc>,
|
||||
pub client: PackageSide,
|
||||
pub server: PackageSide,
|
||||
pub downloads: u32,
|
||||
pub followers: u32,
|
||||
pub categories: Vec<String>,
|
||||
pub optional_categories: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
/// Universal managed package version of a package.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct ManagedVersion {
|
||||
pub id: String,
|
||||
pub package_id: String,
|
||||
pub author: String,
|
||||
pub name: String,
|
||||
|
||||
pub featured: bool,
|
||||
pub version_id: String,
|
||||
pub changelog: String,
|
||||
pub changelog_url: Option<String>,
|
||||
|
||||
pub published: DateTime<Utc>,
|
||||
pub downloads: u32,
|
||||
pub version_type: String,
|
||||
|
||||
pub files: Vec<ManagedVersionFile>,
|
||||
pub deps: Vec<ManagedDependency>,
|
||||
pub game_versions: Vec<String>,
|
||||
pub loaders: Vec<String>,
|
||||
}
|
||||
|
||||
/// Universal interface for managed package files.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct ManagedVersionFile {
|
||||
pub url: String,
|
||||
pub file_name: String,
|
||||
pub primary: bool,
|
||||
|
||||
pub size: u32,
|
||||
pub file_type: Option<PackageFile>,
|
||||
pub hashes: HashMap<String, String>,
|
||||
}
|
||||
|
||||
/// Universal interface for managed package dependencies.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct ManagedDependency {
|
||||
pub version_id: Option<String>,
|
||||
pub package_id: Option<String>,
|
||||
pub file_name: Option<String>,
|
||||
pub dependency_type: PackageDependency,
|
||||
}
|
||||
|
||||
/// Universal interface for managed package authors and users.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct ManagedUser {
|
||||
pub id: String,
|
||||
pub role: String,
|
||||
pub username: String,
|
||||
pub name: Option<String>,
|
||||
pub avatar: Option<String>,
|
||||
pub description: Option<String>,
|
||||
pub created: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// The type of a [`ManagedDependency`].
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub enum PackageDependency {
|
||||
Required,
|
||||
Optional,
|
||||
Incompatible,
|
||||
Embedded,
|
||||
}
|
||||
|
||||
/// The Client/Server side type of a [`Package`].
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum PackageSide {
|
||||
Required,
|
||||
Optional,
|
||||
Unsupported,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// The file type of a [`Package`].
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum PackageFile {
|
||||
RequiredPack,
|
||||
OptionalPack,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(io_semaphore))]
|
||||
#[onelauncher_debug::debugger]
|
||||
async fn read_icon(
|
||||
icon_path: Option<String>,
|
||||
cache_path: &Path,
|
||||
path: &PathBuf,
|
||||
io_semaphore: &IoSemaphore,
|
||||
) -> crate::Result<Option<PathBuf>> {
|
||||
if let Some(icon_path) = icon_path {
|
||||
let zip_reader = ZipFileReader::new(path).await;
|
||||
if let Ok(zip_reader) = zip_reader {
|
||||
let zip_idx_res = zip_reader.file().entries().iter().position(|f| {
|
||||
f.filename().as_str().unwrap_or_default() == icon_path
|
||||
});
|
||||
|
||||
if let Some(zip_idx) = zip_idx_res {
|
||||
let mut bytes = Vec::new();
|
||||
if zip_reader.reader_with_entry(zip_idx).await?.read_to_end_checked(&mut bytes).await.is_ok() {
|
||||
let bytes = bytes::Bytes::from(bytes);
|
||||
let path = write_icon(&icon_path, cache_path, bytes, io_semaphore).await?;
|
||||
|
||||
return Ok(Some(path));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
617
core/src/store/processor.rs
Normal file
|
|
@ -0,0 +1,617 @@
|
|||
//! Handles child processes in a unified API
|
||||
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
use serde::{Serialize, Deserialize};
|
||||
use chrono::{DateTime, Utc};
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::process::{Child, Command};
|
||||
use tokio::sync::RwLock;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::proxy::send::send_process;
|
||||
use crate::utils::http::read_json;
|
||||
use crate::utils::io::IOError;
|
||||
use crate::proxy::ProcessPayloadType;
|
||||
use crate::State;
|
||||
use crate::api::cluster;
|
||||
|
||||
use super::{Cluster, ClusterPath};
|
||||
|
||||
/// Global processor cache file.
|
||||
const PROCESSOR_JSON: &str = "processor.json";
|
||||
|
||||
/// Wrapper over a HashMap of PIDs to ProcessorChildren and unified apis
|
||||
pub struct Processor(HashMap<Uuid, Arc<RwLock<ProcessorChild>>>);
|
||||
|
||||
/// Manager for safe processes like ingress feeds which need to be safely shut down.
|
||||
pub struct IngressProcessor {
|
||||
/// A vector of ingress feed uuids.
|
||||
pub ingress_feeds: Vec<Uuid>,
|
||||
}
|
||||
|
||||
/// A type of Ingress safety process.
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub enum IngressProcessType {
|
||||
/// A single Ingress feed.
|
||||
IngressFeed,
|
||||
// Writes,
|
||||
// Reads,
|
||||
// Fetch,
|
||||
}
|
||||
|
||||
impl IngressProcessor {
|
||||
/// Initialize a new ingresss process manager.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
ingress_feeds: Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Add an ingress safety process to the HashMap.
|
||||
pub async fn add_ingress(
|
||||
r#type: IngressProcessType,
|
||||
uuid: Uuid,
|
||||
) -> crate::Result<Uuid> {
|
||||
let state = State::get().await?;
|
||||
let mut ingress_processor = state.ingress_processor.write().await;
|
||||
match r#type {
|
||||
IngressProcessType::IngressFeed => {
|
||||
ingress_processor.ingress_feeds.push(uuid);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(uuid)
|
||||
}
|
||||
|
||||
/// Complete and retain an ingress safety process from the HashMap of ingress feeds.
|
||||
pub async fn finish(
|
||||
r#type: IngressProcessType,
|
||||
uuid: Uuid,
|
||||
) -> crate::Result<()> {
|
||||
let state = State::get().await?;
|
||||
let mut ingress_processor = state.ingress_processor.write().await;
|
||||
match r#type {
|
||||
IngressProcessType::IngressFeed => {
|
||||
ingress_processor.ingress_feeds.retain(|f| *f != uuid);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Finish and check if an ingress safety processes ingress feed is empty and finished.
|
||||
pub async fn finished(
|
||||
r#type: IngressProcessType,
|
||||
) -> crate::Result<bool> {
|
||||
let state = State::get().await?;
|
||||
let ingress_processor = state.ingress_processor.read().await;
|
||||
match r#type {
|
||||
IngressProcessType::IngressFeed => {
|
||||
if ingress_processor.ingress_feeds.is_empty() {
|
||||
return Ok(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// A child process type.
|
||||
#[derive(Debug)]
|
||||
pub enum ChildType {
|
||||
/// A tokio-managed child process.
|
||||
ChildProcess(Child),
|
||||
/// A restored child from a process cache that needs to be re-registered.
|
||||
RescuedChild(u32),
|
||||
}
|
||||
|
||||
/// A structure representing a cache of a running process.
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ProcessorCache {
|
||||
/// The PID of a process.
|
||||
pub pid: u32,
|
||||
/// The stored UUID of a process.
|
||||
pub uuid: Uuid,
|
||||
/// The time a process started.
|
||||
pub start_time: u64,
|
||||
/// The name of a process.
|
||||
pub name: String,
|
||||
/// The executable file running the process.
|
||||
pub exe: String,
|
||||
/// The associated [`ClusterPath`] to a process.
|
||||
pub cluster_path: ClusterPath,
|
||||
/// A post hook to be run once a process has completed.
|
||||
pub post: Option<String>,
|
||||
}
|
||||
|
||||
impl ChildType {
|
||||
/// Get the PID of a specific ChildType process.
|
||||
pub fn id(&self) -> Option<u32> {
|
||||
match self {
|
||||
ChildType::ChildProcess(child) => child.id(),
|
||||
ChildType::RescuedChild(pid) => Some(*pid),
|
||||
}
|
||||
}
|
||||
|
||||
/// Store a cache of a specific ChildType.
|
||||
pub async fn cache(&self, uuid: Uuid, cluster_path: ClusterPath, post: Option<String>) -> crate::Result<()> {
|
||||
let pid = match self {
|
||||
ChildType::ChildProcess(child) => child.id().unwrap_or(0),
|
||||
ChildType::RescuedChild(pid) => *pid,
|
||||
};
|
||||
|
||||
let state = crate::State::get().await?;
|
||||
let mut system = sysinfo::System::new();
|
||||
|
||||
system.refresh_processes();
|
||||
let process = system.process(sysinfo::Pid::from_u32(pid)).ok_or_else(|| {
|
||||
anyhow::anyhow!("could not find process {}", pid)
|
||||
})?;
|
||||
let start_time = process.start_time();
|
||||
let name = process.name().to_string();
|
||||
let Some(path) = process.exe() else {
|
||||
return Err(anyhow::anyhow!("cached process {} has no path", pid).into())
|
||||
};
|
||||
|
||||
let exe = path.to_string_lossy().to_string();
|
||||
let cached_proccess = ProcessorCache {
|
||||
pid,
|
||||
uuid,
|
||||
start_time,
|
||||
name,
|
||||
exe,
|
||||
cluster_path,
|
||||
post,
|
||||
};
|
||||
|
||||
let path = state
|
||||
.directories
|
||||
.caches_dir()
|
||||
.await
|
||||
.join(PROCESSOR_JSON);
|
||||
let mut caches = if let Ok(proc_json) =
|
||||
read_json::<HashMap<Uuid, ProcessorCache>>(
|
||||
&path,
|
||||
&state.io_semaphore,
|
||||
).await
|
||||
{
|
||||
proc_json
|
||||
} else {
|
||||
HashMap::new()
|
||||
};
|
||||
|
||||
caches.insert(uuid, cached_proccess);
|
||||
crate::utils::http::write(
|
||||
&path,
|
||||
&serde_json::to_vec(&caches)?,
|
||||
&state.io_semaphore,
|
||||
).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove a child from the global store of processes.
|
||||
pub async fn remove(&self, uuid: Uuid) -> crate::Result<()> {
|
||||
let state = crate::State::get().await?;
|
||||
|
||||
let path = state
|
||||
.directories
|
||||
.caches_dir()
|
||||
.await
|
||||
.join(PROCESSOR_JSON);
|
||||
let mut caches = if let Ok(proc_json) =
|
||||
read_json::<HashMap<Uuid, ProcessorCache>>(
|
||||
&path,
|
||||
&state.io_semaphore,
|
||||
).await
|
||||
{
|
||||
proc_json
|
||||
} else {
|
||||
HashMap::new()
|
||||
};
|
||||
caches.remove(&uuid);
|
||||
crate::utils::http::write(
|
||||
&path,
|
||||
&serde_json::to_vec(&caches)?,
|
||||
&state.io_semaphore,
|
||||
).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Kill a process in the global store of processes.
|
||||
pub async fn kill(&mut self) -> crate::Result<()> {
|
||||
match self {
|
||||
ChildType::ChildProcess(child) => {
|
||||
Ok(child.kill().await.map_err(IOError::from)?)
|
||||
}
|
||||
ChildType::RescuedChild(pid) => {
|
||||
let mut system = sysinfo::System::new();
|
||||
if system.refresh_process(sysinfo::Pid::from_u32(*pid)) {
|
||||
let process = system.process(sysinfo::Pid::from_u32(*pid));
|
||||
if let Some(process) = process {
|
||||
process.kill();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for a process to complete.
|
||||
pub async fn try_wait(&mut self) -> crate::Result<Option<i32>> {
|
||||
match self {
|
||||
ChildType::ChildProcess(child) => Ok(child
|
||||
.try_wait()
|
||||
.map_err(IOError::from)?
|
||||
.map(|x| x.code().unwrap_or(0))),
|
||||
ChildType::RescuedChild(pid) => {
|
||||
let mut system = sysinfo::System::new();
|
||||
if !system.refresh_process(sysinfo::Pid::from_u32(*pid)) {
|
||||
return Ok(Some(0))
|
||||
}
|
||||
|
||||
let process = system.process(sysinfo::Pid::from_u32(*pid));
|
||||
if let Some(process) = process {
|
||||
if process.status() == sysinfo::ProcessStatus::Run {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(0))
|
||||
}
|
||||
} else {
|
||||
Ok(Some(0))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`Processor`] child process.
|
||||
#[derive(Debug)]
|
||||
pub struct ProcessorChild {
|
||||
/// The uuid of a process.
|
||||
pub uuid: Uuid,
|
||||
/// The associated [`ClusterPath`] to a process.
|
||||
pub cluster_path: ClusterPath,
|
||||
/// The process manager managing this process.
|
||||
pub manager: Option<JoinHandle<crate::Result<i32>>>,
|
||||
/// The [`ChildType`] of this process.
|
||||
pub current_child: Arc<RwLock<ChildType>>,
|
||||
/// When this process was last updated in [`Utc`].
|
||||
pub last_updated: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl Processor {
|
||||
/// Get a new [`Processor`] instance.
|
||||
pub fn new() -> Self {
|
||||
Processor(HashMap::new())
|
||||
}
|
||||
|
||||
/// Returns a reference to the value corresponding to the key.
|
||||
pub fn get(&self, uuid: &Uuid) -> Option<Arc<RwLock<ProcessorChild>>> {
|
||||
self.0.get(uuid).cloned()
|
||||
}
|
||||
|
||||
/// An collection visiting all keys in arbitrary order.
|
||||
pub fn keys(&self) -> Vec<Uuid> {
|
||||
self.0.keys().cloned().collect()
|
||||
}
|
||||
|
||||
/// Get all running processes.
|
||||
pub async fn running(&self) -> crate::Result<Vec<Uuid>> {
|
||||
let mut keys = Vec::new();
|
||||
for key in self.keys() {
|
||||
if let Some(process) = self.get(&key) {
|
||||
let process = process.clone();
|
||||
let process = process.write().await;
|
||||
if process.current_child.write().await.try_wait().await?.is_none() {
|
||||
keys.push(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
/// Get all running cluster processes.
|
||||
pub async fn running_cluster(&self, cluster_path: ClusterPath) -> crate::Result<Vec<Uuid>> {
|
||||
let running = self.running().await?;
|
||||
let mut keys = Vec::new();
|
||||
for key in running {
|
||||
if let Some(process) = self.get(&key) {
|
||||
let process = process.clone();
|
||||
let process = process.read().await;
|
||||
if process.cluster_path == cluster_path {
|
||||
keys.push(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
/// get all running cluster paths.
|
||||
pub async fn running_cluster_paths(&self) -> crate::Result<Vec<ClusterPath>> {
|
||||
let mut clusters = Vec::new();
|
||||
for key in self.keys() {
|
||||
if let Some(process) = self.get(&key) {
|
||||
let process = process.clone();
|
||||
let process = process.write().await;
|
||||
if process.current_child.write().await.try_wait().await?.is_none() {
|
||||
clusters.push(process.cluster_path.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(clusters)
|
||||
}
|
||||
|
||||
/// get all running clusters.
|
||||
pub async fn running_clusters(&self) -> crate::Result<Vec<Cluster>> {
|
||||
let mut clusters = Vec::new();
|
||||
for key in self.keys() {
|
||||
if let Some(process) = self.get(&key) {
|
||||
let process = process.clone();
|
||||
let process = process.write().await;
|
||||
if process.current_child.write().await.try_wait().await?.is_none() {
|
||||
if let Some(cluster) = cluster::get(&process.cluster_path.clone(), None).await? {
|
||||
clusters.push(cluster);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(clusters)
|
||||
}
|
||||
|
||||
/// get the exit status of a process by its [`Uuid`].
|
||||
pub async fn exit_status(&self, uuid: &Uuid) -> crate::Result<Option<i32>> {
|
||||
if let Some(process) = self.get(uuid) {
|
||||
let process = process.write().await;
|
||||
let status = process.current_child.write().await.try_wait().await?;
|
||||
Ok(status)
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// restore processes from the cache.
|
||||
pub async fn restore(&mut self) -> crate::Result<()> {
|
||||
let state = crate::State::get().await?;
|
||||
let processor_path = state.directories.caches_dir().await.join(PROCESSOR_JSON);
|
||||
|
||||
let mut processor_caches = if let Ok(processes_json) =
|
||||
read_json::<HashMap<uuid::Uuid, ProcessorCache>>(
|
||||
&processor_path,
|
||||
&state.io_semaphore,
|
||||
)
|
||||
.await
|
||||
{
|
||||
let zeros = HashMap::<uuid::Uuid, ProcessorCache>::new();
|
||||
crate::utils::http::write(&processor_path, &serde_json::to_vec(&zeros)?, &state.io_semaphore).await?;
|
||||
processes_json
|
||||
} else {
|
||||
HashMap::new()
|
||||
};
|
||||
|
||||
for (_, cache) in processor_caches.drain() {
|
||||
let uuid = cache.uuid;
|
||||
match self.insert_restored(cache).await {
|
||||
Ok(process) => {
|
||||
self.0.insert(uuid, process);
|
||||
}
|
||||
Err(e) => tracing::warn!("failed to restore process {}: {}", uuid, e),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
/// insert a process with a command and [`ClusterPath`].
|
||||
#[tracing::instrument(skip(self, uuid, command, post, censors))]
|
||||
#[tracing::instrument(level = "trace", skip(self))]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn insert_process(
|
||||
&mut self,
|
||||
uuid: Uuid,
|
||||
cluster_path: ClusterPath,
|
||||
mut command: Command,
|
||||
post: Option<String>,
|
||||
censors: HashMap<String, String>
|
||||
) -> crate::Result<Arc<RwLock<ProcessorChild>>> {
|
||||
let proc = command.spawn().map_err(IOError::from)?;
|
||||
let process = ChildType::ChildProcess(proc);
|
||||
let pid = process.id().ok_or_else(|| anyhow::anyhow!("process failed, couldn't get pid"))?;
|
||||
process.cache(uuid, cluster_path.clone(), post.clone()).await?;
|
||||
|
||||
let current_child = Arc::new(RwLock::new(process));
|
||||
let manager = Some(tokio::spawn(Self::manager(
|
||||
uuid,
|
||||
post,
|
||||
pid,
|
||||
current_child.clone(),
|
||||
cluster_path.clone(),
|
||||
)));
|
||||
|
||||
send_process(uuid, pid, ProcessPayloadType::Started, "started process").await?;
|
||||
let last_updated = Utc::now();
|
||||
let child = ProcessorChild { uuid, cluster_path, current_child, manager, last_updated };
|
||||
let child = Arc::new(RwLock::new(child));
|
||||
self.0.insert(uuid, child.clone());
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Insert a cached process with a [`ProcessorCache`].
|
||||
#[tracing::instrument(skip(self, cache))]
|
||||
#[tracing::instrument(level = "trace", skip(self))]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn insert_restored(
|
||||
&mut self,
|
||||
cache: ProcessorCache,
|
||||
) -> crate::Result<Arc<RwLock<ProcessorChild>>> {
|
||||
let _state = crate::State::get().await?;
|
||||
|
||||
// ensure located stray process matches with our pid recorded process
|
||||
{
|
||||
let mut system = sysinfo::System::new();
|
||||
system.refresh_processes();
|
||||
let process = system
|
||||
.process(sysinfo::Pid::from_u32(cache.pid))
|
||||
.ok_or_else(|| anyhow::anyhow!("could not find pid {}", cache.pid))?;
|
||||
|
||||
if cache.start_time != process.start_time() {
|
||||
return Err(anyhow::anyhow!("restored process {} has a mismatched start time {}", cache.pid, process.start_time()).into());
|
||||
}
|
||||
if cache.name != process.name() {
|
||||
return Err(anyhow::anyhow!("restored process {} has a mismatched name {}", cache.pid, process.name()).into());
|
||||
}
|
||||
|
||||
if let Some(path) = process.exe() {
|
||||
if cache.exe != path.to_string_lossy() {
|
||||
return Err(anyhow::anyhow!("restored process {} has a mismatched exe {}", cache.pid, path.to_string_lossy()).into());
|
||||
}
|
||||
} else {
|
||||
return Err(anyhow::anyhow!("restored process {} has no exe path", cache.pid).into());
|
||||
}
|
||||
}
|
||||
|
||||
let process = ChildType::RescuedChild(cache.pid);
|
||||
let pid = process.id().ok_or_else(|| anyhow::anyhow!("process failed, couldnt get pid"))?;
|
||||
process.cache(cache.uuid, cache.cluster_path.clone(), cache.post.clone()).await?;
|
||||
let current_child = Arc::new(RwLock::new(process));
|
||||
let manager = Some(tokio::spawn(Self::manager(
|
||||
cache.uuid,
|
||||
cache.post,
|
||||
pid,
|
||||
current_child.clone(),
|
||||
cache.cluster_path.clone(),
|
||||
)));
|
||||
|
||||
send_process(cache.uuid, pid, ProcessPayloadType::Started, "started process").await?;
|
||||
|
||||
let last_updated = Utc::now();
|
||||
let child = ProcessorChild {
|
||||
uuid: cache.uuid,
|
||||
cluster_path: cache.cluster_path,
|
||||
current_child,
|
||||
manager,
|
||||
last_updated,
|
||||
};
|
||||
|
||||
let child = Arc::new(RwLock::new(child));
|
||||
self.0.insert(cache.uuid, child.clone());
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Get a process manager and runner awaiting for the exit status.
|
||||
#[tracing::instrument(skip(current_child))]
|
||||
#[onelauncher_debug::debugger]
|
||||
async fn manager(
|
||||
uuid: Uuid,
|
||||
post: Option<String>,
|
||||
mut current_pid: u32,
|
||||
current_child: Arc<RwLock<ChildType>>,
|
||||
cluster_path: ClusterPath,
|
||||
) -> crate::Result<i32> {
|
||||
let current_child = current_child.clone();
|
||||
let mut exit_status;
|
||||
let mut last_updated = Utc::now();
|
||||
|
||||
// core main process loop, managed by tokio
|
||||
loop {
|
||||
if let Some(stat) = current_child.write().await.try_wait().await? {
|
||||
exit_status = stat;
|
||||
break;
|
||||
}
|
||||
|
||||
tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
|
||||
let update = Utc::now().signed_duration_since(last_updated).num_seconds();
|
||||
if update >= 60 {
|
||||
if let Err(err) = cluster::edit(&cluster_path, |cluster| {
|
||||
cluster.meta.recently_played += update as u64;
|
||||
async { Ok(()) }
|
||||
}).await {
|
||||
tracing::warn!("failed to update playtime for cluster {}: {}", &cluster_path, err);
|
||||
}
|
||||
last_updated = Utc::now();
|
||||
}
|
||||
}
|
||||
|
||||
let update = Utc::now().signed_duration_since(last_updated).num_seconds();
|
||||
if let Err(err) = cluster::edit(&cluster_path, |cluster| {
|
||||
cluster.meta.recently_played += update as u64;
|
||||
async { Ok(()) }
|
||||
}).await {
|
||||
tracing::warn!("failed to update playtime for cluster {}: {}", &cluster_path, err);
|
||||
}
|
||||
|
||||
let cluster_path_in = cluster_path.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = cluster::update_playtime(&cluster_path_in).await {
|
||||
tracing::warn!("failed to update playtime for cluster {}: {}", &cluster_path_in, err);
|
||||
}
|
||||
});
|
||||
|
||||
{
|
||||
let state = crate::State::get().await?;
|
||||
let _ = state.discord_rpc.clear(true).await;
|
||||
}
|
||||
|
||||
#[cfg(feature = "tauri")]
|
||||
{
|
||||
let window = crate::ProxyState::get_main_window().await?;
|
||||
window.unminimize()?;
|
||||
}
|
||||
|
||||
{
|
||||
let current_child = current_child.write().await;
|
||||
current_child.remove(uuid).await?;
|
||||
}
|
||||
|
||||
if !exit_status == 0 {
|
||||
send_process(uuid, current_pid, ProcessPayloadType::Finished, "exited process").await?;
|
||||
|
||||
return Ok(exit_status);
|
||||
}
|
||||
|
||||
let post = if let Some(hook) = post {
|
||||
let mut cmd = hook.split(' ');
|
||||
if let Some(c) = cmd.next() {
|
||||
let mut c = Command::new(c);
|
||||
c.args(&cmd.collect::<Vec<&str>>()).current_dir(cluster_path.full_path().await?);
|
||||
Some(c)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(mut m_c) = post {
|
||||
{
|
||||
let mut current_child: tokio::sync::RwLockWriteGuard<'_, ChildType> = current_child.write().await;
|
||||
let new_child = m_c.spawn().map_err(IOError::from)?;
|
||||
current_pid = new_child.id().ok_or_else(|| anyhow::anyhow!("process failed, couldnt get pid"))?;
|
||||
*current_child = ChildType::ChildProcess(new_child);
|
||||
}
|
||||
|
||||
send_process(uuid, current_pid, ProcessPayloadType::Modified, "running post hook").await?;
|
||||
|
||||
loop {
|
||||
if let Some(stat) = current_child.write().await.try_wait().await? {
|
||||
exit_status = stat;
|
||||
break;
|
||||
}
|
||||
|
||||
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
}
|
||||
|
||||
send_process(uuid, current_pid, ProcessPayloadType::Finished, "exited process").await?;
|
||||
|
||||
Ok(exit_status)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Processor {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
174
core/src/store/settings.rs
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
//! Handles user-inputted settings and global values
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::utils::io;
|
||||
use super::{Directories, JavaVersions};
|
||||
|
||||
/// The current [`Settings`] format version, changed for breaking changes.
|
||||
/// If updated, a config file migration logic **NEEDS** to be implemented.
|
||||
const CURRENT_FORMAT_VERSION: u32 = 1;
|
||||
|
||||
/// A global settings state for the launcher.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct Settings {
|
||||
/// A OneLauncher [`Theme`] managed by the core GUI.
|
||||
pub theme: Theme,
|
||||
/// A global fullscreen Minecraft state.
|
||||
#[serde(default)]
|
||||
pub force_fullscreen: bool,
|
||||
/// A global default [`Resolution`] for Minecraft.
|
||||
pub resolution: Resolution,
|
||||
/// A global [`JavaVersions`] list and default version.
|
||||
pub java_versions: JavaVersions,
|
||||
/// A global [`Memory`] settings store for Java memory settings.
|
||||
pub memory: Memory,
|
||||
/// Global and default initialization hooks .
|
||||
pub init_hooks: InitHooks,
|
||||
/// Global and default custom Java arguments.
|
||||
pub custom_jvm_args: Vec<String>,
|
||||
/// Global and default custom environment variables.
|
||||
pub custom_env_args: Vec<(String, String)>,
|
||||
/// Global and default maximum [`Semaphore`] I/O operations.
|
||||
pub max_async_io_operations: usize,
|
||||
/// Global and default maximum [`Semaphore`] HTTP operations.
|
||||
pub max_async_fetches: usize,
|
||||
/// The [`CURRENT_FORMAT_VERSION`] of this settings file.
|
||||
pub version: u32,
|
||||
/// Whether or not to disable Discord IPC.
|
||||
#[serde(default)]
|
||||
pub disable_discord: bool,
|
||||
/// Whether or not to enable a debug mode in the launcher.
|
||||
#[serde(default)]
|
||||
pub debug_mode: bool,
|
||||
/// Whether or not to disable Plausible and Sentry analytics.
|
||||
#[serde(default)]
|
||||
pub disable_analytics: bool,
|
||||
/// The core global config directory stored as a [`PathBuf`].
|
||||
#[serde(default = "Directories::init_settings_dir")]
|
||||
pub config_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
/// Initializes the global settings state.
|
||||
#[tracing::instrument]
|
||||
pub async fn initialize(file: &Path) -> crate::Result<Self> {
|
||||
let mut recovered_corruption = false;
|
||||
|
||||
let settings = if file.exists() {
|
||||
let read_settings = io::read(&file)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
anyhow::anyhow!("error reading settings file: {0}", err).into()
|
||||
})
|
||||
.and_then(|it| {
|
||||
serde_json::from_slice::<Settings>(&it)
|
||||
.map_err(crate::Error::from)
|
||||
});
|
||||
|
||||
if let Err(ref err) = read_settings {
|
||||
tracing::error!("failed to load settings file: {err}.");
|
||||
let backup = file.with_extension("json.bak");
|
||||
tracing::error!("corrupted settings will be backed up as {}, and a new one will be created", backup.display());
|
||||
let _ = io::rename(file, backup).await;
|
||||
recovered_corruption = true;
|
||||
}
|
||||
|
||||
read_settings.ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(settings) = settings {
|
||||
Ok(settings)
|
||||
} else {
|
||||
let settings = Self {
|
||||
theme: Theme::Dark,
|
||||
force_fullscreen: false,
|
||||
resolution: Resolution::default(),
|
||||
java_versions: JavaVersions::new(),
|
||||
memory: Memory::default(),
|
||||
init_hooks: InitHooks::default(),
|
||||
custom_env_args: Vec::new(),
|
||||
custom_jvm_args: Vec::new(),
|
||||
max_async_fetches: 10,
|
||||
max_async_io_operations: 10,
|
||||
version: CURRENT_FORMAT_VERSION,
|
||||
disable_analytics: false,
|
||||
disable_discord: false,
|
||||
debug_mode: false,
|
||||
config_dir: Directories::init_settings_dir(),
|
||||
};
|
||||
|
||||
if recovered_corruption {
|
||||
settings.sync(file).await?;
|
||||
}
|
||||
|
||||
Ok(settings)
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronizes the current settings from a file.
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub async fn sync(&self, to: &Path) -> crate::Result<()> {
|
||||
io::write(to, serde_json::to_vec(self)?).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A OneLauncher theme managed by the GUI.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Theme {
|
||||
/// A default Dark theme.
|
||||
Dark,
|
||||
/// A default Light theme.
|
||||
Light,
|
||||
/// OLED Dark Theme.
|
||||
Contrast,
|
||||
/// Cute and colorful theme.
|
||||
Cat,
|
||||
}
|
||||
|
||||
/// Global memory settings across all clusters.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
|
||||
pub struct Memory {
|
||||
/// Maximum amount of Java memory available globally.
|
||||
pub maximum: u32,
|
||||
/// Minimum amount of Java memory available globally.
|
||||
pub minimum: u32,
|
||||
}
|
||||
|
||||
impl Default for Memory {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
maximum: 2048,
|
||||
minimum: 256,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Global Minecraft resolution.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
|
||||
pub struct Resolution(pub u16, pub u16);
|
||||
|
||||
impl Default for Resolution {
|
||||
fn default() -> Self {
|
||||
Self(854, 480)
|
||||
}
|
||||
}
|
||||
|
||||
/// Global initialization hooks for all Minecraft clusters.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
|
||||
#[serde(default)]
|
||||
pub struct InitHooks {
|
||||
/// Pre-launch hook.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub pre: Option<String>,
|
||||
/// Wrapper hook for the runtime of the game instance.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub wrapper: Option<String>,
|
||||
/// Post-launch hook.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub post: Option<String>,
|
||||
}
|
||||
304
core/src/utils/http.rs
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
//! **HTTP Utilities**
|
||||
//!
|
||||
//! Async extensions and wrappers around [`reqwest`] functions.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::path::PathBuf;
|
||||
use std::{path::Path, time::Duration};
|
||||
|
||||
use reqwest::Method;
|
||||
use serde::de::DeserializeOwned;
|
||||
use tokio::sync::{RwLock, Semaphore};
|
||||
use tokio::fs::File;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use bytes::Bytes;
|
||||
|
||||
use crate::proxy::send::send_ingress;
|
||||
use crate::utils::io;
|
||||
use crate::proxy::IngressId;
|
||||
|
||||
use super::io::IOError;
|
||||
|
||||
/// A [`Semaphore`] used for all I/O operations.
|
||||
#[derive(Debug)]
|
||||
pub struct IoSemaphore(pub RwLock<Semaphore>);
|
||||
/// A [`Semaphore`] used for all HTTP operations.
|
||||
#[derive(Debug)]
|
||||
pub struct FetchSemaphore(pub RwLock<Semaphore>);
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
/// A public reqwest client with configured headers.
|
||||
pub static ref REQWEST_CLIENT: reqwest::Client = {
|
||||
let mut headers = reqwest::header::HeaderMap::new();
|
||||
let header = reqwest::header::HeaderValue::from_str(&format!(
|
||||
"onelauncher/{} (polyfrost.org)",
|
||||
env!("CARGO_PKG_VERSION")
|
||||
)).unwrap();
|
||||
headers.insert(reqwest::header::USER_AGENT, header);
|
||||
reqwest::Client::builder()
|
||||
.tcp_keepalive(Some(std::time::Duration::from_secs(15)))
|
||||
.default_headers(headers)
|
||||
.build()
|
||||
.expect("failed to build reqwest client!")
|
||||
};
|
||||
}
|
||||
|
||||
/// The amount of attempts to fetch a file before the request fails.
|
||||
const FETCH_ATTEMPTS: usize = 3;
|
||||
|
||||
/// Basic HTTP fetch interface.
|
||||
#[tracing::instrument(skip(semaphore))]
|
||||
pub async fn fetch(
|
||||
url: &str,
|
||||
sha1: Option<&str>,
|
||||
semaphore: &FetchSemaphore,
|
||||
) -> crate::Result<Bytes> {
|
||||
fetch_advanced(
|
||||
Method::GET,
|
||||
url,
|
||||
sha1,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
semaphore,
|
||||
).await
|
||||
}
|
||||
|
||||
/// Basic JSON fetch interface.
|
||||
#[tracing::instrument(skip(json_body, semaphore))]
|
||||
pub async fn fetch_json<T>(
|
||||
method: Method,
|
||||
url: &str,
|
||||
sha1: Option<&str>,
|
||||
json_body: Option<serde_json::Value>,
|
||||
semaphore: &FetchSemaphore,
|
||||
) -> crate::Result<T>
|
||||
where
|
||||
T: DeserializeOwned,
|
||||
{
|
||||
let result = fetch_advanced(
|
||||
method,
|
||||
url,
|
||||
sha1,
|
||||
json_body,
|
||||
None,
|
||||
None,
|
||||
semaphore,
|
||||
).await?;
|
||||
|
||||
let value = serde_json::from_slice(&result)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// Advanced HTTP fetch interface with json, sha1 validation, and ingress support.
|
||||
#[tracing::instrument(skip(json_body, semaphore))]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn fetch_advanced(
|
||||
method: Method,
|
||||
url: &str,
|
||||
sha1: Option<&str>,
|
||||
json_body: Option<serde_json::Value>,
|
||||
header: Option<(&str, &str)>,
|
||||
ingress: Option<(&IngressId, f64)>,
|
||||
semaphore: &FetchSemaphore,
|
||||
) -> crate::Result<Bytes> {
|
||||
let io_semaphore = semaphore.0.read().await;
|
||||
let _permit = io_semaphore.acquire().await?;
|
||||
|
||||
for attempt in 1..=(FETCH_ATTEMPTS + 1) {
|
||||
let mut req = REQWEST_CLIENT.request(method.clone(), url);
|
||||
|
||||
if let Some(body) = json_body.clone() {
|
||||
req = req.json(&body)
|
||||
}
|
||||
|
||||
if let Some(header) = header {
|
||||
req = req.header(header.0, header.1);
|
||||
}
|
||||
|
||||
let result = req.send().await;
|
||||
|
||||
match result {
|
||||
Ok(x) => {
|
||||
let bytes = if let Some((feed, total)) = &ingress {
|
||||
let length = x.content_length();
|
||||
if let Some(total_size) = length {
|
||||
use futures::StreamExt;
|
||||
let mut stream = x.bytes_stream();
|
||||
let mut bytes = Vec::new();
|
||||
while let Some(item) = stream.next().await {
|
||||
let chunk = item.or(Err(anyhow::anyhow!("no value for fetch bytes")))?;
|
||||
bytes.append(&mut chunk.to_vec());
|
||||
send_ingress(feed, (chunk.len() as f64 / total_size as f64) * total, None).await?;
|
||||
}
|
||||
|
||||
Ok(bytes::Bytes::from(bytes))
|
||||
} else {
|
||||
x.bytes().await
|
||||
}
|
||||
} else {
|
||||
x.bytes().await
|
||||
};
|
||||
|
||||
if let Ok(bytes) = bytes {
|
||||
if let Some(sha1) = sha1 {
|
||||
let hash = check_sha1(bytes.clone()).await?;
|
||||
if &*hash != sha1 {
|
||||
if attempt <= 3 {
|
||||
continue;
|
||||
} else {
|
||||
return Err(anyhow::anyhow!("hash {0} does not match {1}", sha1.to_string(), hash).into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracing::trace!("finished downloading {url}");
|
||||
return Ok(bytes);
|
||||
} else if attempt <= 3 {
|
||||
continue;
|
||||
} else if let Err(err) = bytes {
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
Err(_) if attempt <= 3 => continue,
|
||||
Err(err) => { return Err(err.into()); }
|
||||
}
|
||||
}
|
||||
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
/// A utility to fetch from multiple mirrored sources.
|
||||
#[tracing::instrument(skip(semaphore))]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn fetch_from_mirrors(
|
||||
mirrors: &[&str],
|
||||
sha1: Option<&str>,
|
||||
semaphore: &FetchSemaphore,
|
||||
) -> crate::Result<Bytes> {
|
||||
if mirrors.is_empty() {
|
||||
return Err(anyhow::anyhow!("no mirrors provided!").into());
|
||||
}
|
||||
|
||||
for (index, mirror) in mirrors.iter().enumerate() {
|
||||
let result = fetch(mirror, sha1, semaphore).await;
|
||||
if result.is_ok() || (result.is_err() && index == (mirrors.len() - 1)) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
/// Checks if we are playing offline by contacting a reliable server.
|
||||
#[tracing::instrument]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn check_internet_connection(timeout: u64) -> bool {
|
||||
REQWEST_CLIENT
|
||||
.get("https://api.polyfrost.org/")
|
||||
.timeout(Duration::from_secs(timeout))
|
||||
.send()
|
||||
.await
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
/// Post JSON to a specified URL (helpful for Microsoft auth)
|
||||
#[tracing::instrument(skip(json_body, semaphore))]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn post_json<T>(
|
||||
url: &str,
|
||||
json_body: serde_json::Value,
|
||||
semaphore: &FetchSemaphore,
|
||||
) -> crate::Result<T>
|
||||
where
|
||||
T: DeserializeOwned,
|
||||
{
|
||||
let io_semaphore = semaphore.0.read().await;
|
||||
let _permit = io_semaphore.acquire().await?;
|
||||
|
||||
let req = REQWEST_CLIENT.post(url).json(&json_body);
|
||||
|
||||
let result = req.send().await?.error_for_status()?;
|
||||
let value = result.json().await?;
|
||||
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// Read JSON from a specified [`Path`].
|
||||
pub async fn read_json<T>(
|
||||
path: &Path,
|
||||
semaphore: &IoSemaphore,
|
||||
) -> crate::Result<T>
|
||||
where
|
||||
T: DeserializeOwned,
|
||||
{
|
||||
let io_semaphore = semaphore.0.read().await;
|
||||
let _permit = io_semaphore.acquire().await?;
|
||||
|
||||
let json = io::read(path).await?;
|
||||
let json = serde_json::from_slice::<T>(&json)?;
|
||||
|
||||
Ok(json)
|
||||
}
|
||||
|
||||
/// Write to a file at a specified [`Path`].
|
||||
#[tracing::instrument(skip(bytes, semaphore))]
|
||||
pub async fn write<'a>(
|
||||
path: &Path,
|
||||
bytes: &[u8],
|
||||
semaphore: &IoSemaphore,
|
||||
) -> crate::Result<()> {
|
||||
let io_semaphore = semaphore.0.read().await;
|
||||
let _permit = io_semaphore.acquire().await?;
|
||||
|
||||
if let Some(parent) = path.parent() {
|
||||
io::create_dir_all(parent).await?;
|
||||
}
|
||||
|
||||
let mut file = File::create(path).await.map_err(|e| IOError::with_path(e, path))?;
|
||||
file.write_all(bytes).await.map_err(|e| IOError::with_path(e, path))?;
|
||||
tracing::trace!("done writing to file {}", path.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Copy a file from one [`AsRef<Path>`] to another.
|
||||
pub async fn copy(
|
||||
src: impl AsRef<std::path::Path>,
|
||||
dest: impl AsRef<std::path::Path>,
|
||||
semaphore: &IoSemaphore,
|
||||
) -> crate::Result<()> {
|
||||
let src = src.as_ref();
|
||||
let dest = dest.as_ref();
|
||||
|
||||
let io_semaphore = semaphore.0.read().await;
|
||||
let _permit = io_semaphore.acquire().await?;
|
||||
|
||||
if let Some(parent) = dest.parent() {
|
||||
io::create_dir_all(parent).await?;
|
||||
}
|
||||
|
||||
io::copy(src, dest).await?;
|
||||
tracing::trace!("done copying file from {} to {}", src.display(), dest.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(bytes, io_semaphore))]
|
||||
pub async fn write_icon(icon_path: &str, cache_path: &Path, bytes: Bytes, io_semaphore: &IoSemaphore) -> crate::Result<PathBuf> {
|
||||
let ext = Path::new(&icon_path).extension().and_then(OsStr::to_str);
|
||||
let hash = check_sha1(bytes.clone()).await?;
|
||||
let path = cache_path.join("icons").join(if let Some(e) = ext { format!("{hash}.{e}") } else { hash });
|
||||
|
||||
write(&path, &bytes, io_semaphore).await?;
|
||||
|
||||
let path = io::canonicalize(path)?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Get the Sha1 hash of [`bytes::Bytes`] array.
|
||||
pub async fn check_sha1(bytes: Bytes) -> crate::Result<String> {
|
||||
let hash = tokio::task::spawn_blocking(move || {
|
||||
sha1_smol::Sha1::from(bytes).hexdigest()
|
||||
}).await?;
|
||||
|
||||
Ok(hash)
|
||||
}
|
||||
209
core/src/utils/io.rs
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
//! **IO Utilities**
|
||||
//!
|
||||
//! Wrapper around [`tokio::io`] for our error system.
|
||||
|
||||
use std::{fs::File, io::Write, path::PathBuf};
|
||||
|
||||
use anyhow::anyhow;
|
||||
use tempfile::NamedTempFile;
|
||||
use tauri::async_runtime::spawn_blocking;
|
||||
|
||||
/// A wrapper around generic and unhelpful [`std::io::Error`] messages.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum IOError {
|
||||
#[error("{source}, path: {path}")]
|
||||
IOErrorWrapper {
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
path: String,
|
||||
},
|
||||
#[error(transparent)]
|
||||
ZipError(#[from] zip::result::ZipError),
|
||||
#[error(transparent)]
|
||||
IOError(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
impl IOError {
|
||||
pub fn from(source: std::io::Error) -> Self {
|
||||
Self::IOError(source)
|
||||
}
|
||||
|
||||
pub fn from_zip(source: zip::result::ZipError) -> Self {
|
||||
Self::ZipError(source)
|
||||
}
|
||||
|
||||
pub fn with_path(
|
||||
source: std::io::Error,
|
||||
path: impl AsRef<std::path::Path>,
|
||||
) -> Self {
|
||||
let path = path.as_ref().to_string_lossy().to_string();
|
||||
|
||||
Self::IOErrorWrapper { source, path }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// An OS specific wrapper of [`std::fs::canonicalize`], but on Windows it outputs the most compatible form of a path instead of UNC.
|
||||
pub fn canonicalize(
|
||||
path: impl AsRef<std::path::Path>,
|
||||
) -> Result<std::path::PathBuf, IOError> {
|
||||
let path = path.as_ref();
|
||||
dunce::canonicalize(path).map_err(|e| IOError::IOErrorWrapper {
|
||||
source: e,
|
||||
path: path.to_string_lossy().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns a stream over the entries within a directory.
|
||||
pub async fn read_dir(
|
||||
path: impl AsRef<std::path::Path>,
|
||||
) -> Result<tokio::fs::ReadDir, IOError> {
|
||||
let path = path.as_ref();
|
||||
tokio::fs::read_dir(path)
|
||||
.await
|
||||
.map_err(|e| IOError::IOErrorWrapper {
|
||||
source: e,
|
||||
path: path.to_string_lossy().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Recursively creates a directory and all of its parent components if they are missing.
|
||||
pub async fn create_dir_all(
|
||||
path: impl AsRef<std::path::Path>,
|
||||
) -> Result<(), IOError> {
|
||||
let path = path.as_ref();
|
||||
tokio::fs::create_dir_all(path)
|
||||
.await
|
||||
.map_err(|e| IOError::IOErrorWrapper { source: e, path: path.to_string_lossy().to_string() })
|
||||
}
|
||||
|
||||
/// Removes a directory at this path, after removing all its contents. Use carefully!
|
||||
pub async fn remove_dir_all(
|
||||
path: impl AsRef<std::path::Path>,
|
||||
) -> Result<(), IOError> {
|
||||
let path = path.as_ref();
|
||||
tokio::fs::remove_dir_all(path)
|
||||
.await
|
||||
.map_err(|e| IOError::IOErrorWrapper { source: e, path: path.to_string_lossy().to_string() })
|
||||
}
|
||||
|
||||
/// Creates a future which will open a file for reading and read the entire contents into a string and return said string.
|
||||
pub async fn read_to_string(
|
||||
path: impl AsRef<std::path::Path>,
|
||||
) -> Result<String, IOError> {
|
||||
let path = path.as_ref();
|
||||
tokio::fs::read_to_string(path)
|
||||
.await
|
||||
.map_err(|e| IOError::IOErrorWrapper { source: e, path: path.to_string_lossy().to_string() })
|
||||
}
|
||||
|
||||
/// Reads the entire contents of a file into a bytes vector.
|
||||
pub async fn read(
|
||||
path: impl AsRef<std::path::Path>,
|
||||
) -> Result<Vec<u8>, IOError> {
|
||||
let path = path.as_ref();
|
||||
tokio::fs::read(path)
|
||||
.await
|
||||
.map_err(|e| IOError::IOErrorWrapper { source: e, path: path.to_string_lossy().to_string() })
|
||||
}
|
||||
|
||||
/// Asynchrously write to a tempfile that is then transferred to an official [`AsRef<Path>`].
|
||||
pub async fn write(
|
||||
path: impl AsRef<std::path::Path>,
|
||||
data: impl AsRef<[u8]>
|
||||
) -> Result<(), IOError> {
|
||||
let path = path.as_ref().to_owned();
|
||||
let data = data.as_ref().to_owned();
|
||||
spawn_blocking(move || {
|
||||
let cloned_path = path.clone();
|
||||
sync_write(data, path).map_err(|e| IOError::IOErrorWrapper { source: e, path: cloned_path.to_string_lossy().to_string() })
|
||||
}).await.map_err(|_| {std::io::Error::new(std::io::ErrorKind::Other, "tokio task failed")})??;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write to a tempfile that is then transferred to an official [`AsRef<Path>`].
|
||||
fn sync_write(
|
||||
data: impl AsRef<[u8]>,
|
||||
path: impl AsRef<std::path::Path>,
|
||||
) -> Result<(), std::io::Error> {
|
||||
let mut tempfile = NamedTempFile::new_in(path.as_ref().parent().ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
"failed to get parent directory of a tempfile",
|
||||
)
|
||||
})?)?;
|
||||
tempfile.write_all(data.as_ref())?;
|
||||
let tmp_path = tempfile.into_temp_path();
|
||||
let path = path.as_ref();
|
||||
// this is a sorta dangerous call but shouldnt matter because of async
|
||||
tmp_path.persist(path);
|
||||
std::io::Result::Ok(())
|
||||
}
|
||||
|
||||
/// Renames a file or directory to a new name, replacing the original file if `to` already exists.
|
||||
pub async fn rename(
|
||||
from: impl AsRef<std::path::Path>,
|
||||
to: impl AsRef<std::path::Path>,
|
||||
) -> Result<(), IOError> {
|
||||
let from = from.as_ref();
|
||||
let to = to.as_ref();
|
||||
tokio::fs::rename(from, to)
|
||||
.await
|
||||
.map_err(|e| IOError::IOErrorWrapper { source: e, path: from.to_string_lossy().to_string() })
|
||||
}
|
||||
|
||||
/// Copies the contents of one file to another. This function will also copy the permission bits of the original file to the destination file. This function will overwrite the contents of to.
|
||||
pub async fn copy(
|
||||
from: impl AsRef<std::path::Path>,
|
||||
to: impl AsRef<std::path::Path>,
|
||||
) -> Result<u64, IOError> {
|
||||
let from = from.as_ref();
|
||||
let to = to.as_ref();
|
||||
tokio::fs::copy(from, to)
|
||||
.await
|
||||
.map_err(|e| IOError::IOErrorWrapper { source: e, path: from.to_string_lossy().to_string() })
|
||||
}
|
||||
|
||||
/// Removes a file from the filesystem.
|
||||
pub async fn remove_file(
|
||||
path: impl AsRef<std::path::Path>,
|
||||
) -> Result<(), IOError> {
|
||||
let path = path.as_ref();
|
||||
tokio::fs::remove_file(path)
|
||||
.await
|
||||
.map_err(|e| IOError::IOErrorWrapper { source: e, path: path.to_string_lossy().to_string() })
|
||||
}
|
||||
|
||||
/// Extract an archive based on its file extension, supporting ZIP files and GZ files.
|
||||
pub fn extract_archive(archive: &PathBuf, dest: &PathBuf) -> crate::Result<()> {
|
||||
let ext = match archive.extension() {
|
||||
Some(ext) => ext.to_str().unwrap(),
|
||||
None => return Err(anyhow!("unsupported operating system").into()),
|
||||
};
|
||||
|
||||
match ext {
|
||||
"zip" => extract_zip(archive, dest).map_err(|err| crate::ErrorKind::IOError(err).into()),
|
||||
"gz" => extract_tar_gz(archive, dest).map_err(|err| crate::ErrorKind::IOError(err).into()),
|
||||
_ => Err(anyhow!("unsupported file extension {:?}", ext).into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extract_zip(archive: &PathBuf, dest: &PathBuf) -> Result<(), IOError> {
|
||||
let file = File::open(archive).map_err(|err| IOError::with_path(err, archive.as_path()))?;
|
||||
let archive = zip::ZipArchive::new(file).map_err(|err| IOError::from_zip(err));
|
||||
archive?
|
||||
.extract(dest)
|
||||
.map_err(|err| IOError::from_zip(err))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn extract_tar_gz(archive: &PathBuf, dest: &PathBuf) -> Result<(), IOError> {
|
||||
let file = File::open(archive).map_err(|err| IOError::from(err))?;
|
||||
let tar_gz = flate2::read::GzDecoder::new(file);
|
||||
let mut archive = tar::Archive::new(tar_gz);
|
||||
archive
|
||||
.unpack(dest)
|
||||
.map_err(|err| IOError::from(err))?;
|
||||
Ok(())
|
||||
}
|
||||
332
core/src/utils/java.rs
Normal file
|
|
@ -0,0 +1,332 @@
|
|||
//! **Java Utilities**
|
||||
//!
|
||||
//! Async utilities for managing and downloading Java versions.
|
||||
|
||||
use std::{collections::HashSet, env, path::{Path, PathBuf}, process::Command};
|
||||
use futures::prelude::*;
|
||||
use serde::{Serialize, Deserialize};
|
||||
use tokio::task::JoinError;
|
||||
use crate::State;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
use winreg::{
|
||||
enums::{HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY, KEY_WOW64_64KEY},
|
||||
RegKey
|
||||
};
|
||||
|
||||
use super::io;
|
||||
|
||||
/// A struct representing a single version of the Java Runtime Environment
|
||||
/// Use [`locate_java`] to get an array of all located java instances on the machine
|
||||
/// paths from https://github.com/PrismLauncher/PrismLauncher/blob/develop/launcher/java/JavaUtils.cpp under GPL 3.0
|
||||
/// paths and java_check from https://github.com/modrinth/theseus/blob/master/theseus/src/util/jre.rs under MIT
|
||||
#[derive(Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Clone)]
|
||||
pub struct JavaVersion {
|
||||
pub version: String,
|
||||
pub arch: String,
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// JVM Entrypoint (WINDOWS ONLY)
|
||||
#[cfg(target_os = "windows")]
|
||||
#[tracing::instrument]
|
||||
pub async fn locate_java() -> Result<Vec<JavaVersion>, JavaError> {
|
||||
let mut paths = HashSet::new();
|
||||
paths.extend(locate_java_path().await);
|
||||
paths.extend(locate_installed_java().await?);
|
||||
if let Ok(java_home) = env::var("JAVA_HOME") {
|
||||
paths.insert(PathBuf::from(java_home));
|
||||
}
|
||||
|
||||
// i hate windows.com
|
||||
let common_java_paths = [
|
||||
r"C:/Program Files/Java",
|
||||
r"C:\Program Files\Eclipse Adoptium",
|
||||
r"C:/Program Files (x86)/Java",
|
||||
r"C:\Program Files (x86)/Eclipse Adoptium",
|
||||
];
|
||||
|
||||
for path in common_java_paths {
|
||||
let Ok(java_subs) = std::fs::read_dir(path) else { continue; };
|
||||
for java_sub in java_subs.flatten() {
|
||||
let full_path = java_sub.path();
|
||||
paths.insert(full_path.join("bin"));
|
||||
}
|
||||
}
|
||||
|
||||
let common_key_paths = [
|
||||
r"SOFTWARE\\JavaSoft\\Java Runtime Environment",
|
||||
r"SOFTWARE\\JavaSoft\\Java Development Kit",
|
||||
r"SOFTWARE\\JavaSoft\\JRE",
|
||||
r"SOFTWARE\\JavaSoft\\JDK",
|
||||
r"SOFTWARE\\AdoptOpenJDK\\JRE",
|
||||
r"SOFTWARE\\AdoptOpenJDK\\JDK",
|
||||
r"SOFTWARE\\Eclipse Foundation\\JDK",
|
||||
r"SOFTWARE\\Eclipse Foundation\\JRE",
|
||||
r"SOFTWARE\\Eclipse Adoptium\\JRE",
|
||||
r"SOFTWARE\\Eclipse Adoptium\\JDK",
|
||||
r"SOFTWARE\\Microsoft\\JDK",
|
||||
r"SOFTWARE\\Azul Systems\\Zulu",
|
||||
r"SOFTWARE\\BellSoft\\Liberica",
|
||||
];
|
||||
|
||||
for key in key_paths {
|
||||
if let Ok(java_key) = RegKey::predef(HKEY_LOCAL_MACHINE)
|
||||
.open_subkey_with_flags(key, KEY_READ | KEY_WOW64_32KEY)
|
||||
{
|
||||
paths.extend(get_java_paths_from_windows(java_key));
|
||||
}
|
||||
if let Ok(java_key) = RegKey::predef(HKEY_LOCAL_MACHINE)
|
||||
.open_subkey_with_flags(key, KEY_READ | KEY_WOW64_64KEY)
|
||||
{
|
||||
paths.extend(get_java_paths_from_windows(java_key));
|
||||
}
|
||||
}
|
||||
|
||||
let java = check_java(paths).await.into_iter().collect();
|
||||
|
||||
Ok(java);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[tracing::instrument]
|
||||
pub fn get_java_paths_from_windows(java_key: RegKey) -> HashSet<PathBuf> {
|
||||
let mut paths = HashSet::new();
|
||||
|
||||
for subkey in java_key.enum_keys().flatten() {
|
||||
if let Ok(subkey) = java_key.open_subkey(subkey) {
|
||||
let common_subkey_value_names = [r"JavaHome", r"InstallationPath", r"\\hotspot\\MSI"];
|
||||
for subkey_value in common_subkey_value_names {
|
||||
let path: Result<String, std::io::Error> = subkey.get_value(subkey_value);
|
||||
let Ok(path) = path else { continue };
|
||||
paths.insert(PathBuf::from(path).join("bin"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
paths
|
||||
}
|
||||
|
||||
/// JVM Entrypoint (MacOS ONLY)
|
||||
#[cfg(target_os = "macos")]
|
||||
#[tracing::instrument]
|
||||
pub async fn locate_java() -> Result<Vec<JavaVersion>, JavaError> {
|
||||
let mut paths = HashSet::new();
|
||||
paths.extend(locate_java_path().await);
|
||||
paths.extend(locate_installed_java().await?);
|
||||
|
||||
let jvm_base = PathBuf::from("/Library/Java/JavaVirtualMachines/");
|
||||
if let Ok(dir) = std::fs::read_dir(jvm_base) {
|
||||
for entry in dir.flatten() {
|
||||
let entry = entry.path().join("Contents/Home/bin");
|
||||
paths.insert(entry);
|
||||
}
|
||||
}
|
||||
|
||||
let common_java_paths = [
|
||||
r"/System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands",
|
||||
r"/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/MacOS/itms/java",
|
||||
r"/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home",
|
||||
];
|
||||
|
||||
for path in common_java_paths {
|
||||
paths.insert(PathBuf::from(path));
|
||||
}
|
||||
|
||||
let java = check_java(paths).await.into_iter().collect();
|
||||
|
||||
Ok(java)
|
||||
}
|
||||
|
||||
/// JVM Entrypoint (LINUX ONLY)
|
||||
#[cfg(target_os = "linux")]
|
||||
#[tracing::instrument]
|
||||
pub async fn locate_java() -> Result<Vec<JavaVersion>, JavaError> {
|
||||
let mut paths = HashSet::new();
|
||||
paths.extend(locate_java_path().await);
|
||||
paths.extend(locate_installed_java().await?);
|
||||
|
||||
let common_java_paths = [
|
||||
r"/usr",
|
||||
r"/usr/java",
|
||||
r"/usr/lib/jvm",
|
||||
r"/usr/lib64/jvm",
|
||||
r"/usr/lib32/jvm",
|
||||
r"/opt/jdk",
|
||||
r"/opt/jdks",
|
||||
r"/app/jdk",
|
||||
];
|
||||
|
||||
for path in common_java_paths {
|
||||
let path = PathBuf::from(path);
|
||||
paths.insert(PathBuf::from(&path).join("jre").join("bin"));
|
||||
paths.insert(PathBuf::from(&path).join("bin"));
|
||||
if let Ok(dir) = std::fs::read_dir(path) {
|
||||
for entry in dir.flatten() {
|
||||
let entry_path = entry.path();
|
||||
paths.insert(entry_path.join("jre").join("bin"));
|
||||
paths.insert(entry_path.join("bin"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let java = check_java(paths).await.into_iter().collect();
|
||||
|
||||
Ok(java)
|
||||
}
|
||||
|
||||
/// Locate JRE's auto-installed by the launcher instance.
|
||||
#[tracing::instrument]
|
||||
#[onelauncher_debug::debugger]
|
||||
async fn locate_installed_java() -> Result<HashSet<PathBuf>, JavaError> {
|
||||
Box::pin(async move {
|
||||
let state = State::get().await.map_err(|_| JavaError::MutexError)?;
|
||||
let mut paths = HashSet::new();
|
||||
let java_base_path = state.directories.java_dir().await;
|
||||
|
||||
if java_base_path.is_dir() {
|
||||
if let Ok(dir) = std::fs::read_dir(java_base_path) {
|
||||
for entry in dir.flatten() {
|
||||
let path = entry.path().join("bin");
|
||||
if let Ok(contents) = io::read_to_string(path.clone()).await {
|
||||
let entry = entry.path().join(contents);
|
||||
paths.insert(entry);
|
||||
} else {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
let path = path.join(JAVA_BIN);
|
||||
paths.insert(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(paths)
|
||||
}).await
|
||||
}
|
||||
|
||||
/// Locate all installed Java instances from the PATH env variable cross-device.
|
||||
#[tracing::instrument]
|
||||
async fn locate_java_path() -> HashSet<PathBuf> {
|
||||
let paths = env::var("PATH").map(|p| env::split_paths(&p).collect::<HashSet<_>>());
|
||||
paths.unwrap_or_else(|_| HashSet::new())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub const JAVA_BIN: &str = "javaw.exe";
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
pub const JAVA_BIN: &str = "java";
|
||||
|
||||
/// Verifies that each Java instance is valid from a HashSet of PathBufs
|
||||
#[tracing::instrument]
|
||||
pub async fn check_java(paths: HashSet<PathBuf>) -> HashSet<JavaVersion> {
|
||||
let java_instances = stream::iter(paths.into_iter())
|
||||
.map(|p: PathBuf| {
|
||||
tokio::task::spawn(async move { check_java_instance(&p).await })
|
||||
})
|
||||
.buffer_unordered(64)
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
|
||||
java_instances
|
||||
.into_iter()
|
||||
.flat_map(|p| p.ok())
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Verifies that a java instance [`Path`] is valid.
|
||||
/// java_check from https://github.com/modrinth/theseus/blob/master/theseus/library/JavaInfo.class under MIT
|
||||
#[tracing::instrument]
|
||||
#[onelauncher_debug::debugger]
|
||||
pub async fn check_java_instance(path: &Path) -> Option<JavaVersion> {
|
||||
let Ok(path) = io::canonicalize(path) else { return None; };
|
||||
let java = if path.file_name()?.to_str()? != JAVA_BIN { path.join(JAVA_BIN) } else { path };
|
||||
if !java.exists() { return None; }
|
||||
|
||||
let bytes = include_bytes!("../../wrapper/java/JavaInfo.class");
|
||||
let tempdir: PathBuf = tempfile::tempdir().ok()?.into_path();
|
||||
if !tempdir.exists() { return None; }
|
||||
|
||||
let file_path = tempdir.join("JavaInfo.class");
|
||||
io::write(&file_path, bytes).await.ok()?;
|
||||
|
||||
let output = Command::new(&java)
|
||||
.arg("-cp")
|
||||
.arg(file_path.parent().unwrap())
|
||||
.arg("JavaInfo").output().ok()?;
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
|
||||
let mut java_version = None;
|
||||
let mut java_arch = None;
|
||||
|
||||
for line in stdout.lines() {
|
||||
let mut parts = line.split('=');
|
||||
let key = parts.next().unwrap_or_default();
|
||||
let value = parts.next().unwrap_or_default();
|
||||
|
||||
if key == "os.arch" {
|
||||
java_arch = Some(value);
|
||||
} else if key == "java.version" {
|
||||
java_version = Some(value);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(arch) = java_arch {
|
||||
if let Some(version) = java_version {
|
||||
let path = java.to_string_lossy().to_string();
|
||||
return Some(JavaVersion {
|
||||
path,
|
||||
version: version.to_string(),
|
||||
arch: arch.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Get a formatted java version.
|
||||
pub fn get_java_version(version: &str) -> Result<(u32, u32), JavaError> {
|
||||
let mut split = version.split('.');
|
||||
let major_opt = split.next();
|
||||
let mut major;
|
||||
let mut minor = if let Some(minor) = split.next() {
|
||||
major = major_opt.unwrap_or("1").parse::<u32>()?;
|
||||
minor.parse::<u32>()?
|
||||
} else {
|
||||
major = 1;
|
||||
major_opt.ok_or_else(|| JavaError::InvalidVersion(version.to_string()))?.parse::<u32>()?
|
||||
};
|
||||
|
||||
if major > 1 {
|
||||
minor = major;
|
||||
major = 1;
|
||||
}
|
||||
|
||||
Ok((major, minor))
|
||||
}
|
||||
|
||||
/// An error wrapper for everything that can go wrong while managing Java installations.
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum JavaError {
|
||||
#[error("failed to fetch environment variable: {0}")]
|
||||
EnvError(#[from] env::VarError),
|
||||
|
||||
#[error("error running java command: {0}")]
|
||||
IOError(#[from] std::io::Error),
|
||||
|
||||
#[error("failed to parse integer: {0}")]
|
||||
ParseError(#[from] std::num::ParseIntError),
|
||||
|
||||
#[error("tokio error: {0}")]
|
||||
JoinError(#[from] JoinError),
|
||||
|
||||
#[error("couldn't get a valid java version from {0}")]
|
||||
InvalidVersion(String),
|
||||
|
||||
#[error("failed to get launcher state mutex!")]
|
||||
MutexError,
|
||||
}
|
||||
20
core/src/utils/mod.rs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
//! OneLauncher utility functions
|
||||
pub mod io;
|
||||
pub mod http;
|
||||
pub mod platform;
|
||||
pub mod java;
|
||||
pub mod watcher;
|
||||
pub mod pkg;
|
||||
|
||||
/// mutable reference gets epically owned by free thinking macro!!!! (not clickbait)
|
||||
/// im going insane insane insane insane insane insane
|
||||
macro_rules! ref_owned {
|
||||
($id:ident = $init:expr => $transform:block) => {{
|
||||
let mut it = $init;
|
||||
{
|
||||
let $id = &mut it;
|
||||
$transform;
|
||||
}
|
||||
it
|
||||
}};
|
||||
}
|
||||
0
core/src/utils/pkg.rs
Normal file
94
core/src/utils/platform.rs
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
//! **Platform Utilities**
|
||||
//!
|
||||
//! Async utilities for managing OS-specific [`interpulse`] operations and rules.
|
||||
|
||||
use interpulse::api::minecraft::{Os, OsRule};
|
||||
use regex::Regex;
|
||||
|
||||
pub trait OsExt {
|
||||
/// Get the OS of the current system
|
||||
fn native() -> Self;
|
||||
|
||||
/// Gets the OS + Arch of the current system
|
||||
fn native_arch(java_arch: &str) -> Self;
|
||||
}
|
||||
|
||||
impl OsExt for Os {
|
||||
fn native_arch(java_arch: &str) -> Self {
|
||||
if std::env::consts::OS == "windows" {
|
||||
if java_arch == "aarch64" {
|
||||
Os::WindowsArm64
|
||||
} else {
|
||||
Os::Windows
|
||||
}
|
||||
} else if std::env::consts::OS == "linux" {
|
||||
if java_arch == "aarch64" {
|
||||
Os::LinuxArm64
|
||||
} else if java_arch == "arm" {
|
||||
Os::LinuxArm32
|
||||
} else {
|
||||
Os::Linux
|
||||
}
|
||||
} else if std::env::consts::OS == "macos" {
|
||||
if java_arch == "aarch64" {
|
||||
Os::OsxArm64
|
||||
} else {
|
||||
Os::Osx
|
||||
}
|
||||
} else {
|
||||
Os::Unknown
|
||||
}
|
||||
}
|
||||
|
||||
fn native() -> Self {
|
||||
match std::env::consts::OS {
|
||||
"windows" => Self::Windows,
|
||||
"macos" => Self::Osx,
|
||||
"linux" => Self::Linux,
|
||||
_ => Self::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Bit width
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
pub const ARCH_WIDTH: &str = "64";
|
||||
|
||||
#[cfg(target_pointer_width = "32")]
|
||||
pub const ARCH_WIDTH: &str = "32";
|
||||
|
||||
// Platform rule handling
|
||||
pub fn os_rule(
|
||||
rule: &OsRule,
|
||||
java_arch: &str,
|
||||
updated: bool,
|
||||
) -> bool {
|
||||
let mut rule_match = true;
|
||||
|
||||
if let Some(ref arch) = rule.arch {
|
||||
rule_match &= !matches!(arch.as_str(), "x86" | "arm");
|
||||
}
|
||||
|
||||
if let Some(name) = &rule.name {
|
||||
if updated && (name != &Os::LinuxArm64 || name != &Os::LinuxArm32) {
|
||||
rule_match &= &Os::native() == name || &Os::native_arch(java_arch) == name;
|
||||
} else {
|
||||
rule_match &= &Os::native_arch(java_arch) == name;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(version) = &rule.version {
|
||||
if let Ok(regex) = Regex::new(version.as_str()) {
|
||||
rule_match &= regex.is_match(&sys_info::os_release().unwrap_or_default());
|
||||
}
|
||||
}
|
||||
|
||||
rule_match
|
||||
}
|
||||
|
||||
pub fn classpath_separator(java_arch: &str) -> &'static str {
|
||||
match Os::native_arch(java_arch) {
|
||||
Os::Osx | Os::OsxArm64 | Os::Linux | Os::LinuxArm32 | Os::LinuxArm64 | Os::Unknown => ":",
|
||||
Os::Windows | Os::WindowsArm64 => ";",
|
||||
}
|
||||
}
|
||||
74
core/src/utils/watcher.rs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
//! **Watcher Utilities*
|
||||
//!
|
||||
//! Async utilities for watching files with [`notify`].
|
||||
|
||||
use std::{path::PathBuf, time::Duration};
|
||||
|
||||
use notify::RecommendedWatcher;
|
||||
use notify_debouncer_mini::{new_debouncer, DebounceEventResult, Debouncer};
|
||||
use futures::{channel::mpsc::channel, SinkExt, StreamExt};
|
||||
use crate::store::{Cluster, ClusterPath, Clusters};
|
||||
|
||||
pub const CLUSTERS_PATH: &str = "clusters";
|
||||
pub const CRASH_PATH: &str = "crash-reports";
|
||||
|
||||
pub async fn initialize_watcher() -> crate::Result<Debouncer<RecommendedWatcher>> {
|
||||
let (mut sender, mut rscv) = channel(1);
|
||||
let watcher = new_debouncer(
|
||||
Duration::from_secs_f32(2.0),
|
||||
move |result: DebounceEventResult| {
|
||||
futures::executor::block_on(async {
|
||||
sender.send(result).await.unwrap();
|
||||
})
|
||||
})?;
|
||||
|
||||
tokio::task::spawn(async move {
|
||||
let span = tracing::span!(tracing::Level::INFO, "initialize_watcher");
|
||||
tracing::info!(parent: &span, "initializing fs watcher...");
|
||||
while let Some(result) = rscv.next().await {
|
||||
let _span = span.enter();
|
||||
|
||||
match result {
|
||||
Ok(mut events) => {
|
||||
let mut paths = Vec::new();
|
||||
events.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
events.iter().for_each(|a| {
|
||||
let mut formatted = PathBuf::new();
|
||||
let mut components = a.path.components();
|
||||
let mut matched = false;
|
||||
|
||||
for cmp in components.by_ref() {
|
||||
formatted.push(cmp);
|
||||
if matched { break; }
|
||||
// really simple fs watcher to check in any cluster files have been modified by outside forces
|
||||
if cmp.as_os_str() == "clusters" { matched = true; }
|
||||
}
|
||||
|
||||
let sub = components.next().is_none();
|
||||
let cluster_path = ClusterPath::new(PathBuf::from(
|
||||
formatted.file_name().unwrap_or_default(),
|
||||
));
|
||||
|
||||
if a.path
|
||||
.components()
|
||||
.any(|c| c.as_os_str() == CRASH_PATH)
|
||||
&& a.path.extension().map(|e| e == "txt").unwrap_or(false)
|
||||
{
|
||||
Cluster::handle_crash(cluster_path);
|
||||
} else if !paths.contains(&formatted) {
|
||||
if sub {
|
||||
Cluster::sync_packages(cluster_path, false);
|
||||
paths.push(formatted);
|
||||
} else {
|
||||
Clusters::sync_clusters(cluster_path);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(err) => tracing::warn!("fs watching error: {err}")
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(watcher)
|
||||
}
|
||||
11
core/wrapper/README.md
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
# Library Wrappers
|
||||
|
||||
TODO: Don't pre-build binaries. That is a huge security issue.
|
||||
|
||||
## JavaCheck
|
||||
|
||||
Yoinked from <https://github.com/PrismLauncher/PrismLauncher/tree/develop/libraries/javacheck>.
|
||||
|
||||
(Relicensed to the Unlicense from ["Do what you want with it. It is so trivial that noone cares."](https://github.com/PrismLauncher/PrismLauncher/blob/develop/libraries/README.md#javacheck))
|
||||
|
||||
## Gamemmode
|
||||
BIN
core/wrapper/java/JavaInfo.class
Normal file
19
core/wrapper/java/JavaInfo.java
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
public final class JavaInfo {
|
||||
private static final String[] CHECKED_PROPERTIES = new String[] {"os.arch", "java.version", "java.vendor"};
|
||||
|
||||
public static void main(String[] args) {
|
||||
int returnCode = 0;
|
||||
|
||||
for (String key : CHECKED_PROPERTIES) {
|
||||
String property = System.getProperty(key);
|
||||
|
||||
if (property != null) {
|
||||
System.out.println(key + "=" + property);
|
||||
} else {
|
||||
returnCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
System.exit(returnCode);
|
||||
}
|
||||
}
|
||||
24
core/wrapper/java/LICENSE
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
This is free and unencumbered software released into the public domain.
|
||||
|
||||
Anyone is free to copy, modify, publish, use, compile, sell, or
|
||||
distribute this software, either in source code form or as a compiled
|
||||
binary, for any purpose, commercial or non-commercial, and by any
|
||||
means.
|
||||
|
||||
In jurisdictions that recognize copyright laws, the author or authors
|
||||
of this software dedicate any and all copyright interest in the
|
||||
software to the public domain. We make this dedication for the benefit
|
||||
of the public at large and to the detriment of our heirs and
|
||||
successors. We intend this dedication to be an overt act of
|
||||
relinquishment in perpetuity of all present and future rights to this
|
||||
software under copyright law.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
For more information, please refer to <https://unlicense.org>
|
||||
1
core/wrapper/main/LICENSE
Symbolic link
|
|
@ -0,0 +1 @@
|
|||
./LICENSE
|
||||
18
debugger/Cargo.toml
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
[package]
|
||||
name = "onelauncher_debug"
|
||||
version = "0.0.0"
|
||||
description = "Debugger macros for OneLauncher"
|
||||
license = { workspace = true }
|
||||
edition = { workspace = true }
|
||||
repository = { workspace = true }
|
||||
documentation = { workspace = true }
|
||||
readme = { workspace = true }
|
||||
homepage = { workspace = true }
|
||||
authors = { workspace = true }
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
syn = { workspace = true }
|
||||
quote = { workspace = true }
|
||||
36
debugger/src/lib.rs
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
extern crate proc_macro;
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{parse_macro_input, ItemFn};
|
||||
|
||||
/// Macro that isolates <Box>s that automatically are isolated in Tauri Debug environments
|
||||
/// This is useful for debugging functions that manage memory.
|
||||
#[proc_macro_attribute]
|
||||
pub fn debugger(_attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(item as ItemFn);
|
||||
|
||||
let attrs = &input.attrs;
|
||||
let vis = &input.vis;
|
||||
let sig = &input.sig;
|
||||
let body = &input.block;
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
let result = quote! {
|
||||
#(#attrs)*
|
||||
#vis #sig {
|
||||
Box::pin(async move {
|
||||
#body
|
||||
}).await
|
||||
}
|
||||
};
|
||||
#[cfg(not(debug_assertions))]
|
||||
let result = quote! {
|
||||
#(#attrs)*
|
||||
#vis #sig {
|
||||
#body
|
||||
}
|
||||
};
|
||||
|
||||
TokenStream::from(result)
|
||||
}
|
||||
3
desktop/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
/dist
|
||||
/dist-isolation
|
||||
/coverage
|
||||
|
Before Width: | Height: | Size: 3.4 KiB After Width: | Height: | Size: 3.4 KiB |
|
Before Width: | Height: | Size: 6.8 KiB After Width: | Height: | Size: 6.8 KiB |
|
Before Width: | Height: | Size: 974 B After Width: | Height: | Size: 974 B |
|
Before Width: | Height: | Size: 2.8 KiB After Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 3.8 KiB After Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 3.9 KiB After Width: | Height: | Size: 3.9 KiB |
|
Before Width: | Height: | Size: 7.6 KiB After Width: | Height: | Size: 7.6 KiB |
|
Before Width: | Height: | Size: 903 B After Width: | Height: | Size: 903 B |
|
Before Width: | Height: | Size: 8.4 KiB After Width: | Height: | Size: 8.4 KiB |
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 2 KiB After Width: | Height: | Size: 2 KiB |
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 85 KiB After Width: | Height: | Size: 85 KiB |
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 14 KiB |
6
desktop/.setup-cross.sh
Executable file
|
|
@ -0,0 +1,6 @@
|
|||
#!/usr/bin/env bash
|
||||
|
||||
export ICONS_VOLUME="$(realpath ./.icons)"
|
||||
export DIST_VOLUME="$(realpath dist)"
|
||||
export ISOLATION_VOLUME="$(realpath isolation-dist)"
|
||||
export WORKSPACE_VOLUME="$(realpath ../..)"
|
||||
2
desktop/.taurignore
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
src-tauri/Cross.toml
|
||||
src-tauri/.gitignore
|
||||