Compare commits
43 Commits
main
...
30c25452dc
Author | SHA1 | Date | |
---|---|---|---|
30c25452dc | |||
aae4261b53 | |||
3b13d78cdc | |||
d38faccf6f | |||
07caa7c53c | |||
a2f42346ae | |||
932d867505 | |||
212b58c072 | |||
3d78d3e279 | |||
e018aec8db | |||
fa115e0a6c | |||
51b155e70a | |||
6ee1b67315 | |||
c39a8bc43c | |||
56da7c7543 | |||
26f601635b | |||
ec54219192 | |||
f3aa32a60a | |||
7938555c91 | |||
591e354dcb | |||
ce141a014c | |||
3d4c9c89ef | |||
90d4bb80e6 | |||
fdf5c7a90d | |||
387d1548ba | |||
942066ea76 | |||
815ce286f7 | |||
31a26dc1ce | |||
5cd483209f | |||
1b50a7d4e4 | |||
b14de1d15a | |||
7eaf7a7610 | |||
76917e3f90 | |||
261b9ac253 | |||
2eda1d7806 | |||
1b496288de | |||
ff91303b18 | |||
8fa6956095 | |||
6f92b2acad | |||
b65b9538bb | |||
4717132b05 | |||
12f7ea8d1c | |||
e21a51482a |
1
.cursorignore
Normal file
1
.cursorignore
Normal file
@ -0,0 +1 @@
|
||||
# Add directories or file patterns to ignore during indexing (e.g. foo/ or *.csv)
|
@ -1,7 +1,3 @@
|
||||
/**
|
||||
* Base webpack config used across other specific configs
|
||||
*/
|
||||
|
||||
import webpack from 'webpack';
|
||||
import TsconfigPathsPlugins from 'tsconfig-paths-webpack-plugin';
|
||||
import webpackPaths from './webpack.paths';
|
||||
@ -20,7 +16,6 @@ const configuration: webpack.Configuration = {
|
||||
use: {
|
||||
loader: 'ts-loader',
|
||||
options: {
|
||||
// Remove this line to enable type checking in webpack builds
|
||||
transpileOnly: true,
|
||||
compilerOptions: {
|
||||
module: 'nodenext',
|
||||
@ -34,18 +29,22 @@ const configuration: webpack.Configuration = {
|
||||
|
||||
output: {
|
||||
path: webpackPaths.srcPath,
|
||||
// https://github.com/webpack/webpack/issues/1114
|
||||
library: { type: 'commonjs2' },
|
||||
},
|
||||
|
||||
/**
|
||||
* Determine the array of extensions that should be used to resolve modules.
|
||||
*/
|
||||
resolve: {
|
||||
extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'],
|
||||
modules: [webpackPaths.srcPath, 'node_modules'],
|
||||
// There is no need to add aliases here, the paths in tsconfig get mirrored
|
||||
plugins: [new TsconfigPathsPlugins()],
|
||||
|
||||
// Новые настройки
|
||||
extensionAlias: {
|
||||
'.js': ['.js', '.mjs'],
|
||||
},
|
||||
fullySpecified: false,
|
||||
alias: {
|
||||
'undici/lib/core/util': 'undici/lib/core/util.js',
|
||||
},
|
||||
},
|
||||
|
||||
plugins: [new webpack.EnvironmentPlugin({ NODE_ENV: 'production' })],
|
||||
|
@ -36,9 +36,15 @@ const configuration: webpack.Configuration = {
|
||||
},
|
||||
|
||||
optimization: {
|
||||
minimize: false,
|
||||
minimizer: [
|
||||
new TerserPlugin({
|
||||
parallel: true,
|
||||
terserOptions: {
|
||||
ecma: 2020,
|
||||
keep_classnames: true,
|
||||
keep_fnames: true,
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -1,3 +1,5 @@
|
||||
public/
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
@ -27,3 +29,4 @@ npm-debug.log.*
|
||||
*.css.d.ts
|
||||
*.sass.d.ts
|
||||
*.scss.d.ts
|
||||
.env
|
||||
|
0
assets/fonts/benzin-bold.eot
Normal file
0
assets/fonts/benzin-bold.eot
Normal file
1745
assets/fonts/benzin-bold.svg
Normal file
1745
assets/fonts/benzin-bold.svg
Normal file
File diff suppressed because it is too large
Load Diff
After Width: | Height: | Size: 221 KiB |
BIN
assets/fonts/benzin-bold.ttf
Normal file
BIN
assets/fonts/benzin-bold.ttf
Normal file
Binary file not shown.
0
assets/fonts/benzin-bold.woff
Normal file
0
assets/fonts/benzin-bold.woff
Normal file
BIN
assets/fonts/benzin-bold.woff2
Normal file
BIN
assets/fonts/benzin-bold.woff2
Normal file
Binary file not shown.
BIN
assets/icons/popa-popa.png
Normal file
BIN
assets/icons/popa-popa.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 6.7 KiB |
18
assets/icons/popa-popa.svg
Normal file
18
assets/icons/popa-popa.svg
Normal file
File diff suppressed because one or more lines are too long
After Width: | Height: | Size: 80 KiB |
30
assets/images/heart.svg
Normal file
30
assets/images/heart.svg
Normal file
@ -0,0 +1,30 @@
|
||||
<svg width="28" height="28" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect x="0" y="12" width="28" height="4" fill="#BD2211"/>
|
||||
<rect x="4" y="16" width="20" height="4" fill="#BD2211"/>
|
||||
<rect x="8" y="20" width="12" height="4" fill="#BD2211"/>
|
||||
<rect x="12" y="24" width="4" height="4" fill="#BD2211"/>
|
||||
<rect x="4" width="8" height="4.5" fill="#FF2D0F"/>
|
||||
<rect x="16" width="8" height="4.5" fill="#FF2D0F"/>
|
||||
<rect x="0" y="4" width="28" height="8" fill="#FF2D0F"/>
|
||||
<rect x="4" y="8" width="20" height="8" fill="#FF2D0F"/>
|
||||
<rect x="8" y="12" width="12" height="8" fill="#FF2D0F"/>
|
||||
<rect x="12" y="16" width="4" height="8" fill="#FF2D0F"/>
|
||||
<rect x="4" y="4" width="4" height="4" fill="#FFCAC8"/>
|
||||
<!-- <rect x="7" y="4" width="6" height="16" fill="#FF2D0F"/>
|
||||
<rect x="6" y="3" width="6" height="16" fill="#FF2D0F"/>
|
||||
<rect x="3" y="8" width="4" height="8" fill="#FF2D0F"/>
|
||||
<rect y="4" width="4" height="8" fill="#FF2D0F"/>
|
||||
<rect x="24" y="4" width="4" height="8" fill="#FF2D0F"/>
|
||||
<rect x="16" width="8" height="16" fill="#FF2D0F"/>
|
||||
<rect x="20" y="4" width="8" height="12" fill="#FF2D0F"/>
|
||||
<rect x="15" y="4" width="5" height="16" fill="#FF2D0F"/>
|
||||
<rect x="24" y="12" width="4" height="4" fill="#BD2211"/>
|
||||
<rect x="20" y="16" width="4" height="4" fill="#BD2211"/>
|
||||
<rect x="16" y="20" width="4" height="4" fill="#BD2211"/>
|
||||
<rect x="12" y="24" width="4" height="4" fill="#BD2211"/>
|
||||
<rect x="8" y="20" width="4" height="4" fill="#BD2211"/>
|
||||
<rect x="4" y="16" width="4" height="4" fill="#BD2211"/>
|
||||
<rect x="4" y="4" width="4" height="4" fill="#FFCAC8"/>
|
||||
<rect y="12" width="4" height="4" fill="#BD2211"/>
|
||||
<rect x="12" y="4" width="4" height="20" fill="#FF2D0F"/> -->
|
||||
</svg>
|
After Width: | Height: | Size: 1.7 KiB |
1399
package-lock.json
generated
1399
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
40
package.json
40
package.json
@ -18,7 +18,7 @@
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/electron-react-boilerplate/electron-react-boilerplate.git"
|
||||
"url": "git+https://git.popa-popa.ru/DIKER/popa-launcher.git"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": {
|
||||
@ -42,14 +42,15 @@
|
||||
"postinstall": "ts-node .erb/scripts/check-native-dep.js && electron-builder install-app-deps && npm run build:dll",
|
||||
"lint": "cross-env NODE_ENV=development eslint . --ext .js,.jsx,.ts,.tsx",
|
||||
"lint:fix": "cross-env NODE_ENV=development eslint . --ext .js,.jsx,.ts,.tsx --fix",
|
||||
"package": "ts-node ./.erb/scripts/clean.js dist && npm run build && electron-builder build --publish never && npm run build:dll",
|
||||
"package": "ts-node ./.erb/scripts/clean.js dist && npm run build && electron-builder build --publish always && npm run build:dll",
|
||||
"rebuild": "electron-rebuild --parallel --types prod,dev,optional --module-dir release/app",
|
||||
"prestart": "cross-env NODE_ENV=development TS_NODE_TRANSPILE_ONLY=true NODE_OPTIONS=\"-r ts-node/register --no-warnings\" webpack --config ./.erb/configs/webpack.config.main.dev.ts",
|
||||
"start": "ts-node ./.erb/scripts/check-port-in-use.js && npm run prestart && npm run start:renderer",
|
||||
"start:main": "concurrently -k -P \"cross-env NODE_ENV=development TS_NODE_TRANSPILE_ONLY=true webpack --watch --config ./.erb/configs/webpack.config.main.dev.ts\" \"electronmon . -- {@}\" --",
|
||||
"start:preload": "cross-env NODE_ENV=development TS_NODE_TRANSPILE_ONLY=true NODE_OPTIONS=\"-r ts-node/register --no-warnings\" webpack --config ./.erb/configs/webpack.config.preload.dev.ts",
|
||||
"start:renderer": "cross-env NODE_ENV=development TS_NODE_TRANSPILE_ONLY=true NODE_OPTIONS=\"-r ts-node/register --no-warnings\" webpack serve --config ./.erb/configs/webpack.config.renderer.dev.ts",
|
||||
"test": "jest"
|
||||
"test": "jest",
|
||||
"publish-debug": "electron-builder build --publish always"
|
||||
},
|
||||
"browserslist": [
|
||||
"extends browserslist-config-erb"
|
||||
@ -102,17 +103,36 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@electron/notarize": "^3.0.0",
|
||||
"@emotion/react": "^11.14.0",
|
||||
"@emotion/styled": "^11.14.1",
|
||||
"@mui/icons-material": "^7.2.0",
|
||||
"@mui/material": "^7.2.0",
|
||||
"@xmcl/core": "^2.14.1",
|
||||
"@xmcl/installer": "^6.1.0",
|
||||
"@xmcl/resourcepack": "^1.2.4",
|
||||
"@xmcl/user": "^4.2.0",
|
||||
"electron-debug": "^4.1.0",
|
||||
"electron-log": "^5.3.2",
|
||||
"electron-updater": "^6.3.9",
|
||||
"find-java-home": "^2.0.0",
|
||||
"https-browserify": "^1.0.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"qr-code-styling": "^1.9.2",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-router-dom": "^7.3.0"
|
||||
"react-router-dom": "^7.3.0",
|
||||
"skinview3d": "^3.4.1",
|
||||
"stream-browserify": "^3.0.0",
|
||||
"three": "^0.178.0",
|
||||
"undici": "^7.11.0",
|
||||
"util": "^0.12.5",
|
||||
"uuid": "^11.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@electron/rebuild": "^3.7.1",
|
||||
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.15",
|
||||
"@svgr/webpack": "^8.1.0",
|
||||
"@swc/core": "^1.12.9",
|
||||
"@teamsupercell/typings-for-css-modules-loader": "^2.5.2",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.2.0",
|
||||
@ -121,6 +141,7 @@
|
||||
"@types/react": "^19.0.11",
|
||||
"@types/react-dom": "^19.0.4",
|
||||
"@types/react-test-renderer": "^19.0.0",
|
||||
"@types/three": "^0.178.1",
|
||||
"@types/webpack-bundle-analyzer": "^4.7.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.26.1",
|
||||
"@typescript-eslint/parser": "^8.26.1",
|
||||
@ -175,7 +196,7 @@
|
||||
"webpack-merge": "^6.0.1"
|
||||
},
|
||||
"build": {
|
||||
"productName": "ElectronReact",
|
||||
"productName": "popa-launcher",
|
||||
"appId": "org.erb.ElectronReact",
|
||||
"asar": true,
|
||||
"afterSign": ".erb/scripts/notarize.js",
|
||||
@ -234,9 +255,12 @@
|
||||
"./assets/**"
|
||||
],
|
||||
"publish": {
|
||||
"provider": "github",
|
||||
"owner": "electron-react-boilerplate",
|
||||
"repo": "electron-react-boilerplate"
|
||||
"provider": "generic",
|
||||
"url": "https://git.popa-popa.ru/DIKER/popa-launcher/releases/download/v${version}",
|
||||
"channel": "latest",
|
||||
"requestHeaders": {
|
||||
"Authorization": "token ${env.GH_TOKEN}"
|
||||
}
|
||||
}
|
||||
},
|
||||
"collective": {
|
||||
|
8
release/app/package-lock.json
generated
8
release/app/package-lock.json
generated
@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "electron-react-boilerplate",
|
||||
"version": "4.6.0",
|
||||
"name": "popa-launcher",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "electron-react-boilerplate",
|
||||
"version": "4.6.0",
|
||||
"name": "popa-launcher",
|
||||
"version": "1.0.0",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT"
|
||||
}
|
||||
|
@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "electron-react-boilerplate",
|
||||
"version": "4.6.0",
|
||||
"description": "A foundation for scalable desktop apps",
|
||||
"name": "popa-launcher",
|
||||
"version": "1.0.0",
|
||||
"description": "Popa Launcher",
|
||||
"license": "MIT",
|
||||
"author": {
|
||||
"name": "Electron React Boilerplate Maintainers",
|
||||
"email": "electronreactboilerplate@gmail.com",
|
||||
"url": "https://github.com/electron-react-boilerplate"
|
||||
"name": "DIKER",
|
||||
"email": "diker0k@gmail.com",
|
||||
"url": "https://github.com/DIKER0K"
|
||||
},
|
||||
"main": "./dist/main/main.js",
|
||||
"scripts": {
|
||||
|
92
src/main/auth-service.ts
Normal file
92
src/main/auth-service.ts
Normal file
@ -0,0 +1,92 @@
|
||||
import { YggdrasilClient, YggrasilAuthentication } from '@xmcl/user';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { API_BASE_URL } from '../renderer/api';
|
||||
|
||||
// Ely.by сервер
|
||||
const ELY_BY_AUTH_SERVER = API_BASE_URL;
|
||||
|
||||
export class AuthService {
|
||||
private client: YggdrasilClient;
|
||||
|
||||
constructor() {
|
||||
this.client = new YggdrasilClient(ELY_BY_AUTH_SERVER);
|
||||
}
|
||||
|
||||
async login(
|
||||
username: string,
|
||||
password: string,
|
||||
): Promise<YggrasilAuthentication> {
|
||||
try {
|
||||
// Генерируем уникальный clientToken
|
||||
const clientToken = uuidv4();
|
||||
|
||||
// Выполняем запрос напрямую к правильному URL
|
||||
const response = await fetch(`${ELY_BY_AUTH_SERVER}/auth/authenticate`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username,
|
||||
password,
|
||||
clientToken,
|
||||
requestUser: true,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`Ошибка авторизации: ${response.status} ${errorText}`);
|
||||
}
|
||||
|
||||
const auth = await response.json();
|
||||
console.log(`Аутентификация успешна для ${auth.selectedProfile?.name}`);
|
||||
return auth;
|
||||
} catch (error) {
|
||||
console.error('Ошибка при авторизации:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async validate(accessToken: string, clientToken: string): Promise<boolean> {
|
||||
try {
|
||||
console.log(accessToken, clientToken);
|
||||
const response = await fetch(`${ELY_BY_AUTH_SERVER}/auth/validate`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ accessToken, clientToken }),
|
||||
});
|
||||
|
||||
return response.ok;
|
||||
} catch (error) {
|
||||
console.error('Ошибка при валидации токена:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async refresh(
|
||||
accessToken: string,
|
||||
clientToken: string,
|
||||
): Promise<YggrasilAuthentication | null> {
|
||||
try {
|
||||
const response = await fetch(`${ELY_BY_AUTH_SERVER}/auth/refresh`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ accessToken, clientToken }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error('Ошибка при обновлении токена:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
@ -14,12 +14,47 @@ import { autoUpdater } from 'electron-updater';
|
||||
import log from 'electron-log';
|
||||
import MenuBuilder from './menu';
|
||||
import { resolveHtmlPath } from './util';
|
||||
import {
|
||||
initMinecraftHandlers,
|
||||
initAuthHandlers,
|
||||
initServerStatusHandler,
|
||||
initPackConfigHandlers,
|
||||
} from './minecraft-launcher';
|
||||
|
||||
class AppUpdater {
|
||||
constructor() {
|
||||
log.transports.file.level = 'info';
|
||||
autoUpdater.logger = log;
|
||||
|
||||
const server = 'https://git.popa-popa.ru/DIKER/popa-launcher';
|
||||
|
||||
// Для Gitea нужно указать конкретную структуру URL
|
||||
// Обратите внимание на использование пути /download/
|
||||
autoUpdater.setFeedURL({
|
||||
provider: 'generic',
|
||||
url: `${server}/releases/download/latest`, // Укажите конкретную версию
|
||||
channel: 'latest',
|
||||
});
|
||||
|
||||
// Проверка обновлений
|
||||
autoUpdater.checkForUpdatesAndNotify();
|
||||
|
||||
// Периодическая проверка обновлений (каждый час)
|
||||
setInterval(
|
||||
() => {
|
||||
autoUpdater.checkForUpdatesAndNotify();
|
||||
},
|
||||
60 * 60 * 1000,
|
||||
);
|
||||
|
||||
// Обработчики событий обновления
|
||||
autoUpdater.on('update-downloaded', () => {
|
||||
log.info('Обновление загружено. Будет установлено при перезапуске.');
|
||||
// Можно отправить событие в renderer для уведомления пользователя
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send('update-available');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -43,6 +78,16 @@ if (isDebug) {
|
||||
require('electron-debug').default();
|
||||
}
|
||||
|
||||
ipcMain.handle('close-app', () => {
|
||||
app.quit();
|
||||
return true;
|
||||
});
|
||||
|
||||
ipcMain.handle('minimize-app', () => {
|
||||
mainWindow?.minimize();
|
||||
return true;
|
||||
});
|
||||
|
||||
const installExtensions = async () => {
|
||||
const installer = require('electron-devtools-installer');
|
||||
const forceDownload = !!process.env.UPGRADE_EXTENSIONS;
|
||||
@ -72,9 +117,13 @@ const createWindow = async () => {
|
||||
mainWindow = new BrowserWindow({
|
||||
show: false,
|
||||
width: 1024,
|
||||
height: 728,
|
||||
height: 850,
|
||||
autoHideMenuBar: true,
|
||||
resizable: true,
|
||||
frame: false,
|
||||
icon: getAssetPath('icon.png'),
|
||||
webPreferences: {
|
||||
webSecurity: false,
|
||||
preload: app.isPackaged
|
||||
? path.join(__dirname, 'preload.js')
|
||||
: path.join(__dirname, '../../.erb/dll/preload.js'),
|
||||
@ -110,6 +159,11 @@ const createWindow = async () => {
|
||||
// Remove this if your app does not use auto updates
|
||||
// eslint-disable-next-line
|
||||
new AppUpdater();
|
||||
|
||||
initAuthHandlers();
|
||||
initMinecraftHandlers();
|
||||
initServerStatusHandler();
|
||||
initPackConfigHandlers();
|
||||
};
|
||||
|
||||
/**
|
||||
@ -135,3 +189,7 @@ app
|
||||
});
|
||||
})
|
||||
.catch(console.log);
|
||||
|
||||
ipcMain.handle('install-update', () => {
|
||||
autoUpdater.quitAndInstall();
|
||||
});
|
||||
|
1182
src/main/minecraft-launcher.ts
Normal file
1182
src/main/minecraft-launcher.ts
Normal file
File diff suppressed because it is too large
Load Diff
@ -1,8 +1,19 @@
|
||||
// Disable no-unused-vars, broken for spread args
|
||||
/* eslint no-unused-vars: off */
|
||||
import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron';
|
||||
|
||||
export type Channels = 'ipc-example';
|
||||
export type Channels =
|
||||
| 'ipc-example'
|
||||
| 'download-progress'
|
||||
| 'launch-minecraft'
|
||||
| 'installation-status'
|
||||
| 'get-server-status'
|
||||
| 'close-app'
|
||||
| 'minimize-app'
|
||||
| 'save-pack-config'
|
||||
| 'load-pack-config'
|
||||
| 'update-available'
|
||||
| 'install-update'
|
||||
| 'get-installed-versions'
|
||||
| 'get-available-versions';
|
||||
|
||||
const electronHandler = {
|
||||
ipcRenderer: {
|
||||
@ -21,6 +32,9 @@ const electronHandler = {
|
||||
once(channel: Channels, func: (...args: unknown[]) => void) {
|
||||
ipcRenderer.once(channel, (_event, ...args) => func(...args));
|
||||
},
|
||||
invoke(channel: Channels, ...args: unknown[]): Promise<any> {
|
||||
return ipcRenderer.invoke(channel, ...args);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
|
@ -1,62 +1,59 @@
|
||||
/*
|
||||
* @NOTE: Prepend a `~` to css file paths that are in your node_modules
|
||||
* See https://github.com/webpack-contrib/sass-loader#imports
|
||||
*/
|
||||
@font-face {
|
||||
font-family: 'Benzin-Bold';
|
||||
src: url('../../assets/fonts/benzin-bold.eot'); /* IE 9 Compatibility Mode */
|
||||
src:
|
||||
url('../../assets/fonts/benzin-bold.eot?#iefix') format('embedded-opentype'),
|
||||
/* IE < 9 */ url('../../assets/fonts/benzin-bold.woff2') format('woff2'),
|
||||
/* Super Modern Browsers */ url('../../assets/fonts/benzin-bold.woff')
|
||||
format('woff'),
|
||||
/* Firefox >= 3.6, any other modern browser */
|
||||
url('../../assets/fonts/benzin-bold.ttf') format('truetype'),
|
||||
/* Safari, Android, iOS */
|
||||
url('../../assets/fonts/benzin-bold.svg#benzin-bold') format('svg'); /* Chrome < 4, Legacy iOS */
|
||||
}
|
||||
|
||||
body {
|
||||
position: relative;
|
||||
color: white;
|
||||
height: 100vh;
|
||||
background: linear-gradient(
|
||||
200.96deg,
|
||||
#fedc2a -29.09%,
|
||||
#dd5789 51.77%,
|
||||
#7a2c9e 129.35%
|
||||
);
|
||||
font-family: sans-serif;
|
||||
background: linear-gradient(242.94deg, #000000 39.07%, #3b4187 184.73%);
|
||||
font-family: 'Benzin-Bold' !important;
|
||||
overflow-y: hidden;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
button {
|
||||
background-color: white;
|
||||
padding: 10px 20px;
|
||||
border-radius: 10px;
|
||||
border: none;
|
||||
appearance: none;
|
||||
font-size: 1.3rem;
|
||||
box-shadow: 0px 8px 28px -6px rgba(24, 39, 75, 0.12),
|
||||
0px 18px 88px -4px rgba(24, 39, 75, 0.14);
|
||||
transition: all ease-in 0.1s;
|
||||
cursor: pointer;
|
||||
opacity: 0.9;
|
||||
p {
|
||||
font-family: 'Benzin-Bold' !important;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
transform: scale(1.05);
|
||||
opacity: 1;
|
||||
h1 {
|
||||
font-family: 'Benzin-Bold' !important;
|
||||
}
|
||||
|
||||
li {
|
||||
list-style: none;
|
||||
h2 {
|
||||
font-family: 'Benzin-Bold' !important;
|
||||
}
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
height: fit-content;
|
||||
width: fit-content;
|
||||
margin: 10px;
|
||||
h3 {
|
||||
font-family: 'Benzin-Bold' !important;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
opacity: 1;
|
||||
text-decoration: none;
|
||||
h4 {
|
||||
font-family: 'Benzin-Bold' !important;
|
||||
}
|
||||
|
||||
.Hello {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
margin: 20px 0;
|
||||
h5 {
|
||||
font-family: 'Benzin-Bold' !important;
|
||||
}
|
||||
|
||||
h6 {
|
||||
font-family: 'Benzin-Bold' !important;
|
||||
}
|
||||
|
||||
span {
|
||||
font-family: 'Benzin-Bold' !important;
|
||||
}
|
||||
|
@ -1,50 +1,178 @@
|
||||
import { MemoryRouter as Router, Routes, Route } from 'react-router-dom';
|
||||
import icon from '../../assets/icon.svg';
|
||||
import {
|
||||
MemoryRouter as Router,
|
||||
Routes,
|
||||
Route,
|
||||
Navigate,
|
||||
useNavigate,
|
||||
} from 'react-router-dom';
|
||||
import Login from './pages/Login';
|
||||
import LaunchPage from './pages/LaunchPage';
|
||||
import { ReactNode, useEffect, useState } from 'react';
|
||||
import './App.css';
|
||||
import TopBar from './components/TopBar';
|
||||
import { Box } from '@mui/material';
|
||||
import MinecraftBackground from './components/MinecraftBackground';
|
||||
import { Notifier } from './components/Notifier';
|
||||
import { VersionsExplorer } from './pages/VersionsExplorer';
|
||||
import Profile from './pages/Profile';
|
||||
import Shop from './pages/Shop';
|
||||
import Marketplace from './pages/Marketplace';
|
||||
import { Registration } from './pages/Registration';
|
||||
|
||||
function Hello() {
|
||||
return (
|
||||
<div>
|
||||
<div className="Hello">
|
||||
<img width="200" alt="icon" src={icon} />
|
||||
</div>
|
||||
<h1>electron-react-boilerplate</h1>
|
||||
<div className="Hello">
|
||||
<a
|
||||
href="https://electron-react-boilerplate.js.org/"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
<button type="button">
|
||||
<span role="img" aria-label="books">
|
||||
📚
|
||||
</span>
|
||||
Read our docs
|
||||
</button>
|
||||
</a>
|
||||
<a
|
||||
href="https://github.com/sponsors/electron-react-boilerplate"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
<button type="button">
|
||||
<span role="img" aria-label="folded hands">
|
||||
🙏
|
||||
</span>
|
||||
Donate
|
||||
</button>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const AuthCheck = ({ children }: { children: ReactNode }) => {
|
||||
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const checkAuth = async () => {
|
||||
try {
|
||||
const savedConfig = localStorage.getItem('launcher_config');
|
||||
if (savedConfig) {
|
||||
const config = JSON.parse(savedConfig);
|
||||
if (config.accessToken) {
|
||||
// Можно добавить дополнительную проверку токена
|
||||
const isValid = await validateToken(
|
||||
config.accessToken,
|
||||
config.clientToken,
|
||||
);
|
||||
setIsAuthenticated(isValid);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setIsAuthenticated(false);
|
||||
} catch (error) {
|
||||
console.error('Ошибка проверки авторизации:', error);
|
||||
setIsAuthenticated(false);
|
||||
}
|
||||
};
|
||||
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
const validateToken = async (accessToken: string, clientToken: string) => {
|
||||
try {
|
||||
// Используем IPC для валидации токена через main процесс
|
||||
const result = await window.electron.ipcRenderer.invoke(
|
||||
'validate-token',
|
||||
{ accessToken, clientToken },
|
||||
);
|
||||
|
||||
// Если токен недействителен, очищаем сохраненные данные в localStorage
|
||||
if (!result.valid) {
|
||||
console.log(
|
||||
'Токен недействителен, очищаем данные авторизации из localStorage',
|
||||
);
|
||||
const savedConfig = localStorage.getItem('launcher_config');
|
||||
if (savedConfig) {
|
||||
const config = JSON.parse(savedConfig);
|
||||
// Сохраняем только логин и другие настройки, но удаляем токены
|
||||
const cleanedConfig = {
|
||||
username: config.username,
|
||||
memory: config.memory || 4096,
|
||||
comfortVersion: config.comfortVersion || '',
|
||||
password: '', // Очищаем пароль для безопасности
|
||||
};
|
||||
localStorage.setItem(
|
||||
'launcher_config',
|
||||
JSON.stringify(cleanedConfig),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return result.valid;
|
||||
} catch (error) {
|
||||
console.error('Ошибка проверки токена:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
if (isAuthenticated === null) {
|
||||
return <div>Loading...</div>;
|
||||
}
|
||||
|
||||
return isAuthenticated ? children : <Navigate to="/login" replace />;
|
||||
};
|
||||
|
||||
const App = () => {
|
||||
// Просто используйте window.open без useNavigate
|
||||
const handleRegister = () => {
|
||||
window.open('https://account.ely.by/register', '_blank');
|
||||
};
|
||||
const [username, setUsername] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const savedConfig = localStorage.getItem('launcher_config');
|
||||
if (savedConfig) {
|
||||
const config = JSON.parse(savedConfig);
|
||||
if (config.username) {
|
||||
setUsername(config.username);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<Router>
|
||||
<Routes>
|
||||
<Route path="/" element={<Hello />} />
|
||||
</Routes>
|
||||
<Box
|
||||
sx={{
|
||||
height: '100vh',
|
||||
width: '100vw',
|
||||
position: 'relative',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
overflowX: 'hidden',
|
||||
}}
|
||||
>
|
||||
<MinecraftBackground />
|
||||
<TopBar onRegister={handleRegister} username={username || ''} />
|
||||
<Notifier />
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/registration" element={<Registration />} />
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
<AuthCheck>
|
||||
<VersionsExplorer />
|
||||
</AuthCheck>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/launch/:versionId"
|
||||
element={
|
||||
<AuthCheck>
|
||||
<LaunchPage />
|
||||
</AuthCheck>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/profile"
|
||||
element={
|
||||
<AuthCheck>
|
||||
<Profile />
|
||||
</AuthCheck>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/shop"
|
||||
element={
|
||||
<AuthCheck>
|
||||
<Shop />
|
||||
</AuthCheck>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/marketplace"
|
||||
element={
|
||||
<AuthCheck>
|
||||
<Marketplace />
|
||||
</AuthCheck>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
</Box>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export default App;
|
||||
|
628
src/renderer/api.ts
Normal file
628
src/renderer/api.ts
Normal file
@ -0,0 +1,628 @@
|
||||
export const API_BASE_URL = 'https://minecraft.api.popa-popa.ru';
|
||||
|
||||
export interface Player {
|
||||
uuid: string;
|
||||
username: string;
|
||||
skin_url: string;
|
||||
cloak_url: string;
|
||||
coins: number;
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface CoinsResponse {
|
||||
username: string;
|
||||
coins: number;
|
||||
total_time_played: {
|
||||
seconds: number;
|
||||
formatted: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Cape {
|
||||
cape_id: string;
|
||||
cape_name: string;
|
||||
cape_description: string;
|
||||
image_url: string;
|
||||
purchased_at: string;
|
||||
is_active: boolean;
|
||||
}
|
||||
|
||||
export type CapesResponse = Cape[];
|
||||
|
||||
export interface StoreCape {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
price: number;
|
||||
image_url: string;
|
||||
}
|
||||
|
||||
export type StoreCapesResponse = StoreCape[];
|
||||
|
||||
export interface ApiError {
|
||||
message: string;
|
||||
details?: string;
|
||||
}
|
||||
|
||||
export interface Server {
|
||||
id: string;
|
||||
name: string;
|
||||
ip: string;
|
||||
port: number;
|
||||
description: string;
|
||||
online_players: number;
|
||||
max_players: number;
|
||||
last_activity: string;
|
||||
}
|
||||
|
||||
export interface ActiveServersResponse {
|
||||
servers: Server[];
|
||||
}
|
||||
|
||||
export interface OnlinePlayersResponse {
|
||||
server: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
online_players: {
|
||||
// Это массив объектов, а не один объект
|
||||
username: string;
|
||||
uuid: string;
|
||||
online_since: string;
|
||||
}[]; // Добавьте [] здесь чтобы указать, что это массив
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface MarketplaceResponse {
|
||||
items: [
|
||||
{
|
||||
_id: string;
|
||||
id: string;
|
||||
material: string;
|
||||
amount: number;
|
||||
price: number;
|
||||
seller_name: string;
|
||||
server_ip: string;
|
||||
display_name: string | null;
|
||||
lore: string | null;
|
||||
enchants: string | null;
|
||||
item_data: {
|
||||
slot: number;
|
||||
material: string;
|
||||
amount: number;
|
||||
};
|
||||
created_at: string;
|
||||
},
|
||||
];
|
||||
total: number;
|
||||
page: number;
|
||||
pages: number;
|
||||
}
|
||||
|
||||
export interface MarketplaceItemResponse {
|
||||
_id: string;
|
||||
id: string;
|
||||
material: string;
|
||||
amount: number;
|
||||
price: number;
|
||||
seller_name: string;
|
||||
server_ip: string;
|
||||
display_name: string | null;
|
||||
lore: string | null;
|
||||
enchants: string | null;
|
||||
item_data: {
|
||||
slot: number;
|
||||
material: string;
|
||||
amount: number;
|
||||
};
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface SellItemResponse {
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface BuyItemResponse {
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface PlayerInventoryResponse {
|
||||
status: string;
|
||||
request_id: string;
|
||||
}
|
||||
|
||||
export interface PlayerInventory {
|
||||
status: string;
|
||||
result: {
|
||||
player_name: string;
|
||||
server_ip: string;
|
||||
inventory_data: PlayerInventoryItem[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface PlayerInventoryItem {
|
||||
slot: number;
|
||||
material: string;
|
||||
amount: number;
|
||||
enchants: {
|
||||
[key: string]: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface MarketplaceOperation {
|
||||
id: string;
|
||||
type: 'sell' | 'buy';
|
||||
player_name: string;
|
||||
slot_index?: number;
|
||||
amount?: number;
|
||||
price: number;
|
||||
server_ip: string;
|
||||
status: 'pending' | 'completed' | 'failed';
|
||||
item_id?: string;
|
||||
error?: string;
|
||||
created_at: string;
|
||||
item_data?: any;
|
||||
}
|
||||
|
||||
export interface OperationsResponse {
|
||||
operations: MarketplaceOperation[];
|
||||
}
|
||||
|
||||
export interface RegisterUserResponse {
|
||||
status: string;
|
||||
uuid: string;
|
||||
}
|
||||
|
||||
export interface GenerateVerificationCodeResponse {
|
||||
status: string;
|
||||
code: string;
|
||||
}
|
||||
|
||||
export interface VerificationStatusResponse {
|
||||
is_verified: boolean;
|
||||
}
|
||||
|
||||
export async function getVerificationStatus(
|
||||
username: string,
|
||||
): Promise<VerificationStatusResponse> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/auth/verification_status/${username}`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Не удалось получить статус верификации');
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
export async function generateVerificationCode(
|
||||
username: string,
|
||||
): Promise<GenerateVerificationCodeResponse> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/auth/generate_code?username=${username}`,
|
||||
{
|
||||
method: 'POST',
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Не удалось сгенерировать код верификации');
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
export async function registerUser(
|
||||
username: string,
|
||||
password: string,
|
||||
): Promise<RegisterUserResponse> {
|
||||
const response = await fetch(`${API_BASE_URL}/auth/register`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username,
|
||||
password,
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('Не удалось зарегистрировать пользователя');
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
export async function getPlayerInventory(
|
||||
request_id: string,
|
||||
): Promise<PlayerInventory> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/server/inventory/${request_id}`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Не удалось получить инвентарь игрока');
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
export async function RequestPlayerInventory(
|
||||
server_ip: string,
|
||||
player_name: string,
|
||||
): Promise<PlayerInventoryResponse> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/server/inventory`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
server_ip: server_ip,
|
||||
player_name: player_name,
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('Не удалось получить инвентарь игрока');
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
export async function buyItem(
|
||||
buyer_username: string,
|
||||
item_id: string,
|
||||
): Promise<{ status: string; operation_id: string; message: string }> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/marketplace/items/buy/${item_id}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username: buyer_username,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(
|
||||
errorData.message || errorData.detail || 'Не удалось купить предмет',
|
||||
);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
export async function confirmMarketplaceOperation(
|
||||
operation_id: string,
|
||||
status: string = 'success',
|
||||
error?: string,
|
||||
): Promise<{ status: string }> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/marketplace/operations/confirm`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
operation_id,
|
||||
status,
|
||||
error,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Не удалось подтвердить операцию');
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
export async function submitItemDetails(
|
||||
operation_id: string,
|
||||
item_data: any,
|
||||
): Promise<{ status: string }> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/marketplace/items/details`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
operation_id,
|
||||
item_data,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Не удалось отправить данные предмета');
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
export async function sellItem(
|
||||
username: string,
|
||||
slot_index: number,
|
||||
amount: number,
|
||||
price: number,
|
||||
server_ip: string,
|
||||
): Promise<{ status: string; operation_id: string }> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/marketplace/items/sell`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username,
|
||||
slot_index,
|
||||
amount,
|
||||
price,
|
||||
server_ip,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(
|
||||
errorData.message ||
|
||||
errorData.detail ||
|
||||
'Не удалось выставить предмет на продажу',
|
||||
);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
export async function fetchMarketplaceItem(
|
||||
item_id: string,
|
||||
): Promise<MarketplaceItemResponse> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/marketplace/items/${item_id}`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Не удалось получить рынок');
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
export async function fetchMarketplace(
|
||||
server_ip: string,
|
||||
page: number,
|
||||
limit: number,
|
||||
): Promise<MarketplaceResponse> {
|
||||
// Создаем URL с параметрами запроса
|
||||
const url = new URL(`${API_BASE_URL}/api/marketplace/items`);
|
||||
url.searchParams.append('server_ip', server_ip);
|
||||
url.searchParams.append('page', page.toString());
|
||||
url.searchParams.append('limit', limit.toString());
|
||||
|
||||
const response = await fetch(url.toString());
|
||||
if (!response.ok) {
|
||||
throw new Error('Не удалось получить предметы рынка');
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
// Исправьте тип возвращаемого значения
|
||||
export async function fetchActiveServers(): Promise<Server[]> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/pranks/servers`);
|
||||
if (!response.ok) {
|
||||
throw new Error('Не удалось получить активные сервера');
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
export async function fetchOnlinePlayers(
|
||||
server_id: string,
|
||||
): Promise<OnlinePlayersResponse> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/pranks/servers/${server_id}/players`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Не удалось получить онлайн игроков');
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
// Получение информации о игроке
|
||||
export async function fetchPlayer(uuid: string): Promise<Player> {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/users/${uuid}`);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.message || 'Ошибка получения данных игрока');
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error('API ошибка:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchCoins(username: string): Promise<CoinsResponse> {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/users/${username}/coins`);
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.message || 'Ошибка получения данных игрока');
|
||||
}
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error('API ошибка:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchCapes(username: string): Promise<CapesResponse> {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/store/user/${username}/capes`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
return []; // Если плащи не найдены, возвращаем пустой массив
|
||||
}
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error('API ошибка:', error);
|
||||
return []; // В случае ошибки возвращаем пустой массив
|
||||
}
|
||||
}
|
||||
|
||||
export async function purchaseCape(
|
||||
username: string,
|
||||
cape_id: string,
|
||||
): Promise<void> {
|
||||
// Создаем URL с query-параметрами
|
||||
const url = new URL(`${API_BASE_URL}/store/purchase/cape`);
|
||||
url.searchParams.append('username', username);
|
||||
url.searchParams.append('cape_id', cape_id);
|
||||
|
||||
const response = await fetch(url.toString(), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
// Не нужно отправлять тело запроса
|
||||
// body: JSON.stringify({
|
||||
// username: username,
|
||||
// cape_id: cape_id,
|
||||
// }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(
|
||||
errorData.message ||
|
||||
errorData.detail?.toString() ||
|
||||
'Не удалось купить плащ',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchCapesStore(): Promise<StoreCape[]> {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/store/capes`);
|
||||
if (!response.ok) {
|
||||
return [];
|
||||
}
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error('API ошибка:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function activateCape(
|
||||
username: string,
|
||||
cape_id: string,
|
||||
): Promise<void> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/store/user/${username}/capes/activate/${cape_id}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
cape_id: cape_id,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Не удалось активировать плащ');
|
||||
}
|
||||
}
|
||||
|
||||
export async function deactivateCape(
|
||||
username: string,
|
||||
cape_id: string,
|
||||
): Promise<void> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/store/user/${username}/capes/deactivate/${cape_id}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
cape_id: cape_id,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Не удалось деактивировать плащ');
|
||||
}
|
||||
}
|
||||
|
||||
// Загрузка скина
|
||||
export async function uploadSkin(
|
||||
username: string,
|
||||
skinFile: File,
|
||||
skinModel: string,
|
||||
): Promise<void> {
|
||||
const savedConfig = localStorage.getItem('launcher_config');
|
||||
let accessToken = '';
|
||||
let clientToken = '';
|
||||
|
||||
if (savedConfig) {
|
||||
const config = JSON.parse(savedConfig);
|
||||
accessToken = config.accessToken || '';
|
||||
clientToken = config.clientToken || '';
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('skin_file', skinFile);
|
||||
formData.append('skin_model', skinModel);
|
||||
formData.append('accessToken', accessToken);
|
||||
formData.append('clientToken', clientToken);
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}/user/${username}/skin`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.message || 'Не удалось загрузить скин');
|
||||
}
|
||||
}
|
||||
|
||||
// Получение токенов из локального хранилища
|
||||
export function getAuthTokens(): { accessToken: string; clientToken: string } {
|
||||
const savedConfig = localStorage.getItem('launcher_config');
|
||||
let accessToken = '';
|
||||
let clientToken = '';
|
||||
|
||||
if (savedConfig) {
|
||||
const config = JSON.parse(savedConfig);
|
||||
accessToken = config.accessToken || '';
|
||||
clientToken = config.clientToken || '';
|
||||
}
|
||||
|
||||
return { accessToken, clientToken };
|
||||
}
|
||||
|
||||
// Загрузка плаща
|
||||
export async function uploadCape(
|
||||
username: string,
|
||||
capeFile: File,
|
||||
): Promise<void> {
|
||||
const { accessToken, clientToken } = getAuthTokens();
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('cape_file', capeFile);
|
||||
formData.append('accessToken', accessToken);
|
||||
formData.append('clientToken', clientToken);
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}/user/${username}/cape`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.message || 'Не удалось загрузить плащ');
|
||||
}
|
||||
}
|
127
src/renderer/components/CapeCard.tsx
Normal file
127
src/renderer/components/CapeCard.tsx
Normal file
@ -0,0 +1,127 @@
|
||||
// src/renderer/components/CapeCard.tsx
|
||||
import React from 'react';
|
||||
import {
|
||||
Card,
|
||||
CardMedia,
|
||||
CardContent,
|
||||
Typography,
|
||||
CardActions,
|
||||
Button,
|
||||
Tooltip,
|
||||
Box,
|
||||
Chip,
|
||||
} from '@mui/material';
|
||||
|
||||
// Тип для плаща с необязательными полями для обоих вариантов использования
|
||||
export interface CapeCardProps {
|
||||
cape: {
|
||||
cape_id?: string;
|
||||
id?: string;
|
||||
cape_name?: string;
|
||||
name?: string;
|
||||
cape_description?: string;
|
||||
description?: string;
|
||||
image_url: string;
|
||||
is_active?: boolean;
|
||||
price?: number;
|
||||
purchased_at?: string;
|
||||
};
|
||||
mode: 'profile' | 'shop';
|
||||
onAction: (capeId: string) => void;
|
||||
actionDisabled?: boolean;
|
||||
}
|
||||
|
||||
export default function CapeCard({
|
||||
cape,
|
||||
mode,
|
||||
onAction,
|
||||
actionDisabled = false,
|
||||
}: CapeCardProps) {
|
||||
// Определяем текст и цвет кнопки в зависимости от режима
|
||||
const getActionButton = () => {
|
||||
if (mode === 'shop') {
|
||||
return {
|
||||
text: 'Купить',
|
||||
color: 'primary',
|
||||
};
|
||||
} else {
|
||||
// Профиль
|
||||
return cape.is_active
|
||||
? { text: 'Снять', color: 'error' }
|
||||
: { text: 'Надеть', color: 'success' };
|
||||
}
|
||||
};
|
||||
|
||||
const actionButton = getActionButton();
|
||||
|
||||
// В функции компонента добавьте нормализацию данных
|
||||
const capeId = cape.cape_id || cape.id || '';
|
||||
const capeName = cape.cape_name || cape.name || '';
|
||||
const capeDescription = cape.cape_description || cape.description || '';
|
||||
|
||||
return (
|
||||
<Tooltip arrow title={capeDescription}>
|
||||
<Card
|
||||
sx={{
|
||||
bgcolor: 'rgba(255, 255, 255, 0.05)',
|
||||
width: 200,
|
||||
overflow: 'hidden',
|
||||
position: 'relative', // для позиционирования ценника
|
||||
}}
|
||||
>
|
||||
{/* Ценник для магазина */}
|
||||
{mode === 'shop' && cape.price !== undefined && (
|
||||
<Chip
|
||||
label={`${cape.price} коинов`}
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
top: 8,
|
||||
right: 8,
|
||||
zIndex: 2,
|
||||
bgcolor: 'rgba(0, 0, 0, 0.7)',
|
||||
color: 'white',
|
||||
fontWeight: 'bold',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<CardMedia
|
||||
component="img"
|
||||
image={cape.image_url}
|
||||
alt={capeName}
|
||||
sx={{
|
||||
display: 'block',
|
||||
width: '100%',
|
||||
transform: 'scale(2.9) translateX(66px) translateY(32px)',
|
||||
imageRendering: 'pixelated',
|
||||
}}
|
||||
/>
|
||||
|
||||
<CardContent sx={{ bgcolor: 'rgba(255, 255, 255, 0.05)', pt: '9vh' }}>
|
||||
<Typography sx={{ color: 'white' }}>{capeName}</Typography>
|
||||
</CardContent>
|
||||
|
||||
<CardActions sx={{ display: 'flex', justifyContent: 'center' }}>
|
||||
<Button
|
||||
variant="contained"
|
||||
color={actionButton.color as 'primary' | 'success' | 'error'}
|
||||
onClick={() => onAction(capeId)}
|
||||
disabled={actionDisabled}
|
||||
sx={{
|
||||
borderRadius: '20px',
|
||||
p: '5px 25px',
|
||||
color: 'white',
|
||||
backgroundColor: 'rgb(0, 134, 0)',
|
||||
'&:hover': {
|
||||
backgroundColor: 'rgba(0, 134, 0, 0.5)',
|
||||
},
|
||||
fontFamily: 'Benzin-Bold',
|
||||
}}
|
||||
>
|
||||
{actionButton.text}
|
||||
</Button>
|
||||
</CardActions>
|
||||
</Card>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
205
src/renderer/components/FilesSelector.tsx
Normal file
205
src/renderer/components/FilesSelector.tsx
Normal file
@ -0,0 +1,205 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Checkbox,
|
||||
Typography,
|
||||
List,
|
||||
ListItem,
|
||||
ListItemIcon,
|
||||
ListItemText,
|
||||
Collapse,
|
||||
CircularProgress,
|
||||
} from '@mui/material';
|
||||
import FolderIcon from '@mui/icons-material/Folder';
|
||||
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';
|
||||
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
|
||||
import ExpandLessIcon from '@mui/icons-material/ExpandLess';
|
||||
|
||||
interface FileNode {
|
||||
name: string;
|
||||
path: string;
|
||||
isDirectory: boolean;
|
||||
children: FileNode[];
|
||||
}
|
||||
|
||||
interface FilesSelectorProps {
|
||||
packName: string;
|
||||
onSelectionChange: (selectedFiles: string[]) => void;
|
||||
initialSelected?: string[]; // Добавляем этот параметр
|
||||
}
|
||||
|
||||
export default function FilesSelector({
|
||||
packName,
|
||||
onSelectionChange,
|
||||
initialSelected = [], // Значение по умолчанию
|
||||
}: FilesSelectorProps) {
|
||||
const [files, setFiles] = useState<FileNode[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// Используем initialSelected для начального состояния
|
||||
const [selectedFiles, setSelectedFiles] = useState<string[]>(initialSelected);
|
||||
const [expandedFolders, setExpandedFolders] = useState<Set<string>>(
|
||||
new Set(),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchFiles = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const result = await window.electron.ipcRenderer.invoke(
|
||||
'get-pack-files',
|
||||
packName,
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
setFiles(result.files);
|
||||
} else {
|
||||
setError(result.error);
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Ошибка при загрузке файлов');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchFiles();
|
||||
}, [packName]);
|
||||
|
||||
// Обработка выбора файла/папки
|
||||
const handleToggle = (
|
||||
path: string,
|
||||
isDirectory: boolean,
|
||||
children: FileNode[],
|
||||
) => {
|
||||
let newSelected = [...selectedFiles];
|
||||
|
||||
if (isDirectory) {
|
||||
if (selectedFiles.includes(path)) {
|
||||
// Если папка выбрана, убираем ее и все вложенные файлы
|
||||
newSelected = newSelected.filter((p) => !p.startsWith(path));
|
||||
} else {
|
||||
// Если папка не выбрана, добавляем ее и все вложенные файлы
|
||||
newSelected.push(path);
|
||||
const addChildPaths = (nodes: FileNode[]) => {
|
||||
for (const node of nodes) {
|
||||
newSelected.push(node.path);
|
||||
if (node.isDirectory) {
|
||||
addChildPaths(node.children);
|
||||
}
|
||||
}
|
||||
};
|
||||
addChildPaths(children);
|
||||
}
|
||||
} else {
|
||||
// Для обычного файла просто переключаем состояние
|
||||
if (selectedFiles.includes(path)) {
|
||||
newSelected = newSelected.filter((p) => p !== path);
|
||||
} else {
|
||||
newSelected.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
setSelectedFiles(newSelected);
|
||||
onSelectionChange(newSelected);
|
||||
};
|
||||
|
||||
// Переключение раскрытия папки
|
||||
const toggleFolder = (path: string) => {
|
||||
const newExpanded = new Set(expandedFolders);
|
||||
if (expandedFolders.has(path)) {
|
||||
newExpanded.delete(path);
|
||||
} else {
|
||||
newExpanded.add(path);
|
||||
}
|
||||
setExpandedFolders(newExpanded);
|
||||
};
|
||||
|
||||
// Рекурсивный компонент для отображения файлов и папок
|
||||
const renderFileTree = (nodes: FileNode[]) => {
|
||||
// Сортировка: сначала папки, потом файлы
|
||||
const sortedNodes = [...nodes].sort((a, b) => {
|
||||
// Если у элементов разные типы (папка/файл)
|
||||
if (a.isDirectory !== b.isDirectory) {
|
||||
return a.isDirectory ? -1 : 1; // Папки идут первыми
|
||||
}
|
||||
// Если оба элемента одного типа, сортируем по алфавиту
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
return (
|
||||
<List dense>
|
||||
{sortedNodes.map((node) => (
|
||||
<div key={node.path}>
|
||||
<ListItem
|
||||
sx={{
|
||||
borderRadius: '3vw',
|
||||
backgroundColor: '#FFFFFF1A',
|
||||
marginBottom: '1vh',
|
||||
}}
|
||||
>
|
||||
<ListItemIcon>
|
||||
<Checkbox
|
||||
edge="start"
|
||||
checked={selectedFiles.includes(node.path)}
|
||||
onChange={() =>
|
||||
handleToggle(node.path, node.isDirectory, node.children)
|
||||
}
|
||||
tabIndex={-1}
|
||||
sx={{ color: 'white' }}
|
||||
/>
|
||||
</ListItemIcon>
|
||||
|
||||
{node.isDirectory && (
|
||||
<ListItemIcon onClick={() => toggleFolder(node.path)}>
|
||||
{expandedFolders.has(node.path) ? (
|
||||
<ExpandLessIcon sx={{ color: 'white' }} />
|
||||
) : (
|
||||
<ExpandMoreIcon sx={{ color: 'white' }} />
|
||||
)}
|
||||
</ListItemIcon>
|
||||
)}
|
||||
|
||||
<ListItemIcon>
|
||||
{node.isDirectory ? (
|
||||
<FolderIcon sx={{ color: 'white' }} />
|
||||
) : (
|
||||
<InsertDriveFileIcon sx={{ color: 'white' }} />
|
||||
)}
|
||||
</ListItemIcon>
|
||||
|
||||
<ListItemText
|
||||
primary={node.name}
|
||||
sx={{ color: 'white', fontFamily: 'Benzin-Bold' }}
|
||||
/>
|
||||
</ListItem>
|
||||
|
||||
{node.isDirectory && node.children.length > 0 && (
|
||||
<Collapse
|
||||
in={expandedFolders.has(node.path)}
|
||||
timeout="auto"
|
||||
unmountOnExit
|
||||
>
|
||||
<Box sx={{ pl: 4 }}>{renderFileTree(node.children)}</Box>
|
||||
</Collapse>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</List>
|
||||
);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <CircularProgress />;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return <Typography color="error">{error}</Typography>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box sx={{ maxHeight: '300px', overflow: 'auto' }}>
|
||||
{renderFileTree(files)}
|
||||
</Box>
|
||||
);
|
||||
}
|
94
src/renderer/components/Login/AuthForm.tsx
Normal file
94
src/renderer/components/Login/AuthForm.tsx
Normal file
@ -0,0 +1,94 @@
|
||||
import { Box, Button, TextField, Typography } from '@mui/material';
|
||||
|
||||
interface AuthFormProps {
|
||||
config: {
|
||||
username: string;
|
||||
password: string;
|
||||
};
|
||||
handleInputChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
|
||||
onLogin: () => void;
|
||||
}
|
||||
|
||||
const AuthForm = ({ config, handleInputChange, onLogin }: AuthFormProps) => {
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '1.5vw',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6">Логин</Typography>
|
||||
<TextField
|
||||
required
|
||||
name="username"
|
||||
variant="outlined"
|
||||
value={config.username}
|
||||
onChange={handleInputChange}
|
||||
sx={{
|
||||
width: '100%',
|
||||
// '& .MuiFormLabel-root': {
|
||||
// color: 'white',
|
||||
// },
|
||||
'& .MuiInputBase-input': {
|
||||
color: 'white',
|
||||
},
|
||||
'& .MuiInput-underline:after': {
|
||||
borderBottomColor: '#B2BAC2',
|
||||
},
|
||||
'& .MuiOutlinedInput-root': {
|
||||
'& fieldset': {
|
||||
borderColor: '#E0E3E7',
|
||||
color: 'white',
|
||||
},
|
||||
'&:hover fieldset': {
|
||||
borderColor: '#B2BAC2',
|
||||
},
|
||||
'&.Mui-focused fieldset': {
|
||||
borderColor: '#6F7E8C',
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<Typography variant="h6">Пароль</Typography>
|
||||
<TextField
|
||||
required
|
||||
type="password"
|
||||
name="password"
|
||||
variant="outlined"
|
||||
value={config.password}
|
||||
onChange={handleInputChange}
|
||||
sx={{
|
||||
width: '100%',
|
||||
// '& .MuiFormLabel-root': {
|
||||
// color: 'white',
|
||||
// },
|
||||
'& .MuiInputBase-input': {
|
||||
color: 'white',
|
||||
},
|
||||
'& .MuiInput-underline:after': {
|
||||
borderBottomColor: '#B2BAC2',
|
||||
},
|
||||
'& .MuiOutlinedInput-root': {
|
||||
'& fieldset': {
|
||||
borderColor: '#E0E3E7',
|
||||
color: 'white',
|
||||
},
|
||||
'&:hover fieldset': {
|
||||
borderColor: '#B2BAC2',
|
||||
},
|
||||
'&.Mui-focused fieldset': {
|
||||
borderColor: '#6F7E8C',
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<Button onClick={onLogin} variant="contained">
|
||||
Войти
|
||||
</Button>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default AuthForm;
|
26
src/renderer/components/Login/MemorySlider.tsx
Normal file
26
src/renderer/components/Login/MemorySlider.tsx
Normal file
@ -0,0 +1,26 @@
|
||||
import { Slider } from '@mui/material';
|
||||
|
||||
interface MemorySliderProps {
|
||||
memory: number;
|
||||
onChange: (e: Event, value: number | number[]) => void;
|
||||
}
|
||||
|
||||
const MemorySlider = ({ memory, onChange }: MemorySliderProps) => {
|
||||
return (
|
||||
<Slider
|
||||
name="memory"
|
||||
aria-label="Memory"
|
||||
defaultValue={4096}
|
||||
valueLabelDisplay="auto"
|
||||
shiftStep={1024}
|
||||
step={1024}
|
||||
marks
|
||||
min={1024}
|
||||
max={32628}
|
||||
value={memory}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default MemorySlider;
|
110
src/renderer/components/MinecraftBackground.tsx
Normal file
110
src/renderer/components/MinecraftBackground.tsx
Normal file
@ -0,0 +1,110 @@
|
||||
import { Box } from '@mui/material';
|
||||
import heart from '../../../assets/images/heart.svg';
|
||||
|
||||
export default function MinecraftBackground() {
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
opacity: 0.25,
|
||||
overflow: 'hidden',
|
||||
zIndex: -10,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
bottom: 0,
|
||||
right: 0,
|
||||
gap: '1vw',
|
||||
display: 'flex',
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
rotate: '-20deg',
|
||||
paddingTop: '30vw',
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={heart}
|
||||
draggable={false}
|
||||
style={{
|
||||
width: '20vw',
|
||||
height: '20vw',
|
||||
rotate: '-20deg',
|
||||
userSelect: 'none',
|
||||
}}
|
||||
/>
|
||||
<img
|
||||
src={heart}
|
||||
draggable={false}
|
||||
style={{
|
||||
width: '20vw',
|
||||
height: '20vw',
|
||||
paddingBottom: '5vw',
|
||||
userSelect: 'none',
|
||||
}}
|
||||
/>
|
||||
<img
|
||||
src={heart}
|
||||
draggable={false}
|
||||
style={{
|
||||
width: '20vw',
|
||||
height: '20vw',
|
||||
rotate: '20deg',
|
||||
userSelect: 'none',
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
gap: '1vw',
|
||||
display: 'flex',
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
rotate: '160deg',
|
||||
paddingTop: '80vw',
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={heart}
|
||||
draggable={false}
|
||||
style={{
|
||||
width: '20vw',
|
||||
height: '20vw',
|
||||
rotate: '-20deg',
|
||||
userSelect: 'none',
|
||||
}}
|
||||
/>
|
||||
<img
|
||||
src={heart}
|
||||
draggable={false}
|
||||
style={{
|
||||
width: '20vw',
|
||||
height: '20vw',
|
||||
paddingBottom: '5vw',
|
||||
userSelect: 'none',
|
||||
}}
|
||||
/>
|
||||
<img
|
||||
src={heart}
|
||||
draggable={false}
|
||||
style={{
|
||||
width: '20vw',
|
||||
height: '20vw',
|
||||
rotate: '20deg',
|
||||
userSelect: 'none',
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
63
src/renderer/components/Notifier.tsx
Normal file
63
src/renderer/components/Notifier.tsx
Normal file
@ -0,0 +1,63 @@
|
||||
import { Alert, Box, Snackbar, Button } from '@mui/material';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export const Notifier = () => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [severity, setSeverity] = useState<
|
||||
'error' | 'warning' | 'info' | 'success'
|
||||
>('info');
|
||||
const [hasUpdateAvailable, setHasUpdateAvailable] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Слушаем событие о наличии обновления
|
||||
window.electron.ipcRenderer.on('update-available', () => {
|
||||
setMessage('Доступно новое обновление');
|
||||
setSeverity('info');
|
||||
setHasUpdateAvailable(true);
|
||||
setOpen(true);
|
||||
});
|
||||
|
||||
return () => {
|
||||
// Отписываемся от события при размонтировании
|
||||
window.electron.ipcRenderer.removeAllListeners('update-available');
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleClose = () => {
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleUpdate = () => {
|
||||
window.electron.ipcRenderer.invoke('install-update');
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Snackbar
|
||||
open={open}
|
||||
autoHideDuration={hasUpdateAvailable ? null : 6000}
|
||||
onClose={handleClose}
|
||||
>
|
||||
<Alert
|
||||
severity={severity}
|
||||
action={
|
||||
hasUpdateAvailable && (
|
||||
<>
|
||||
<Button color="primary" size="small" onClick={handleUpdate}>
|
||||
Обновить сейчас
|
||||
</Button>
|
||||
<Button color="secondary" size="small" onClick={handleClose}>
|
||||
Позже
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
>
|
||||
{message}
|
||||
</Alert>
|
||||
</Snackbar>
|
||||
</Box>
|
||||
);
|
||||
};
|
372
src/renderer/components/PlayerInventory.tsx
Normal file
372
src/renderer/components/PlayerInventory.tsx
Normal file
@ -0,0 +1,372 @@
|
||||
// src/renderer/components/PlayerInventory.tsx
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
Grid,
|
||||
Card,
|
||||
CardMedia,
|
||||
CardContent,
|
||||
Button,
|
||||
CircularProgress,
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogActions,
|
||||
TextField,
|
||||
Alert,
|
||||
} from '@mui/material';
|
||||
import {
|
||||
RequestPlayerInventory,
|
||||
getPlayerInventory,
|
||||
sellItem,
|
||||
PlayerInventoryItem,
|
||||
} from '../api';
|
||||
|
||||
interface PlayerInventoryProps {
|
||||
username: string;
|
||||
serverIp: string;
|
||||
onSellSuccess?: () => void; // Callback для обновления маркетплейса после продажи
|
||||
}
|
||||
|
||||
export default function PlayerInventory({
|
||||
username,
|
||||
serverIp,
|
||||
onSellSuccess,
|
||||
}: PlayerInventoryProps) {
|
||||
const [loading, setLoading] = useState<boolean>(false);
|
||||
const [inventoryItems, setInventoryItems] = useState<PlayerInventoryItem[]>(
|
||||
[],
|
||||
);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [sellDialogOpen, setSellDialogOpen] = useState<boolean>(false);
|
||||
const [selectedItem, setSelectedItem] = useState<PlayerInventoryItem | null>(
|
||||
null,
|
||||
);
|
||||
const [price, setPrice] = useState<number>(0);
|
||||
const [amount, setAmount] = useState<number>(1);
|
||||
const [sellLoading, setSellLoading] = useState<boolean>(false);
|
||||
const [sellError, setSellError] = useState<string | null>(null);
|
||||
|
||||
// Функция для запроса инвентаря игрока
|
||||
const fetchPlayerInventory = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
// Сначала делаем запрос на получение идентификатора запроса инвентаря
|
||||
const inventoryRequest = await RequestPlayerInventory(serverIp, username);
|
||||
const requestId = inventoryRequest.request_id;
|
||||
|
||||
// Затем начинаем опрашивать API для получения результата
|
||||
let inventoryData = null;
|
||||
let attempts = 0;
|
||||
const maxAttempts = 10; // Максимальное количество попыток
|
||||
|
||||
while (!inventoryData && attempts < maxAttempts) {
|
||||
attempts++;
|
||||
|
||||
try {
|
||||
// Пауза перед следующим запросом
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
|
||||
// Запрашиваем состояние инвентаря
|
||||
const response = await getPlayerInventory(requestId);
|
||||
|
||||
// Если инвентарь загружен, сохраняем его
|
||||
if (response.status === 'completed') {
|
||||
inventoryData = response.result.inventory_data;
|
||||
break;
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Ожидание завершения запроса инвентаря...');
|
||||
}
|
||||
}
|
||||
|
||||
if (inventoryData) {
|
||||
setInventoryItems(inventoryData);
|
||||
} else {
|
||||
setError('Не удалось получить инвентарь. Попробуйте еще раз.');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Ошибка при получении инвентаря:', e);
|
||||
setError('Произошла ошибка при загрузке инвентаря.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Открываем диалог для продажи предмета
|
||||
const handleOpenSellDialog = (item: PlayerInventoryItem) => {
|
||||
setSelectedItem(item);
|
||||
setAmount(1);
|
||||
setPrice(0);
|
||||
setSellError(null);
|
||||
setSellDialogOpen(true);
|
||||
};
|
||||
|
||||
// Закрываем диалог
|
||||
const handleCloseSellDialog = () => {
|
||||
setSellDialogOpen(false);
|
||||
setSelectedItem(null);
|
||||
};
|
||||
|
||||
// Выставляем предмет на продажу
|
||||
const handleSellItem = async () => {
|
||||
if (!selectedItem) return;
|
||||
|
||||
try {
|
||||
setSellLoading(true);
|
||||
setSellError(null);
|
||||
|
||||
// Проверяем валидность введенных данных
|
||||
if (price <= 0) {
|
||||
setSellError('Цена должна быть больше 0');
|
||||
return;
|
||||
}
|
||||
|
||||
if (amount <= 0 || amount > selectedItem.amount) {
|
||||
setSellError(`Количество должно быть от 1 до ${selectedItem.amount}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Отправляем запрос на продажу
|
||||
const result = await sellItem(
|
||||
username,
|
||||
selectedItem.slot,
|
||||
amount,
|
||||
price,
|
||||
serverIp,
|
||||
);
|
||||
|
||||
// Проверяем статус операции
|
||||
if (result.status === 'pending') {
|
||||
// Закрываем диалог и обновляем инвентарь
|
||||
handleCloseSellDialog();
|
||||
|
||||
// Показываем уведомление о том, что операция обрабатывается
|
||||
// setNotification({ // Assuming setNotification is available in the context
|
||||
// open: true,
|
||||
// message: 'Предмет выставляется на продажу. Это может занять некоторое время.',
|
||||
// type: 'info'
|
||||
// });
|
||||
|
||||
// Через 5 секунд обновляем инвентарь
|
||||
setTimeout(() => {
|
||||
fetchPlayerInventory();
|
||||
|
||||
// Вызываем callback для обновления маркетплейса
|
||||
if (onSellSuccess) {
|
||||
onSellSuccess();
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Ошибка при продаже предмета:', e);
|
||||
setSellError('Произошла ошибка при продаже предмета.');
|
||||
} finally {
|
||||
setSellLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Загружаем инвентарь при монтировании компонента
|
||||
useEffect(() => {
|
||||
fetchPlayerInventory();
|
||||
}, [username, serverIp]);
|
||||
|
||||
// Получаем отображаемое имя предмета
|
||||
const getItemDisplayName = (material: string) => {
|
||||
return material
|
||||
.replace(/_/g, ' ')
|
||||
.toLowerCase()
|
||||
.replace(/\b\w/g, (l) => l.toUpperCase());
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ mt: '1vw' }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
gap: '1vw',
|
||||
alignItems: 'center',
|
||||
mb: '2vw',
|
||||
}}
|
||||
>
|
||||
<Typography variant="h5" color="white">
|
||||
Ваш инвентарь
|
||||
</Typography>
|
||||
<Button
|
||||
variant="outlined"
|
||||
onClick={fetchPlayerInventory}
|
||||
disabled={loading}
|
||||
sx={{
|
||||
borderRadius: '20px',
|
||||
p: '10px 25px',
|
||||
color: 'white',
|
||||
borderColor: 'rgba(255, 77, 77, 1)',
|
||||
'&:hover': {
|
||||
backgroundColor: 'rgba(255, 77, 77, 1)',
|
||||
borderColor: 'rgba(255, 77, 77, 1)',
|
||||
},
|
||||
fontFamily: 'Benzin-Bold',
|
||||
fontSize: '1vw',
|
||||
}}
|
||||
>
|
||||
Обновить
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 2 }}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', my: 4 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
) : (
|
||||
<>
|
||||
{inventoryItems.length === 0 ? (
|
||||
<Typography
|
||||
variant="body1"
|
||||
color="white"
|
||||
sx={{ textAlign: 'center', my: 4 }}
|
||||
>
|
||||
Ваш инвентарь пуст или не удалось загрузить предметы.
|
||||
</Typography>
|
||||
) : (
|
||||
<Grid container spacing={2}>
|
||||
{inventoryItems.map((item) =>
|
||||
item.material !== 'AIR' && item.amount > 0 ? (
|
||||
<Grid item xs={6} sm={4} md={3} lg={2} key={item.slot}>
|
||||
<Card
|
||||
sx={{
|
||||
bgcolor: 'rgba(255, 255, 255, 0.05)',
|
||||
cursor: 'pointer',
|
||||
transition: 'transform 0.2s',
|
||||
'&:hover': { transform: 'scale(1.03)' },
|
||||
borderRadius: '1vw',
|
||||
}}
|
||||
onClick={() => handleOpenSellDialog(item)}
|
||||
>
|
||||
<CardMedia
|
||||
component="img"
|
||||
sx={{
|
||||
minWidth: '10vw',
|
||||
minHeight: '10vw',
|
||||
maxHeight: '10vw',
|
||||
objectFit: 'contain',
|
||||
bgcolor: 'white',
|
||||
p: '1vw',
|
||||
imageRendering: 'pixelated',
|
||||
}}
|
||||
image={`/minecraft/${item.material.toLowerCase()}.png`}
|
||||
alt={item.material}
|
||||
/>
|
||||
<CardContent sx={{ p: 1 }}>
|
||||
<Box sx={{ display: 'flex', gap: '1vw', justifyContent: 'space-between' }}>
|
||||
<Typography variant="body2" color="white" noWrap>
|
||||
{getItemDisplayName(item.material)}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="white">
|
||||
{item.amount > 1 ? `x${item.amount}` : ''}
|
||||
</Typography>
|
||||
</Box>
|
||||
{Object.keys(item.enchants || {}).length > 0 && (
|
||||
<Typography
|
||||
variant="caption"
|
||||
color="secondary"
|
||||
sx={{ display: 'block' }}
|
||||
>
|
||||
Зачарования: {Object.keys(item.enchants).length}
|
||||
</Typography>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Grid>
|
||||
) : null,
|
||||
)}
|
||||
</Grid>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Диалог для продажи предмета */}
|
||||
<Dialog open={sellDialogOpen} onClose={handleCloseSellDialog}>
|
||||
<DialogTitle>Продать предмет</DialogTitle>
|
||||
<DialogContent>
|
||||
{selectedItem && (
|
||||
<Box sx={{ mt: 1 }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
|
||||
<CardMedia
|
||||
component="img"
|
||||
sx={{
|
||||
width: 50,
|
||||
height: 50,
|
||||
objectFit: 'contain',
|
||||
mr: 2,
|
||||
}}
|
||||
image={`/items/${selectedItem.material.toLowerCase()}.png`}
|
||||
alt={selectedItem.material}
|
||||
/>
|
||||
<Typography variant="h6">
|
||||
{getItemDisplayName(selectedItem.material)}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Typography variant="body2" gutterBottom>
|
||||
Всего доступно: {selectedItem.amount}
|
||||
</Typography>
|
||||
|
||||
<TextField
|
||||
label="Количество"
|
||||
type="number"
|
||||
fullWidth
|
||||
margin="dense"
|
||||
value={amount}
|
||||
onChange={(e) =>
|
||||
setAmount(
|
||||
Math.min(
|
||||
parseInt(e.target.value) || 0,
|
||||
selectedItem.amount,
|
||||
),
|
||||
)
|
||||
}
|
||||
inputProps={{ min: 1, max: selectedItem.amount }}
|
||||
/>
|
||||
|
||||
<TextField
|
||||
label="Цена (за всё)"
|
||||
type="number"
|
||||
fullWidth
|
||||
margin="dense"
|
||||
value={price}
|
||||
onChange={(e) => setPrice(parseInt(e.target.value) || 0)}
|
||||
inputProps={{ min: 1 }}
|
||||
/>
|
||||
|
||||
{sellError && (
|
||||
<Alert severity="error" sx={{ mt: 2 }}>
|
||||
{sellError}
|
||||
</Alert>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={handleCloseSellDialog}>Отмена</Button>
|
||||
<Button
|
||||
onClick={handleSellItem}
|
||||
variant="contained"
|
||||
color="primary"
|
||||
disabled={sellLoading}
|
||||
>
|
||||
{sellLoading ? <CircularProgress size={24} /> : 'Продать'}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</Box>
|
||||
);
|
||||
}
|
118
src/renderer/components/ServerStatus/ServerStatus.tsx
Normal file
118
src/renderer/components/ServerStatus/ServerStatus.tsx
Normal file
@ -0,0 +1,118 @@
|
||||
import { Box, Typography, CircularProgress, Avatar } from '@mui/material';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
interface ServerStatusProps {
|
||||
serverIp: string;
|
||||
serverPort?: number;
|
||||
refreshInterval?: number; // Интервал обновления в миллисекундах
|
||||
}
|
||||
|
||||
const ServerStatus = ({
|
||||
serverIp,
|
||||
serverPort,
|
||||
refreshInterval = 60000, // По умолчанию обновление раз в минуту
|
||||
}: ServerStatusProps) => {
|
||||
const [serverStatus, setServerStatus] = useState<{
|
||||
online: number;
|
||||
max: number;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
icon: string | null;
|
||||
motd: string;
|
||||
}>({
|
||||
online: 0,
|
||||
max: 0,
|
||||
loading: true,
|
||||
error: null,
|
||||
icon: null,
|
||||
motd: '',
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
// Функция для получения статуса сервера
|
||||
const fetchServerStatus = async () => {
|
||||
try {
|
||||
setServerStatus((prev) => ({ ...prev, loading: true, error: null }));
|
||||
console.log('Отправляем запрос на сервер с параметрами:', {
|
||||
host: serverIp,
|
||||
port: serverPort || 25565,
|
||||
});
|
||||
|
||||
// Проверяем, что serverIp имеет значение
|
||||
if (!serverIp) {
|
||||
throw new Error('Адрес сервера не указан');
|
||||
}
|
||||
|
||||
const result = await window.electron.ipcRenderer.invoke(
|
||||
'get-server-status',
|
||||
{
|
||||
host: serverIp,
|
||||
port: serverPort || 25565,
|
||||
},
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
setServerStatus({
|
||||
online: result.online,
|
||||
max: result.max,
|
||||
loading: false,
|
||||
error: null,
|
||||
icon: result.icon,
|
||||
motd: result.motd || serverIp,
|
||||
});
|
||||
} else {
|
||||
setServerStatus({
|
||||
online: 0,
|
||||
max: 0,
|
||||
loading: false,
|
||||
error: result.error || 'Неизвестная ошибка',
|
||||
icon: null,
|
||||
motd: '',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при получении статуса сервера:', error);
|
||||
setServerStatus((prev) => ({
|
||||
...prev,
|
||||
loading: false,
|
||||
error: 'Ошибка при получении статуса сервера',
|
||||
icon: null,
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
// Загрузка при первом рендере
|
||||
fetchServerStatus();
|
||||
|
||||
// Периодическое обновление
|
||||
const interval = setInterval(fetchServerStatus, refreshInterval);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [serverIp, serverPort, refreshInterval]);
|
||||
|
||||
return (
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||
{/* Отображаем иконку сервера или иконку по умолчанию */}
|
||||
{serverStatus.icon ? (
|
||||
<Avatar
|
||||
src={serverStatus.icon}
|
||||
alt={serverStatus.motd || 'Minecraft сервер'}
|
||||
sx={{ width: '2em', height: '2em' }}
|
||||
/>
|
||||
) : (
|
||||
<Avatar sx={{ width: '2em', height: '2em', bgcolor: 'primary.main' }}>
|
||||
?
|
||||
</Avatar>
|
||||
)}
|
||||
{serverStatus.error ? (
|
||||
<Typography color="error">Ошибка загрузки</Typography>
|
||||
) : (
|
||||
<Typography sx={{ fontWeight: 'bold' }}>
|
||||
{serverStatus.online} / {serverStatus.max} игроков
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default ServerStatus;
|
92
src/renderer/components/Settings/SettingsModal.tsx
Normal file
92
src/renderer/components/Settings/SettingsModal.tsx
Normal file
@ -0,0 +1,92 @@
|
||||
import { Box, Typography, Button, Modal } from '@mui/material';
|
||||
import React from 'react';
|
||||
import MemorySlider from '../Login/MemorySlider';
|
||||
import FilesSelector from '../FilesSelector';
|
||||
|
||||
interface SettingsModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
config: {
|
||||
memory: number;
|
||||
preserveFiles: string[];
|
||||
};
|
||||
onConfigChange: (newConfig: {
|
||||
memory: number;
|
||||
preserveFiles: string[];
|
||||
}) => void;
|
||||
packName: string;
|
||||
onSave: () => void;
|
||||
}
|
||||
|
||||
const SettingsModal = ({
|
||||
open,
|
||||
onClose,
|
||||
config,
|
||||
onConfigChange,
|
||||
packName,
|
||||
onSave,
|
||||
}: SettingsModalProps) => {
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
aria-labelledby="modal-modal-title"
|
||||
aria-describedby="modal-modal-description"
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
top: '50%',
|
||||
left: '50%',
|
||||
transform: 'translate(-50%, -50%)',
|
||||
width: 400,
|
||||
background:
|
||||
'linear-gradient(-242.94deg, #000000 39.07%, #3b4187 184.73%)',
|
||||
border: '2px solid #000',
|
||||
boxShadow: 24,
|
||||
p: 4,
|
||||
borderRadius: '3vw',
|
||||
gap: '1vh',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}}
|
||||
>
|
||||
<Typography id="modal-modal-title" variant="body1" component="h2">
|
||||
Файлы и папки, которые будут сохранены после переустановки сборки
|
||||
</Typography>
|
||||
<FilesSelector
|
||||
packName={packName}
|
||||
initialSelected={config.preserveFiles}
|
||||
onSelectionChange={(selected) => {
|
||||
onConfigChange({ ...config, preserveFiles: selected });
|
||||
}}
|
||||
/>
|
||||
<Typography variant="body1" sx={{ color: 'white' }}>
|
||||
Оперативная память выделенная для Minecraft
|
||||
</Typography>
|
||||
<MemorySlider
|
||||
memory={config.memory}
|
||||
onChange={(e, value) => {
|
||||
onConfigChange({ ...config, memory: value as number });
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="success"
|
||||
onClick={() => {
|
||||
onSave();
|
||||
onClose();
|
||||
}}
|
||||
sx={{
|
||||
borderRadius: '3vw',
|
||||
fontFamily: 'Benzin-Bold',
|
||||
}}
|
||||
>
|
||||
Сохранить
|
||||
</Button>
|
||||
</Box>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default SettingsModal;
|
75
src/renderer/components/SkinViewer.tsx
Normal file
75
src/renderer/components/SkinViewer.tsx
Normal file
@ -0,0 +1,75 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
interface SkinViewerProps {
|
||||
width?: number;
|
||||
height?: number;
|
||||
skinUrl?: string;
|
||||
capeUrl?: string;
|
||||
walkingSpeed?: number;
|
||||
autoRotate?: boolean;
|
||||
}
|
||||
|
||||
export default function SkinViewer({
|
||||
width = 300,
|
||||
height = 400,
|
||||
skinUrl,
|
||||
capeUrl,
|
||||
walkingSpeed = 0.5,
|
||||
autoRotate = true,
|
||||
}: SkinViewerProps) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const viewerRef = useRef<any>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!canvasRef.current) return;
|
||||
|
||||
// Используем динамический импорт для обхода проблемы ESM/CommonJS
|
||||
const initSkinViewer = async () => {
|
||||
try {
|
||||
const skinview3d = await import('skinview3d');
|
||||
|
||||
// Создаем просмотрщик скина по документации
|
||||
const viewer = new skinview3d.SkinViewer({
|
||||
canvas: canvasRef.current,
|
||||
width,
|
||||
height,
|
||||
skin:
|
||||
skinUrl ||
|
||||
'https://static.planetminecraft.com/files/resource_media/skin/original-steve-15053860.png',
|
||||
model: 'auto-detect',
|
||||
cape: capeUrl || undefined,
|
||||
});
|
||||
|
||||
// Настраиваем вращение
|
||||
viewer.autoRotate = autoRotate;
|
||||
|
||||
// Настраиваем анимацию ходьбы
|
||||
viewer.animation = new skinview3d.WalkingAnimation();
|
||||
viewer.animation.speed = walkingSpeed;
|
||||
|
||||
// Сохраняем экземпляр для очистки
|
||||
viewerRef.current = viewer;
|
||||
} catch (error) {
|
||||
console.error('Ошибка при инициализации skinview3d:', error);
|
||||
}
|
||||
};
|
||||
|
||||
initSkinViewer();
|
||||
|
||||
// Очистка при размонтировании
|
||||
return () => {
|
||||
if (viewerRef.current) {
|
||||
viewerRef.current.dispose();
|
||||
}
|
||||
};
|
||||
}, [width, height, skinUrl, capeUrl, walkingSpeed, autoRotate]);
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={width}
|
||||
height={height}
|
||||
style={{ display: 'block' }}
|
||||
/>
|
||||
);
|
||||
}
|
382
src/renderer/components/TopBar.tsx
Normal file
382
src/renderer/components/TopBar.tsx
Normal file
@ -0,0 +1,382 @@
|
||||
import { Box, Button, Tab, Tabs, Typography } from '@mui/material';
|
||||
import CloseRoundedIcon from '@mui/icons-material/CloseRounded';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import ArrowBackRoundedIcon from '@mui/icons-material/ArrowBackRounded';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Tooltip } from '@mui/material';
|
||||
import { fetchCoins } from '../api';
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
electron: {
|
||||
ipcRenderer: {
|
||||
invoke(channel: string, ...args: unknown[]): Promise<any>;
|
||||
on(channel: string, func: (...args: unknown[]) => void): void;
|
||||
removeAllListeners(channel: string): void;
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Определяем пропсы
|
||||
interface TopBarProps {
|
||||
onRegister?: () => void; // Опционально, если нужен обработчик регистрации
|
||||
username?: string;
|
||||
}
|
||||
|
||||
export default function TopBar({ onRegister, username }: TopBarProps) {
|
||||
// Получаем текущий путь
|
||||
const location = useLocation();
|
||||
const isLoginPage = location.pathname === '/login';
|
||||
const isLaunchPage = location.pathname.startsWith('/launch');
|
||||
const isVersionsExplorerPage = location.pathname.startsWith('/');
|
||||
const isRegistrationPage = location.pathname === '/registration';
|
||||
const navigate = useNavigate();
|
||||
const [coins, setCoins] = useState<number>(0);
|
||||
const [value, setValue] = useState(0);
|
||||
const [activePage, setActivePage] = useState('versions');
|
||||
|
||||
const handleChange = (event: React.SyntheticEvent, newValue: number) => {
|
||||
setValue(newValue);
|
||||
if (newValue === 0) {
|
||||
navigate('/');
|
||||
} else if (newValue === 1) {
|
||||
navigate('/profile');
|
||||
} else if (newValue === 2) {
|
||||
navigate('/shop');
|
||||
} else if (newValue === 3) {
|
||||
navigate('/marketplace');
|
||||
}
|
||||
};
|
||||
|
||||
const handleLaunchPage = () => {
|
||||
navigate('/');
|
||||
};
|
||||
|
||||
const getPageTitle = () => {
|
||||
if (isLoginPage) {
|
||||
return 'Вход';
|
||||
}
|
||||
if (isLaunchPage) {
|
||||
return 'Запуск';
|
||||
}
|
||||
if (isVersionsExplorerPage) {
|
||||
if (activePage === 'versions') {
|
||||
return 'Версии';
|
||||
}
|
||||
if (activePage === 'profile') {
|
||||
return 'Профиль';
|
||||
}
|
||||
if (activePage === 'shop') {
|
||||
return 'Магазин';
|
||||
}
|
||||
if (activePage === 'marketplace') {
|
||||
return 'Рынок';
|
||||
}
|
||||
}
|
||||
return 'Неизвестная страница';
|
||||
};
|
||||
|
||||
// Функция для получения количества монет
|
||||
const fetchCoinsData = async () => {
|
||||
if (!username) return;
|
||||
|
||||
try {
|
||||
const coinsData = await fetchCoins(username);
|
||||
setCoins(coinsData.coins);
|
||||
} catch (error) {
|
||||
console.error('Ошибка при получении количества монет:', error);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (username) {
|
||||
fetchCoinsData();
|
||||
|
||||
// Создаем интервалы для периодического обновления данных
|
||||
const coinsInterval = setInterval(fetchCoinsData, 60000);
|
||||
|
||||
return () => {
|
||||
clearInterval(coinsInterval);
|
||||
};
|
||||
}
|
||||
}, [username]);
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
height: '7vh',
|
||||
zIndex: 1000,
|
||||
width: '100%',
|
||||
WebkitAppRegion: 'drag',
|
||||
overflow: 'hidden',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
// marginLeft: '1em',
|
||||
// marginRight: '1em',
|
||||
}}
|
||||
>
|
||||
{/* Левая часть */}
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
WebkitAppRegion: 'no-drag',
|
||||
gap: '2vw',
|
||||
alignItems: 'center',
|
||||
marginLeft: '1vw',
|
||||
}}
|
||||
>
|
||||
{(isLaunchPage || isRegistrationPage) && (
|
||||
<Button
|
||||
variant="outlined"
|
||||
onClick={() => handleLaunchPage()}
|
||||
sx={{
|
||||
width: '3em',
|
||||
height: '3em',
|
||||
borderRadius: '50%',
|
||||
border: 'unset',
|
||||
color: 'white',
|
||||
minWidth: 'unset',
|
||||
minHeight: 'unset',
|
||||
}}
|
||||
>
|
||||
<ArrowBackRoundedIcon />
|
||||
</Button>
|
||||
)}
|
||||
{!isLaunchPage && !isRegistrationPage && !isLoginPage && (
|
||||
<Box
|
||||
sx={{
|
||||
borderBottom: 1,
|
||||
borderColor: 'transparent',
|
||||
'& .MuiTabs-indicator': {
|
||||
backgroundColor: 'rgba(255, 77, 77, 1)',
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tabs
|
||||
value={value}
|
||||
onChange={handleChange}
|
||||
aria-label="basic tabs example"
|
||||
disableRipple={true}
|
||||
>
|
||||
<Tab
|
||||
label="Версии"
|
||||
disableRipple={true}
|
||||
onClick={() => {
|
||||
setActivePage('versions');
|
||||
}}
|
||||
sx={{
|
||||
color: 'white',
|
||||
fontFamily: 'Benzin-Bold',
|
||||
fontSize: '0.7em',
|
||||
'&.Mui-selected': {
|
||||
color: 'rgba(255, 77, 77, 1)',
|
||||
},
|
||||
'&:hover': {
|
||||
color: 'rgb(177, 52, 52)',
|
||||
},
|
||||
transition: 'all 0.3s ease',
|
||||
}}
|
||||
/>
|
||||
<Tab
|
||||
label="Профиль"
|
||||
disableRipple={true}
|
||||
onClick={() => {
|
||||
setActivePage('profile');
|
||||
}}
|
||||
sx={{
|
||||
color: 'white',
|
||||
fontFamily: 'Benzin-Bold',
|
||||
fontSize: '0.7em',
|
||||
'&.Mui-selected': {
|
||||
color: 'rgba(255, 77, 77, 1)',
|
||||
},
|
||||
'&:hover': {
|
||||
color: 'rgb(177, 52, 52)',
|
||||
},
|
||||
transition: 'all 0.3s ease',
|
||||
}}
|
||||
/>
|
||||
<Tab
|
||||
label="Магазин"
|
||||
disableRipple={true}
|
||||
onClick={() => {
|
||||
setActivePage('shop');
|
||||
}}
|
||||
sx={{
|
||||
color: 'white',
|
||||
fontFamily: 'Benzin-Bold',
|
||||
fontSize: '0.7em',
|
||||
'&.Mui-selected': {
|
||||
color: 'rgba(255, 77, 77, 1)',
|
||||
},
|
||||
'&:hover': {
|
||||
color: 'rgb(177, 52, 52)',
|
||||
},
|
||||
transition: 'all 0.3s ease',
|
||||
}}
|
||||
/>
|
||||
<Tab
|
||||
label="Рынок"
|
||||
disableRipple={true}
|
||||
onClick={() => {
|
||||
setActivePage('marketplace');
|
||||
}}
|
||||
sx={{
|
||||
color: 'white',
|
||||
fontFamily: 'Benzin-Bold',
|
||||
fontSize: '0.7em',
|
||||
'&.Mui-selected': {
|
||||
color: 'rgba(255, 77, 77, 1)',
|
||||
},
|
||||
'&:hover': {
|
||||
color: 'rgb(177, 52, 52)',
|
||||
},
|
||||
transition: 'all 0.3s ease',
|
||||
}}
|
||||
/>
|
||||
</Tabs>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
{/* Центр */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
left: '50%',
|
||||
transform: 'translateX(-50%)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
flexGrow: 1,
|
||||
WebkitAppRegion: 'drag',
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant="h6"
|
||||
sx={{ color: 'white', fontFamily: 'Benzin-Bold' }}
|
||||
>
|
||||
{getPageTitle()}
|
||||
</Typography>
|
||||
</Box>
|
||||
{/* Правая часть со всеми кнопками */}
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
WebkitAppRegion: 'no-drag',
|
||||
gap: '1vw',
|
||||
alignItems: 'center',
|
||||
marginRight: '1vw',
|
||||
}}
|
||||
>
|
||||
{/* Кнопка регистрации, если на странице логина */}
|
||||
{username && (
|
||||
<Tooltip
|
||||
title="Попы — внутриигровая валюта, начисляемая за время игры на серверах."
|
||||
arrow
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '8px',
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.2)',
|
||||
borderRadius: '16px',
|
||||
padding: '6px 12px',
|
||||
border: '1px solid rgba(255, 255, 255, 0.1)',
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
width: '24px',
|
||||
height: '24px',
|
||||
}}
|
||||
>
|
||||
<Typography sx={{ color: '#2bff00ff' }}>P</Typography>
|
||||
</Box>
|
||||
<Typography
|
||||
variant="body1"
|
||||
sx={{
|
||||
color: 'white',
|
||||
fontWeight: 'bold',
|
||||
fontSize: '16px',
|
||||
lineHeight: 1,
|
||||
}}
|
||||
>
|
||||
{coins}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Tooltip>
|
||||
)}
|
||||
{isLoginPage && (
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="primary"
|
||||
onClick={() => navigate('/registration')}
|
||||
sx={{
|
||||
width: '10em',
|
||||
height: '3em',
|
||||
borderRadius: '1.5vw',
|
||||
color: 'white',
|
||||
backgroundImage: 'linear-gradient(to right, #7BB8FF, #FFB7ED)',
|
||||
border: 'unset',
|
||||
'&:hover': {
|
||||
backgroundImage: 'linear-gradient(to right, #6AA8EE, #EEA7DD)',
|
||||
},
|
||||
boxShadow: '0.5em 0.5em 0.5em 0px #00000040 inset',
|
||||
}}
|
||||
>
|
||||
Регистрация
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Кнопки управления окном */}
|
||||
<Button
|
||||
onClick={() => {
|
||||
window.electron.ipcRenderer.invoke('minimize-app');
|
||||
}}
|
||||
sx={{
|
||||
minWidth: 'unset',
|
||||
minHeight: 'unset',
|
||||
width: '3em',
|
||||
height: '3em',
|
||||
borderRadius: '50%',
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
className="MuiSvgIcon-root MuiSvgIcon-fontSizeMedium"
|
||||
focusable="false"
|
||||
aria-hidden="true"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
d="M 7 19 h 10 c 0.55 0 1 0.45 1 1 s -0.45 1 -1 1 H 7 c -0.55 0 -1 -0.45 -1 -1 s 0.45 -1 1 -1"
|
||||
fill="white"
|
||||
></path>
|
||||
</svg>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
window.electron.ipcRenderer.invoke('close-app');
|
||||
}}
|
||||
sx={{
|
||||
minWidth: 'unset',
|
||||
minHeight: 'unset',
|
||||
width: '3em',
|
||||
height: '3em',
|
||||
borderRadius: '50%',
|
||||
}}
|
||||
>
|
||||
<CloseRoundedIcon sx={{ color: 'white' }} />
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
22
src/renderer/components/popa-popa.tsx
Normal file
22
src/renderer/components/popa-popa.tsx
Normal file
@ -0,0 +1,22 @@
|
||||
import { Typography } from '@mui/material';
|
||||
|
||||
import { Box } from '@mui/material';
|
||||
|
||||
export default function PopaPopa() {
|
||||
return (
|
||||
<Box sx={{ display: 'flex' }}>
|
||||
<Typography variant="h3">POPA</Typography>
|
||||
<Typography variant="h3">-</Typography>
|
||||
<Typography
|
||||
variant="h3"
|
||||
sx={{
|
||||
background: '-webkit-linear-gradient(200.96deg, #88BCFF, #FD71FF)',
|
||||
WebkitBackgroundClip: 'text',
|
||||
WebkitTextFillColor: 'transparent',
|
||||
}}
|
||||
>
|
||||
POPA
|
||||
</Typography>
|
||||
</Box>
|
||||
);
|
||||
}
|
94
src/renderer/hooks/useAuth.ts
Normal file
94
src/renderer/hooks/useAuth.ts
Normal file
@ -0,0 +1,94 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
interface AuthSession {
|
||||
accessToken: string;
|
||||
clientToken: string;
|
||||
selectedProfile: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
export default function useAuth() {
|
||||
const [status, setStatus] = useState('idle');
|
||||
|
||||
// Проверка валидности токена
|
||||
const validateSession = async (accessToken: string): Promise<boolean> => {
|
||||
try {
|
||||
setStatus('validating');
|
||||
const response = await window.electron.ipcRenderer.invoke(
|
||||
'validate-token',
|
||||
accessToken,
|
||||
);
|
||||
setStatus('idle');
|
||||
return response.valid;
|
||||
} catch (error) {
|
||||
console.error('Ошибка при валидации токена:', error);
|
||||
setStatus('error');
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Обновление токена
|
||||
const refreshSession = async (
|
||||
accessToken: string,
|
||||
clientToken: string,
|
||||
): Promise<AuthSession | null> => {
|
||||
try {
|
||||
setStatus('refreshing');
|
||||
const response = await window.electron.ipcRenderer.invoke(
|
||||
'refresh-token',
|
||||
{ accessToken, clientToken },
|
||||
);
|
||||
setStatus('idle');
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error('Ошибка при обновлении токена:', error);
|
||||
setStatus('error');
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// Аутентификация в Ely.by
|
||||
const authenticateWithElyBy = async (
|
||||
username: string,
|
||||
password: string,
|
||||
saveConfigFunc: Function,
|
||||
): Promise<AuthSession | null> => {
|
||||
try {
|
||||
setStatus('authenticating');
|
||||
const response = await window.electron.ipcRenderer.invoke(
|
||||
'authenticate',
|
||||
{ username, password },
|
||||
);
|
||||
|
||||
if (response && response.accessToken) {
|
||||
// Правильно сохраняем данные в конфигурации
|
||||
saveConfigFunc({
|
||||
username: response.selectedProfile.name, // Имя игрока как строка
|
||||
uuid: response.selectedProfile.id,
|
||||
accessToken: response.accessToken,
|
||||
clientToken: response.clientToken,
|
||||
memory: 4096, // Сохраняем значение по умолчанию или из предыдущей конфигурации
|
||||
});
|
||||
|
||||
setStatus('authenticated');
|
||||
return response;
|
||||
}
|
||||
|
||||
setStatus('error');
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Ошибка при аутентификации:', error);
|
||||
setStatus('error');
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
status,
|
||||
validateSession,
|
||||
refreshSession,
|
||||
authenticateWithElyBy,
|
||||
};
|
||||
}
|
61
src/renderer/hooks/useConfig.ts
Normal file
61
src/renderer/hooks/useConfig.ts
Normal file
@ -0,0 +1,61 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
// Добавляем определение типа Config
|
||||
interface Config {
|
||||
username: string;
|
||||
password: string;
|
||||
memory: number;
|
||||
comfortVersion: string;
|
||||
accessToken: string;
|
||||
clientToken: string;
|
||||
uuid?: string; // Добавляем uuid, который используется для авторизации
|
||||
}
|
||||
|
||||
const useConfig = () => {
|
||||
const [config, setConfig] = useState<Config>({
|
||||
username: '',
|
||||
password: '',
|
||||
memory: 4096,
|
||||
comfortVersion: '',
|
||||
accessToken: '',
|
||||
clientToken: '',
|
||||
});
|
||||
|
||||
const loadInitialConfig = () => {
|
||||
try {
|
||||
const savedConfig = localStorage.getItem('launcher_config');
|
||||
if (savedConfig) {
|
||||
return JSON.parse(savedConfig);
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('Ошибка загрузки конфигурации:', error);
|
||||
}
|
||||
return {
|
||||
username: '',
|
||||
password: '',
|
||||
comfortVersion: '',
|
||||
accessToken: '',
|
||||
clientToken: '',
|
||||
};
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const savedConfig = loadInitialConfig();
|
||||
setConfig(savedConfig);
|
||||
}, []);
|
||||
|
||||
const saveConfig = (newConfig: Partial<Config>) => {
|
||||
const updatedConfig = { ...config, ...newConfig };
|
||||
setConfig(updatedConfig);
|
||||
localStorage.setItem('launcher_config', JSON.stringify(updatedConfig));
|
||||
};
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setConfig((prev) => ({ ...prev, [name]: value }));
|
||||
};
|
||||
|
||||
return { config, setConfig, saveConfig, handleInputChange };
|
||||
};
|
||||
|
||||
export default useConfig;
|
@ -6,7 +6,7 @@
|
||||
http-equiv="Content-Security-Policy"
|
||||
content="script-src 'self' 'unsafe-inline'"
|
||||
/>
|
||||
<title>Hello Electron React!</title>
|
||||
<title>popa-launcher</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
433
src/renderer/pages/LaunchPage.tsx
Normal file
433
src/renderer/pages/LaunchPage.tsx
Normal file
@ -0,0 +1,433 @@
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
Button,
|
||||
Snackbar,
|
||||
Alert,
|
||||
LinearProgress,
|
||||
} from '@mui/material';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import ServerStatus from '../components/ServerStatus/ServerStatus';
|
||||
import PopaPopa from '../components/popa-popa';
|
||||
import SettingsIcon from '@mui/icons-material/Settings';
|
||||
import React from 'react';
|
||||
import SettingsModal from '../components/Settings/SettingsModal';
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
electron: {
|
||||
ipcRenderer: {
|
||||
invoke(channel: string, ...args: unknown[]): Promise<any>;
|
||||
on(channel: string, func: (...args: unknown[]) => void): void;
|
||||
removeAllListeners(channel: string): void;
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Определяем тип для props
|
||||
interface LaunchPageProps {
|
||||
onLaunchPage?: () => void;
|
||||
launchOptions?: {
|
||||
// Делаем опциональным
|
||||
downloadUrl: string;
|
||||
apiReleaseUrl: string;
|
||||
versionFileName: string;
|
||||
packName: string;
|
||||
memory: number;
|
||||
baseVersion: string;
|
||||
serverIp: string;
|
||||
fabricVersion: string;
|
||||
};
|
||||
}
|
||||
|
||||
const LaunchPage = ({
|
||||
onLaunchPage,
|
||||
launchOptions = {} as any,
|
||||
}: LaunchPageProps) => {
|
||||
const navigate = useNavigate();
|
||||
const { versionId } = useParams();
|
||||
const [versionConfig, setVersionConfig] = useState<any>(null);
|
||||
|
||||
// Начальное состояние должно быть пустым или с минимальными значениями
|
||||
const [config, setConfig] = useState<{
|
||||
memory: number;
|
||||
preserveFiles: string[];
|
||||
}>({
|
||||
memory: 0,
|
||||
preserveFiles: [],
|
||||
});
|
||||
const [isDownloading, setIsDownloading] = useState(false);
|
||||
const [downloadProgress, setDownloadProgress] = useState(0);
|
||||
const [buffer, setBuffer] = useState(10);
|
||||
const [installStatus, setInstallStatus] = useState('');
|
||||
const [notification, setNotification] = useState<{
|
||||
open: boolean;
|
||||
message: string;
|
||||
severity: 'success' | 'error' | 'info';
|
||||
}>({ open: false, message: '', severity: 'info' });
|
||||
const [installStep, setInstallStep] = useState('');
|
||||
const [installMessage, setInstallMessage] = useState('');
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const handleOpen = () => setOpen(true);
|
||||
const handleClose = () => setOpen(false);
|
||||
|
||||
useEffect(() => {
|
||||
const savedConfig = localStorage.getItem('launcher_config');
|
||||
if (!savedConfig || !JSON.parse(savedConfig).accessToken) {
|
||||
navigate('/login');
|
||||
}
|
||||
|
||||
const progressListener = (...args: unknown[]) => {
|
||||
const progress = args[0] as number;
|
||||
setDownloadProgress(progress);
|
||||
setBuffer(Math.min(progress + 10, 100));
|
||||
};
|
||||
|
||||
const statusListener = (...args: unknown[]) => {
|
||||
const status = args[0] as { step: string; message: string };
|
||||
setInstallStep(status.step);
|
||||
setInstallMessage(status.message);
|
||||
};
|
||||
|
||||
window.electron.ipcRenderer.on('download-progress', progressListener);
|
||||
window.electron.ipcRenderer.on('installation-status', statusListener);
|
||||
|
||||
return () => {
|
||||
// Удаляем только конкретных слушателей, а не всех
|
||||
// Это безопаснее, чем removeAllListeners
|
||||
const cleanup = window.electron.ipcRenderer.on;
|
||||
if (typeof cleanup === 'function') {
|
||||
cleanup('download-progress', progressListener);
|
||||
cleanup('installation-status', statusListener);
|
||||
}
|
||||
// Удаляем использование removeAllListeners
|
||||
};
|
||||
}, [navigate]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchVersionConfig = async () => {
|
||||
if (!versionId) return;
|
||||
|
||||
try {
|
||||
// Сначала проверяем, есть ли конфигурация в localStorage
|
||||
const savedConfig = localStorage.getItem('selected_version_config');
|
||||
if (savedConfig) {
|
||||
const parsedConfig = JSON.parse(savedConfig);
|
||||
setVersionConfig(parsedConfig);
|
||||
|
||||
// Устанавливаем значения памяти и preserveFiles из конфигурации
|
||||
setConfig({
|
||||
memory: parsedConfig.memory || 4096,
|
||||
preserveFiles: parsedConfig.preserveFiles || [],
|
||||
});
|
||||
|
||||
// Очищаем localStorage
|
||||
localStorage.removeItem('selected_version_config');
|
||||
return;
|
||||
}
|
||||
|
||||
// Если нет в localStorage, запрашиваем с сервера
|
||||
const result = await window.electron.ipcRenderer.invoke(
|
||||
'get-version-config',
|
||||
{ versionId },
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
setVersionConfig(result.config);
|
||||
setConfig({
|
||||
memory: result.config.memory || 4096,
|
||||
preserveFiles: result.config.preserveFiles || [],
|
||||
});
|
||||
} else {
|
||||
// Если не удалось получить конфигурацию, используем значения по умолчанию
|
||||
const defaultConfig = {
|
||||
downloadUrl: '',
|
||||
apiReleaseUrl: '',
|
||||
versionFileName: `${versionId}_version.txt`,
|
||||
packName: versionId || 'Comfort',
|
||||
memory: 4096,
|
||||
baseVersion: '1.21.4',
|
||||
serverIp: 'popa-popa.ru',
|
||||
fabricVersion: '0.16.14',
|
||||
preserveFiles: ['popa-launcher-config.json'],
|
||||
};
|
||||
setVersionConfig(defaultConfig);
|
||||
setConfig({
|
||||
memory: defaultConfig.memory,
|
||||
preserveFiles: defaultConfig.preserveFiles || [],
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при получении настроек версии:', error);
|
||||
// Используем значения по умолчанию
|
||||
const defaultConfig = {
|
||||
downloadUrl: '',
|
||||
apiReleaseUrl: '',
|
||||
versionFileName: `${versionId}_version.txt`,
|
||||
packName: versionId || 'Comfort',
|
||||
memory: 4096,
|
||||
baseVersion: '1.21.4',
|
||||
serverIp: 'popa-popa.ru',
|
||||
fabricVersion: '0.16.14',
|
||||
preserveFiles: ['popa-launcher-config.json'],
|
||||
};
|
||||
setVersionConfig(defaultConfig);
|
||||
setConfig({
|
||||
memory: defaultConfig.memory,
|
||||
preserveFiles: defaultConfig.preserveFiles || [],
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
fetchVersionConfig();
|
||||
}, [versionId]);
|
||||
|
||||
const showNotification = (
|
||||
message: string,
|
||||
severity: 'success' | 'error' | 'info',
|
||||
) => {
|
||||
setNotification({ open: true, message, severity });
|
||||
};
|
||||
|
||||
const handleCloseNotification = () => {
|
||||
setNotification({ ...notification, open: false });
|
||||
};
|
||||
|
||||
// Функция для запуска игры с настройками выбранной версии
|
||||
const handleLaunchMinecraft = async () => {
|
||||
try {
|
||||
setIsDownloading(true);
|
||||
setDownloadProgress(0);
|
||||
setBuffer(10);
|
||||
|
||||
// Используем настройки выбранной версии или дефолтные
|
||||
const currentConfig = versionConfig || {
|
||||
packName: versionId || 'Comfort',
|
||||
memory: 4096,
|
||||
baseVersion: '1.21.4',
|
||||
serverIp: 'popa-popa.ru',
|
||||
fabricVersion: '0.16.14',
|
||||
preserveFiles: [],
|
||||
};
|
||||
|
||||
// Проверяем, является ли это ванильной версией
|
||||
const isVanillaVersion =
|
||||
!currentConfig.downloadUrl || currentConfig.downloadUrl === '';
|
||||
|
||||
if (!isVanillaVersion) {
|
||||
// Если это не ванильная версия, выполняем загрузку и распаковку
|
||||
const packOptions = {
|
||||
downloadUrl: currentConfig.downloadUrl,
|
||||
apiReleaseUrl: currentConfig.apiReleaseUrl,
|
||||
versionFileName: currentConfig.versionFileName,
|
||||
packName: versionId || currentConfig.packName,
|
||||
preserveFiles: config.preserveFiles,
|
||||
};
|
||||
|
||||
// Передаем опции для скачивания
|
||||
const downloadResult = await window.electron.ipcRenderer.invoke(
|
||||
'download-and-extract',
|
||||
packOptions,
|
||||
);
|
||||
|
||||
if (downloadResult?.success) {
|
||||
if (downloadResult.updated) {
|
||||
showNotification(
|
||||
`Сборка ${downloadResult.packName} успешно обновлена до версии ${downloadResult.version}`,
|
||||
'success',
|
||||
);
|
||||
} else {
|
||||
showNotification(
|
||||
`Установлена актуальная версия сборки ${downloadResult.packName} (${downloadResult.version})`,
|
||||
'info',
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
showNotification('Запускаем ванильный Minecraft...', 'info');
|
||||
}
|
||||
|
||||
// Опции для запуска Minecraft
|
||||
const savedConfig = JSON.parse(
|
||||
localStorage.getItem('launcher_config') || '{}',
|
||||
);
|
||||
|
||||
const options = {
|
||||
accessToken: savedConfig.accessToken,
|
||||
uuid: savedConfig.uuid,
|
||||
username: savedConfig.username,
|
||||
memory: config.memory,
|
||||
baseVersion: currentConfig.baseVersion,
|
||||
packName: versionId || currentConfig.packName,
|
||||
serverIp: currentConfig.serverIp,
|
||||
fabricVersion: currentConfig.fabricVersion,
|
||||
// Для ванильной версии устанавливаем флаг
|
||||
isVanillaVersion: isVanillaVersion,
|
||||
versionToLaunchOverride: isVanillaVersion ? versionId : undefined,
|
||||
};
|
||||
|
||||
const launchResult = await window.electron.ipcRenderer.invoke(
|
||||
'launch-minecraft',
|
||||
options,
|
||||
);
|
||||
|
||||
if (launchResult?.success) {
|
||||
showNotification('Minecraft успешно запущен!', 'success');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
showNotification(`Ошибка: ${error.message}`, 'error');
|
||||
} finally {
|
||||
setIsDownloading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Функция для сохранения настроек
|
||||
const savePackConfig = async () => {
|
||||
try {
|
||||
const configToSave = {
|
||||
memory: config.memory,
|
||||
preserveFiles: config.preserveFiles || [],
|
||||
};
|
||||
|
||||
await window.electron.ipcRenderer.invoke('save-pack-config', {
|
||||
packName: versionId || versionConfig?.packName || 'Comfort',
|
||||
config: configToSave,
|
||||
});
|
||||
|
||||
// Обновляем launchOptions
|
||||
launchOptions.memory = config.memory;
|
||||
|
||||
showNotification('Настройки сохранены', 'success');
|
||||
} catch (error) {
|
||||
console.error('Ошибка при сохранении настроек:', error);
|
||||
showNotification('Ошибка сохранения настроек', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ gap: '1vh', display: 'flex', flexDirection: 'column' }}>
|
||||
<PopaPopa />
|
||||
|
||||
<Typography variant="h4">Игровой сервер</Typography>
|
||||
|
||||
<Typography variant="h4">долбаёбов в Minecraft</Typography>
|
||||
|
||||
<Box>
|
||||
<Typography variant="body1" sx={{ color: '#FFFFFF61' }}>
|
||||
СЕРВЕР ГДЕ ВСЕМ НА ВАС ПОХУЙ
|
||||
</Typography>
|
||||
<Typography variant="body1" sx={{ color: '#FFFFFF61' }}>
|
||||
СЕРВЕР ГДЕ РАЗРЕШЕНЫ ОДНОПОЛЫЕ БРАКИ
|
||||
</Typography>
|
||||
<Typography variant="body1" sx={{ color: '#FFFFFF61' }}>
|
||||
СЕРВЕР ГДЕ ВСЕ ДОЛБАЕБЫ
|
||||
</Typography>
|
||||
<Typography variant="body1" sx={{ color: '#FFFFFF61' }}>
|
||||
СЕРВЕР ГДЕ НА СПАВНЕ БУДЕТ ХУЙ (ВОЗМОЖНО)
|
||||
</Typography>
|
||||
<Typography variant="body1" sx={{ color: '#FFFFFF61' }}>
|
||||
СЕРВЕР ЗА КОТОРЫЙ ВЫ ПРОДАДИТЕ МАТЬ
|
||||
</Typography>
|
||||
<Typography variant="body1" sx={{ color: '#FFFFFF61' }}>
|
||||
ТЫ МОЖЕШЬ КУПИТЬ АДМИНКУ И ПОЛУЧИТЬ ПИЗДЫ
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box>
|
||||
<ServerStatus
|
||||
serverIp={versionConfig?.serverIp || 'popa-popa.ru'}
|
||||
refreshInterval={30000}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
{isDownloading ? (
|
||||
<Box sx={{ mb: 3, width: '100%' }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center' }}>
|
||||
<Box sx={{ width: '100%', mr: 1 }}>
|
||||
<LinearProgress
|
||||
variant="buffer"
|
||||
value={downloadProgress}
|
||||
valueBuffer={buffer}
|
||||
/>
|
||||
</Box>
|
||||
<Box sx={{ minWidth: 35 }}>
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{ color: 'white' }}
|
||||
>{`${Math.round(downloadProgress)}%`}</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
) : (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
gap: '1vw',
|
||||
width: '100%', // родитель занимает всю ширину
|
||||
}}
|
||||
>
|
||||
{/* Первая кнопка — растягивается на всё доступное пространство */}
|
||||
<Button
|
||||
variant="contained"
|
||||
color="primary"
|
||||
onClick={handleLaunchMinecraft}
|
||||
sx={{
|
||||
flexGrow: 1, // занимает всё свободное место
|
||||
width: 'auto', // ширина подстраивается
|
||||
borderRadius: '3vw',
|
||||
fontFamily: 'Benzin-Bold',
|
||||
background: 'linear-gradient(90deg, #3B96FF 0%, #FFB7ED 100%)',
|
||||
}}
|
||||
>
|
||||
Запустить Minecraft
|
||||
</Button>
|
||||
|
||||
{/* Вторая кнопка — квадратная, фиксированного размера (ширина = высоте) */}
|
||||
<Button
|
||||
variant="contained"
|
||||
sx={{
|
||||
flexShrink: 0, // не сжимается
|
||||
aspectRatio: '1', // ширина = высоте
|
||||
backgroundColor: 'grey',
|
||||
borderRadius: '3vw',
|
||||
minHeight: 'unset',
|
||||
minWidth: 'unset',
|
||||
height: '100%', // занимает полную высоту родителя
|
||||
}}
|
||||
onClick={handleOpen}
|
||||
>
|
||||
<SettingsIcon />
|
||||
</Button>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Snackbar
|
||||
open={notification.open}
|
||||
autoHideDuration={6000}
|
||||
onClose={handleCloseNotification}
|
||||
>
|
||||
<Alert
|
||||
onClose={handleCloseNotification}
|
||||
severity={notification.severity}
|
||||
sx={{ width: '100%' }}
|
||||
>
|
||||
{notification.message}
|
||||
</Alert>
|
||||
</Snackbar>
|
||||
|
||||
<SettingsModal
|
||||
open={open}
|
||||
onClose={handleClose}
|
||||
config={config}
|
||||
onConfigChange={setConfig}
|
||||
packName={versionId || versionConfig?.packName || 'Comfort'}
|
||||
onSave={savePackConfig}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default LaunchPage;
|
110
src/renderer/pages/Login.tsx
Normal file
110
src/renderer/pages/Login.tsx
Normal file
@ -0,0 +1,110 @@
|
||||
import { Box, Typography } from '@mui/material';
|
||||
import useAuth from '../hooks/useAuth';
|
||||
import AuthForm from '../components/Login/AuthForm';
|
||||
import MemorySlider from '../components/Login/MemorySlider';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import PopaPopa from '../components/popa-popa';
|
||||
import useConfig from '../hooks/useConfig';
|
||||
|
||||
const Login = () => {
|
||||
const navigate = useNavigate();
|
||||
const { config, setConfig, saveConfig, handleInputChange } = useConfig();
|
||||
const { status, validateSession, refreshSession, authenticateWithElyBy } =
|
||||
useAuth();
|
||||
|
||||
const authorization = async () => {
|
||||
console.log('Начинаем процесс авторизации...');
|
||||
|
||||
if (!config.username.trim()) {
|
||||
console.log('Ошибка: не указан никнейм');
|
||||
alert('Введите никнейм!');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Проверяем, есть ли сохранённый токен
|
||||
if (config.accessToken && config.clientToken) {
|
||||
console.log('Проверка валидности существующего токена...');
|
||||
const isValid = await validateSession(config.accessToken);
|
||||
|
||||
if (!isValid) {
|
||||
console.log('Токен недействителен, пытаемся обновить...');
|
||||
const refreshedSession = await refreshSession(
|
||||
config.accessToken,
|
||||
config.clientToken,
|
||||
);
|
||||
|
||||
if (!refreshedSession) {
|
||||
console.log(
|
||||
'Не удалось обновить токен, требуется новая авторизация',
|
||||
);
|
||||
// Очищаем недействительные токены
|
||||
saveConfig({
|
||||
accessToken: '',
|
||||
clientToken: '',
|
||||
});
|
||||
|
||||
// Пытаемся выполнить новую авторизацию
|
||||
if (config.password) {
|
||||
const newSession = await authenticateWithElyBy(
|
||||
config.username,
|
||||
config.password,
|
||||
saveConfig,
|
||||
);
|
||||
if (!newSession) {
|
||||
console.log('Авторизация не удалась');
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
console.log('Требуется ввод пароля для новой авторизации');
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.log('Токен действителен');
|
||||
}
|
||||
} else {
|
||||
console.log('Токен отсутствует, выполняем авторизацию...');
|
||||
// Проверяем наличие пароля
|
||||
if (!config.password) {
|
||||
console.log('Ошибка: не указан пароль');
|
||||
alert('Введите пароль!');
|
||||
return;
|
||||
}
|
||||
|
||||
const session = await authenticateWithElyBy(
|
||||
config.username,
|
||||
config.password,
|
||||
saveConfig,
|
||||
);
|
||||
if (!session) {
|
||||
console.log('Авторизация не удалась');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
console.log('Авторизация успешно завершена');
|
||||
navigate('/');
|
||||
} catch (error) {
|
||||
console.log(`ОШИБКА при авторизации: ${error.message}`);
|
||||
// Очищаем недействительные токены при ошибке
|
||||
saveConfig({
|
||||
accessToken: '',
|
||||
clientToken: '',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<PopaPopa />
|
||||
<AuthForm
|
||||
config={config}
|
||||
handleInputChange={handleInputChange}
|
||||
onLogin={authorization}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default Login;
|
489
src/renderer/pages/Marketplace.tsx
Normal file
489
src/renderer/pages/Marketplace.tsx
Normal file
@ -0,0 +1,489 @@
|
||||
// src/renderer/pages/Marketplace.tsx
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
CircularProgress,
|
||||
Button,
|
||||
Grid,
|
||||
Card,
|
||||
CardContent,
|
||||
CardMedia,
|
||||
Pagination,
|
||||
Tabs,
|
||||
Tab,
|
||||
Alert,
|
||||
Snackbar,
|
||||
} from '@mui/material';
|
||||
import { isPlayerOnline, getPlayerServer } from '../utils/playerOnlineCheck';
|
||||
import { buyItem, fetchMarketplace, MarketplaceResponse, Server } from '../api';
|
||||
import PlayerInventory from '../components/PlayerInventory';
|
||||
|
||||
interface TabPanelProps {
|
||||
children?: React.ReactNode;
|
||||
index: number;
|
||||
value: number;
|
||||
}
|
||||
|
||||
function TabPanel(props: TabPanelProps) {
|
||||
const { children, value, index, ...other } = props;
|
||||
|
||||
return (
|
||||
<div
|
||||
role="tabpanel"
|
||||
hidden={value !== index}
|
||||
id={`marketplace-tabpanel-${index}`}
|
||||
aria-labelledby={`marketplace-tab-${index}`}
|
||||
{...other}
|
||||
>
|
||||
{value === index && <Box sx={{ pt: 3 }}>{children}</Box>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Marketplace() {
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [marketLoading, setMarketLoading] = useState<boolean>(false);
|
||||
const [isOnline, setIsOnline] = useState<boolean>(false);
|
||||
const [username, setUsername] = useState<string>('');
|
||||
const [playerServer, setPlayerServer] = useState<Server | null>(null);
|
||||
const [marketItems, setMarketItems] = useState<MarketplaceResponse | null>(
|
||||
null,
|
||||
);
|
||||
const [page, setPage] = useState<number>(1);
|
||||
const [totalPages, setTotalPages] = useState<number>(1);
|
||||
const [tabValue, setTabValue] = useState<number>(0);
|
||||
const [notification, setNotification] = useState<{
|
||||
open: boolean;
|
||||
message: string;
|
||||
type: 'success' | 'error';
|
||||
}>({
|
||||
open: false,
|
||||
message: '',
|
||||
type: 'success',
|
||||
});
|
||||
|
||||
const translateServer = (server: Server) => {
|
||||
switch (server.name) {
|
||||
case 'Server minecraft.hub.popa-popa.ru':
|
||||
return 'Хаб';
|
||||
case 'Server survival.hub.popa-popa.ru':
|
||||
return 'Выживание';
|
||||
case 'Server minecraft.minigames.popa-popa.ru':
|
||||
return 'Миниигры';
|
||||
default:
|
||||
return server.name;
|
||||
}
|
||||
};
|
||||
|
||||
// Функция для проверки онлайн-статуса игрока и определения сервера
|
||||
const checkPlayerStatus = async () => {
|
||||
if (!username) return;
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
// Проверяем, онлайн ли игрок и получаем сервер, где он находится
|
||||
const { online, server } = await getPlayerServer(username);
|
||||
setIsOnline(online);
|
||||
setPlayerServer(server);
|
||||
|
||||
// Если игрок онлайн и на каком-то сервере, загружаем предметы рынка
|
||||
if (online && server) {
|
||||
await loadMarketItems(server.ip, 1);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при проверке онлайн-статуса:', error);
|
||||
setIsOnline(false);
|
||||
setPlayerServer(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Функция для загрузки предметов маркетплейса
|
||||
const loadMarketItems = async (serverIp: string, pageNumber: number) => {
|
||||
try {
|
||||
setMarketLoading(true);
|
||||
const marketData = await fetchMarketplace(serverIp, pageNumber, 10); // 10 предметов на страницу
|
||||
setMarketItems(marketData);
|
||||
setPage(marketData.page);
|
||||
setTotalPages(marketData.pages);
|
||||
} catch (error) {
|
||||
console.error('Ошибка при загрузке предметов рынка:', error);
|
||||
setMarketItems(null);
|
||||
} finally {
|
||||
setMarketLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Обработчик смены страницы
|
||||
const handlePageChange = (
|
||||
_event: React.ChangeEvent<unknown>,
|
||||
newPage: number,
|
||||
) => {
|
||||
if (playerServer) {
|
||||
loadMarketItems(playerServer.ip, newPage);
|
||||
}
|
||||
};
|
||||
|
||||
// Обработчик смены вкладок
|
||||
const handleTabChange = (_event: React.SyntheticEvent, newValue: number) => {
|
||||
setTabValue(newValue);
|
||||
};
|
||||
|
||||
// Обновляем функцию handleBuyItem в Marketplace.tsx
|
||||
const handleBuyItem = async (itemId: string) => {
|
||||
try {
|
||||
if (username) {
|
||||
const result = await buyItem(username, itemId);
|
||||
|
||||
setNotification({
|
||||
open: true,
|
||||
message:
|
||||
result.message ||
|
||||
'Предмет успешно куплен! Он будет добавлен в ваш инвентарь.',
|
||||
type: 'success',
|
||||
});
|
||||
|
||||
// Обновляем список предметов
|
||||
if (playerServer) {
|
||||
loadMarketItems(playerServer.ip, page);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при покупке предмета:', error);
|
||||
setNotification({
|
||||
open: true,
|
||||
message:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Ошибка при покупке предмета',
|
||||
type: 'error',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Закрытие уведомления
|
||||
const handleCloseNotification = () => {
|
||||
setNotification({ ...notification, open: false });
|
||||
};
|
||||
|
||||
// Получаем имя пользователя из localStorage при монтировании компонента
|
||||
useEffect(() => {
|
||||
const savedConfig = localStorage.getItem('launcher_config');
|
||||
if (savedConfig) {
|
||||
const config = JSON.parse(savedConfig);
|
||||
if (config.username) {
|
||||
setUsername(config.username);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Проверяем статус при изменении username
|
||||
useEffect(() => {
|
||||
if (username) {
|
||||
checkPlayerStatus();
|
||||
}
|
||||
}, [username]);
|
||||
|
||||
// Показываем loader во время проверки
|
||||
if (loading) {
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
height: '100%',
|
||||
gap: 2,
|
||||
}}
|
||||
>
|
||||
<CircularProgress size={60} />
|
||||
<Typography variant="h6" color="white">
|
||||
Проверяем, находитесь ли вы на сервере...
|
||||
</Typography>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// Если игрок не онлайн
|
||||
if (!isOnline) {
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
height: '100%',
|
||||
gap: 3,
|
||||
padding: 4,
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
<Typography variant="h4" color="error">
|
||||
Доступ к рынку ограничен
|
||||
</Typography>
|
||||
<Typography variant="h6" color="white">
|
||||
Для доступа к рынку вам необходимо находиться на одном из серверов
|
||||
игры.
|
||||
</Typography>
|
||||
<Typography variant="body1" color="white" sx={{ opacity: 0.8 }}>
|
||||
Зайдите на любой сервер и обновите страницу.
|
||||
</Typography>
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={checkPlayerStatus}
|
||||
sx={{
|
||||
mt: '1%',
|
||||
borderRadius: '20px',
|
||||
p: '10px 25px',
|
||||
color: 'white',
|
||||
backgroundColor: 'rgb(255, 77, 77)',
|
||||
'&:hover': {
|
||||
backgroundColor: 'rgba(255, 77, 77, 0.5)',
|
||||
},
|
||||
fontFamily: 'Benzin-Bold',
|
||||
}}
|
||||
>
|
||||
Проверить снова
|
||||
</Button>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box sx={{ padding: 3, width: '95%', height: '80%' }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: '1vw' }}>
|
||||
<Typography variant="h4" color="white" gutterBottom>
|
||||
Рынок сервера{' '}
|
||||
</Typography>
|
||||
<Typography
|
||||
style={{
|
||||
color: 'white',
|
||||
backgroundColor: 'rgba(255, 77, 77, 1)',
|
||||
padding: '0vw 2vw',
|
||||
borderRadius: '5vw',
|
||||
fontFamily: 'Benzin-Bold',
|
||||
textAlign: 'center',
|
||||
fontSize: '2vw',
|
||||
}}
|
||||
>
|
||||
{translateServer(playerServer || { name: '' })}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{/* Вкладки */}
|
||||
<Box sx={{ borderBottom: 1, borderColor: 'transparent' }}>
|
||||
<Tabs
|
||||
value={tabValue}
|
||||
onChange={handleTabChange}
|
||||
aria-label="marketplace tabs"
|
||||
disableRipple={true}
|
||||
sx={{
|
||||
'& .MuiTabs-indicator': {
|
||||
backgroundColor: 'rgba(255, 77, 77, 1)',
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tab
|
||||
label="Товары"
|
||||
disableRipple={true}
|
||||
sx={{
|
||||
fontFamily: 'Benzin-Bold',
|
||||
color: 'white',
|
||||
'&.Mui-selected': {
|
||||
color: 'rgba(255, 77, 77, 1)',
|
||||
},
|
||||
'&:hover': {
|
||||
color: 'rgba(255, 77, 77, 1)',
|
||||
},
|
||||
transition: 'all 0.3s ease',
|
||||
}}
|
||||
/>
|
||||
<Tab
|
||||
label="Мой инвентарь"
|
||||
disableRipple={true}
|
||||
sx={{
|
||||
fontFamily: 'Benzin-Bold',
|
||||
color: 'white',
|
||||
'&.Mui-selected': {
|
||||
color: 'rgba(255, 77, 77, 1)',
|
||||
},
|
||||
'&:hover': {
|
||||
color: 'rgba(255, 77, 77, 1)',
|
||||
},
|
||||
transition: 'all 0.3s ease',
|
||||
}}
|
||||
/>
|
||||
</Tabs>
|
||||
</Box>
|
||||
|
||||
{/* Содержимое вкладки "Товары" */}
|
||||
<TabPanel value={tabValue} index={0}>
|
||||
{marketLoading ? (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', mt: '50vw' }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
) : !marketItems || marketItems.items.length === 0 ? (
|
||||
<Box sx={{ mt: 4, textAlign: 'center' }}>
|
||||
<Typography variant="h6" color="white" sx={{ mt: '10vw' }}>
|
||||
На данный момент на рынке нет предметов.
|
||||
</Typography>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="primary"
|
||||
onClick={() =>
|
||||
playerServer && loadMarketItems(playerServer.ip, 1)
|
||||
}
|
||||
sx={{
|
||||
mt: 2,
|
||||
borderRadius: '20px',
|
||||
p: '10px 25px',
|
||||
color: 'white',
|
||||
backgroundColor: 'rgb(255, 77, 77)',
|
||||
'&:hover': {
|
||||
backgroundColor: 'rgba(255, 77, 77, 0.5)',
|
||||
},
|
||||
fontFamily: 'Benzin-Bold',
|
||||
fontSize: '1vw',
|
||||
}}
|
||||
>
|
||||
Обновить
|
||||
</Button>
|
||||
</Box>
|
||||
) : (
|
||||
<>
|
||||
<Grid container spacing={2} sx={{ mt: 2 }}>
|
||||
{marketItems.items.map((item) => (
|
||||
<Grid item xs={12} sm={6} md={4} lg={3} key={item.id}>
|
||||
<Card
|
||||
sx={{
|
||||
bgcolor: 'rgba(255, 255, 255, 0.05)',
|
||||
borderRadius: '1vw',
|
||||
}}
|
||||
>
|
||||
<CardMedia
|
||||
component="img"
|
||||
sx={{
|
||||
minWidth: '10vw',
|
||||
minHeight: '10vw',
|
||||
maxHeight: '10vw',
|
||||
objectFit: 'contain',
|
||||
bgcolor: 'white',
|
||||
p: '1vw',
|
||||
imageRendering: 'pixelated',
|
||||
}}
|
||||
image={`/minecraft/${item.material.toLowerCase()}.png`}
|
||||
alt={item.material}
|
||||
/>
|
||||
<CardContent>
|
||||
<Typography variant="h6" color="white">
|
||||
{item.display_name ||
|
||||
item.material
|
||||
.replace(/_/g, ' ')
|
||||
.toLowerCase()
|
||||
.replace(/\b\w/g, (l) => l.toUpperCase())}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="white">
|
||||
Количество: {item.amount}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="white">
|
||||
Цена: {item.price} монет
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="white"
|
||||
sx={{ opacity: 0.7 }}
|
||||
>
|
||||
Продавец: {item.seller_name}
|
||||
</Typography>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="primary"
|
||||
fullWidth
|
||||
sx={{
|
||||
mt: '1vw',
|
||||
borderRadius: '20px',
|
||||
p: '0.3vw 0vw',
|
||||
color: 'white',
|
||||
backgroundColor: 'rgb(255, 77, 77)',
|
||||
'&:hover': {
|
||||
backgroundColor: 'rgba(255, 77, 77, 0.5)',
|
||||
},
|
||||
fontFamily: 'Benzin-Bold',
|
||||
fontSize: '1vw',
|
||||
}}
|
||||
onClick={() => handleBuyItem(item.id)}
|
||||
>
|
||||
Купить
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
|
||||
{totalPages > 1 && (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
|
||||
<Pagination
|
||||
count={totalPages}
|
||||
page={page}
|
||||
onChange={handlePageChange}
|
||||
color="primary"
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</TabPanel>
|
||||
|
||||
{/* Содержимое вкладки "Мой инвентарь" */}
|
||||
<TabPanel value={tabValue} index={1}>
|
||||
{playerServer && username ? (
|
||||
<PlayerInventory
|
||||
username={username}
|
||||
serverIp={playerServer.ip}
|
||||
onSellSuccess={() => {
|
||||
// После успешной продажи, обновляем список товаров
|
||||
if (playerServer) {
|
||||
loadMarketItems(playerServer.ip, 1);
|
||||
}
|
||||
|
||||
// Показываем уведомление
|
||||
setNotification({
|
||||
open: true,
|
||||
message: 'Предмет успешно выставлен на продажу!',
|
||||
type: 'success',
|
||||
});
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<Typography
|
||||
variant="body1"
|
||||
color="white"
|
||||
sx={{ textAlign: 'center', my: 4 }}
|
||||
>
|
||||
Не удалось загрузить инвентарь.
|
||||
</Typography>
|
||||
)}
|
||||
</TabPanel>
|
||||
|
||||
{/* Уведомления */}
|
||||
<Snackbar
|
||||
open={notification.open}
|
||||
autoHideDuration={6000}
|
||||
onClose={handleCloseNotification}
|
||||
>
|
||||
<Alert
|
||||
onClose={handleCloseNotification}
|
||||
severity={notification.type}
|
||||
sx={{ width: '100%' }}
|
||||
>
|
||||
{notification.message}
|
||||
</Alert>
|
||||
</Snackbar>
|
||||
</Box>
|
||||
);
|
||||
}
|
373
src/renderer/pages/Profile.tsx
Normal file
373
src/renderer/pages/Profile.tsx
Normal file
@ -0,0 +1,373 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import SkinViewer from '../components/SkinViewer';
|
||||
import {
|
||||
fetchPlayer,
|
||||
uploadSkin,
|
||||
fetchCapes,
|
||||
Cape,
|
||||
activateCape,
|
||||
deactivateCape,
|
||||
} from '../api';
|
||||
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
Paper,
|
||||
Button,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Select,
|
||||
MenuItem,
|
||||
Alert,
|
||||
CircularProgress,
|
||||
} from '@mui/material';
|
||||
|
||||
import CapeCard from '../components/CapeCard';
|
||||
|
||||
export default function Profile() {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [walkingSpeed, setWalkingSpeed] = useState<number>(0.5);
|
||||
const [skin, setSkin] = useState<string>('');
|
||||
const [cape, setCape] = useState<string>('');
|
||||
const [username, setUsername] = useState<string>('');
|
||||
const [skinFile, setSkinFile] = useState<File | null>(null);
|
||||
const [skinModel, setSkinModel] = useState<string>(''); // slim или classic
|
||||
const [uploadStatus, setUploadStatus] = useState<
|
||||
'idle' | 'loading' | 'success' | 'error'
|
||||
>('idle');
|
||||
const [statusMessage, setStatusMessage] = useState<string>('');
|
||||
const [isDragOver, setIsDragOver] = useState<boolean>(false);
|
||||
const [capes, setCapes] = useState<Cape[]>([]);
|
||||
const [uuid, setUuid] = useState<string>('');
|
||||
const [loading, setLoading] = useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
const savedConfig = localStorage.getItem('launcher_config');
|
||||
if (savedConfig) {
|
||||
const config = JSON.parse(savedConfig);
|
||||
if (config.uuid) {
|
||||
loadPlayerData(config.uuid);
|
||||
setUsername(config.username || '');
|
||||
loadCapesData(config.username || '');
|
||||
setUuid(config.uuid || '');
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadPlayerData = async (uuid: string) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const player = await fetchPlayer(uuid);
|
||||
setSkin(player.skin_url);
|
||||
setCape(player.cloak_url);
|
||||
setLoading(false);
|
||||
} catch (error) {
|
||||
console.error('Ошибка при получении данных игрока:', error);
|
||||
setSkin('');
|
||||
setCape('');
|
||||
}
|
||||
};
|
||||
|
||||
const loadCapesData = async (username: string) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const capesData = await fetchCapes(username);
|
||||
setCapes(capesData);
|
||||
setLoading(false);
|
||||
} catch (error) {
|
||||
console.error('Ошибка при получении плащей:', error);
|
||||
setCapes([]);
|
||||
}
|
||||
};
|
||||
|
||||
// Обработка перетаскивания файла
|
||||
const handleFileDrop = (e: React.DragEvent<HTMLDivElement>) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
|
||||
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
|
||||
const file = e.dataTransfer.files[0];
|
||||
if (file.type === 'image/png') {
|
||||
setSkinFile(file);
|
||||
setStatusMessage(`Файл "${file.name}" готов к загрузке`);
|
||||
} else {
|
||||
setStatusMessage('Пожалуйста, выберите файл в формате PNG');
|
||||
setUploadStatus('error');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Обработка выбора файла
|
||||
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
if (e.target.files && e.target.files.length > 0) {
|
||||
const file = e.target.files[0];
|
||||
if (file.type === 'image/png') {
|
||||
setSkinFile(file);
|
||||
setStatusMessage(`Файл "${file.name}" готов к загрузке`);
|
||||
} else {
|
||||
setStatusMessage('Пожалуйста, выберите файл в формате PNG');
|
||||
setUploadStatus('error');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleActivateCape = async (cape_id: string) => {
|
||||
setLoading(true);
|
||||
await activateCape(username, cape_id);
|
||||
await loadCapesData(username);
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const handleDeactivateCape = async (cape_id: string) => {
|
||||
setLoading(true);
|
||||
await deactivateCape(username, cape_id);
|
||||
await loadCapesData(username);
|
||||
await loadPlayerData(uuid);
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
// Отправка запроса на установку скина
|
||||
const handleUploadSkin = async () => {
|
||||
setLoading(true);
|
||||
if (!skinFile || !username) {
|
||||
setStatusMessage('Необходимо выбрать файл и указать имя пользователя');
|
||||
setUploadStatus('error');
|
||||
return;
|
||||
}
|
||||
|
||||
setUploadStatus('loading');
|
||||
|
||||
try {
|
||||
await uploadSkin(username, skinFile, skinModel);
|
||||
|
||||
setStatusMessage('Скин успешно загружен!');
|
||||
setUploadStatus('success');
|
||||
|
||||
// Обновляем информацию о игроке, чтобы увидеть новый скин
|
||||
const config = JSON.parse(
|
||||
localStorage.getItem('launcher_config') || '{}',
|
||||
);
|
||||
if (config.uuid) {
|
||||
loadPlayerData(config.uuid);
|
||||
}
|
||||
} catch (error) {
|
||||
setStatusMessage(
|
||||
`Ошибка: ${error instanceof Error ? error.message : 'Не удалось загрузить скин'}`,
|
||||
);
|
||||
setUploadStatus('error');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
my: 4,
|
||||
display: 'flex',
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: '100px',
|
||||
width: '100%',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
{loading ? (
|
||||
<CircularProgress />
|
||||
) : (
|
||||
<>
|
||||
<Paper
|
||||
elevation={0}
|
||||
sx={{
|
||||
p: 0,
|
||||
borderRadius: 2,
|
||||
overflow: 'hidden',
|
||||
mb: 4,
|
||||
bgcolor: 'transparent',
|
||||
}}
|
||||
>
|
||||
{/* Используем переработанный компонент SkinViewer */}
|
||||
<Typography
|
||||
sx={{
|
||||
fontFamily: 'Benzin-Bold',
|
||||
alignSelf: 'center',
|
||||
justifySelf: 'center',
|
||||
textAlign: 'center',
|
||||
width: '100%',
|
||||
mb: '5vw',
|
||||
fontSize: '3vw',
|
||||
color: 'white',
|
||||
}}
|
||||
>
|
||||
{username}
|
||||
</Typography>
|
||||
<SkinViewer
|
||||
width={300}
|
||||
height={400}
|
||||
skinUrl={skin}
|
||||
capeUrl={cape}
|
||||
walkingSpeed={walkingSpeed}
|
||||
autoRotate={true}
|
||||
/>
|
||||
</Paper>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 2,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: '100%',
|
||||
maxWidth: '500px',
|
||||
bgcolor: 'rgba(255, 255, 255, 0.05)',
|
||||
padding: '3vw',
|
||||
borderRadius: '1vw',
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
border: '2px dashed',
|
||||
borderColor: isDragOver ? 'primary.main' : 'grey.400',
|
||||
borderRadius: 2,
|
||||
p: 3,
|
||||
mb: 2,
|
||||
textAlign: 'center',
|
||||
cursor: 'pointer',
|
||||
bgcolor: isDragOver
|
||||
? 'rgba(25, 118, 210, 0.08)'
|
||||
: 'transparent',
|
||||
transition: 'all 0.2s',
|
||||
}}
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(true);
|
||||
}}
|
||||
onDragLeave={() => setIsDragOver(false)}
|
||||
onDrop={handleFileDrop}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
accept=".png"
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
<Typography sx={{ color: 'white' }}>
|
||||
{skinFile
|
||||
? `Выбран файл: ${skinFile.name}`
|
||||
: 'Перетащите PNG файл скина или кликните для выбора'}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<FormControl
|
||||
color="primary"
|
||||
fullWidth
|
||||
sx={{ mb: 2, color: 'white' }}
|
||||
>
|
||||
<InputLabel sx={{ color: 'white' }}>Модель скина</InputLabel>
|
||||
<Select
|
||||
value={skinModel}
|
||||
label="Модель скина"
|
||||
onChange={(e) => setSkinModel(e.target.value)}
|
||||
sx={{
|
||||
color: 'white',
|
||||
borderColor: 'white',
|
||||
'& .MuiInputBase-input': {
|
||||
border: '1px solid white',
|
||||
transition: 'unset',
|
||||
},
|
||||
'&:focus': {
|
||||
borderRadius: 4,
|
||||
borderColor: '#80bdff',
|
||||
boxShadow: '0 0 0 0.2rem rgba(0,123,255,.25)',
|
||||
},
|
||||
}}
|
||||
>
|
||||
<MenuItem value="">По умолчанию</MenuItem>
|
||||
<MenuItem value="slim">Тонкая (Alex)</MenuItem>
|
||||
<MenuItem value="classic">Классическая (Steve)</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
{uploadStatus === 'error' && (
|
||||
<Alert severity="error" sx={{ mb: 2 }}>
|
||||
{statusMessage}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{uploadStatus === 'success' && (
|
||||
<Alert severity="success" sx={{ mb: 2 }}>
|
||||
{statusMessage}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Button
|
||||
sx={{
|
||||
color: 'white',
|
||||
borderRadius: '20px',
|
||||
p: '10px 25px',
|
||||
backgroundColor: 'rgb(0, 134, 0)',
|
||||
'&:hover': {
|
||||
backgroundColor: 'rgba(0, 134, 0, 0.5)',
|
||||
},
|
||||
fontFamily: 'Benzin-Bold',
|
||||
}}
|
||||
variant="contained"
|
||||
fullWidth
|
||||
onClick={handleUploadSkin}
|
||||
disabled={uploadStatus === 'loading' || !skinFile}
|
||||
startIcon={
|
||||
uploadStatus === 'loading' ? (
|
||||
<CircularProgress size={20} color="inherit" />
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{uploadStatus === 'loading' ? (
|
||||
<Typography sx={{ color: 'white' }}>Загрузка...</Typography>
|
||||
) : (
|
||||
<Typography sx={{ color: 'white' }}>
|
||||
Установить скин
|
||||
</Typography>
|
||||
)}
|
||||
</Button>
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
flexDirection: 'column',
|
||||
gap: 2,
|
||||
}}
|
||||
>
|
||||
<Typography>Ваши плащи</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'row',
|
||||
gap: 2,
|
||||
flexWrap: 'wrap',
|
||||
}}
|
||||
>
|
||||
{capes.map((cape) => (
|
||||
<CapeCard
|
||||
key={cape.cape_id}
|
||||
cape={cape}
|
||||
mode="profile"
|
||||
onAction={
|
||||
cape.is_active ? handleDeactivateCape : handleActivateCape
|
||||
}
|
||||
actionDisabled={loading}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
</>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
427
src/renderer/pages/Registration.tsx
Normal file
427
src/renderer/pages/Registration.tsx
Normal file
@ -0,0 +1,427 @@
|
||||
import Stepper from '@mui/material/Stepper';
|
||||
import Step from '@mui/material/Step';
|
||||
import StepLabel from '@mui/material/StepLabel';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
StepConnector,
|
||||
stepConnectorClasses,
|
||||
StepIconProps,
|
||||
styled,
|
||||
Typography,
|
||||
Box,
|
||||
TextField,
|
||||
Button,
|
||||
Snackbar,
|
||||
CircularProgress,
|
||||
} from '@mui/material';
|
||||
import LoginRoundedIcon from '@mui/icons-material/LoginRounded';
|
||||
import VerifiedRoundedIcon from '@mui/icons-material/VerifiedRounded';
|
||||
import AssignmentIndRoundedIcon from '@mui/icons-material/AssignmentIndRounded';
|
||||
import {
|
||||
generateVerificationCode,
|
||||
registerUser,
|
||||
getVerificationStatus,
|
||||
} from '../api';
|
||||
import QRCodeStyling from 'qr-code-styling';
|
||||
import popalogo from '../../../assets/icons/popa-popa.svg';
|
||||
|
||||
const ColorlibConnector = styled(StepConnector)(({ theme }) => ({
|
||||
[`&.${stepConnectorClasses.alternativeLabel}`]: {
|
||||
top: 22,
|
||||
},
|
||||
[`&.${stepConnectorClasses.active}`]: {
|
||||
[`& .${stepConnectorClasses.line}`]: {
|
||||
backgroundImage:
|
||||
'linear-gradient( 95deg,rgb(242,113,33) 0%,rgb(233,64,87) 50%,rgb(138,35,135) 100%)',
|
||||
},
|
||||
},
|
||||
[`&.${stepConnectorClasses.completed}`]: {
|
||||
[`& .${stepConnectorClasses.line}`]: {
|
||||
backgroundImage:
|
||||
'linear-gradient( 95deg,rgb(242,113,33) 0%,rgb(233,64,87) 50%,rgb(138,35,135) 100%)',
|
||||
},
|
||||
},
|
||||
[`& .${stepConnectorClasses.line}`]: {
|
||||
height: 3,
|
||||
border: 0,
|
||||
backgroundColor: '#eaeaf0',
|
||||
borderRadius: 1,
|
||||
...theme.applyStyles('dark', {
|
||||
backgroundColor: theme.palette.grey[800],
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
const ColorlibStepIconRoot = styled('div')<{
|
||||
ownerState: { completed?: boolean; active?: boolean };
|
||||
}>(({ theme }) => ({
|
||||
backgroundColor: '#ccc',
|
||||
zIndex: 1,
|
||||
color: '#fff',
|
||||
width: 50,
|
||||
height: 50,
|
||||
display: 'flex',
|
||||
borderRadius: '50%',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
...theme.applyStyles('dark', {
|
||||
backgroundColor: theme.palette.grey[700],
|
||||
}),
|
||||
variants: [
|
||||
{
|
||||
props: ({ ownerState }) => ownerState.active,
|
||||
style: {
|
||||
backgroundImage:
|
||||
'linear-gradient( 136deg, rgb(242,113,33) 0%, rgb(233,64,87) 50%, rgb(138,35,135) 100%)',
|
||||
boxShadow: '0 4px 10px 0 rgba(0,0,0,.25)',
|
||||
},
|
||||
},
|
||||
{
|
||||
props: ({ ownerState }) => ownerState.completed,
|
||||
style: {
|
||||
backgroundImage:
|
||||
'linear-gradient( 136deg, rgb(242,113,33) 0%, rgb(233,64,87) 50%, rgb(138,35,135) 100%)',
|
||||
},
|
||||
},
|
||||
],
|
||||
}));
|
||||
|
||||
function ColorlibStepIcon(props: StepIconProps) {
|
||||
const { active, completed, className } = props;
|
||||
|
||||
const icons: { [index: string]: React.ReactElement<unknown> } = {
|
||||
1: <AssignmentIndRoundedIcon />,
|
||||
2: <VerifiedRoundedIcon />,
|
||||
3: <LoginRoundedIcon />,
|
||||
};
|
||||
|
||||
return (
|
||||
<ColorlibStepIconRoot
|
||||
ownerState={{ completed, active }}
|
||||
className={className}
|
||||
>
|
||||
{icons[String(props.icon)]}
|
||||
</ColorlibStepIconRoot>
|
||||
);
|
||||
}
|
||||
|
||||
const qrCode = new QRCodeStyling({
|
||||
width: 300,
|
||||
height: 300,
|
||||
image: popalogo,
|
||||
data: 'https://t.me/popa_popa_popa_bot?start=test',
|
||||
shape: 'square',
|
||||
margin: 10,
|
||||
dotsOptions: {
|
||||
gradient: {
|
||||
type: 'linear',
|
||||
colorStops: [
|
||||
{
|
||||
offset: 0,
|
||||
color: 'rgb(242,113,33)',
|
||||
},
|
||||
{
|
||||
offset: 1,
|
||||
color: 'rgb(233,64,87)',
|
||||
},
|
||||
],
|
||||
},
|
||||
type: 'extra-rounded',
|
||||
},
|
||||
imageOptions: {
|
||||
crossOrigin: 'anonymous',
|
||||
margin: 20,
|
||||
imageSize: 0.5,
|
||||
},
|
||||
backgroundOptions: {
|
||||
color: 'transparent',
|
||||
},
|
||||
});
|
||||
|
||||
export const Registration = () => {
|
||||
const [activeStep, setActiveStep] = useState(0);
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [verificationCode, setVerificationCode] = useState<string | null>(null);
|
||||
const ref = useRef(null);
|
||||
const [url, setUrl] = useState('');
|
||||
const steps = ['Создание аккаунта', 'Верификация аккаунта в телеграмме'];
|
||||
|
||||
useEffect(() => {
|
||||
if (ref.current) {
|
||||
qrCode.append(ref.current);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
qrCode.update({
|
||||
data: url,
|
||||
});
|
||||
}, [url]);
|
||||
|
||||
const handleCreateAccount = async () => {
|
||||
const response = await registerUser(username, password);
|
||||
if (response.status === 'success') {
|
||||
setActiveStep(1);
|
||||
} else {
|
||||
setOpen(true);
|
||||
setMessage(response.status);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (activeStep === 1) {
|
||||
handleGenerateVerificationCode(username);
|
||||
setUrl(`https://t.me/popa_popa_popa_bot?start=${username}`);
|
||||
|
||||
while (ref.current.firstChild) {
|
||||
ref.current.removeChild(ref.current.firstChild);
|
||||
}
|
||||
|
||||
const newQrCode = new QRCodeStyling({
|
||||
width: 300,
|
||||
height: 300,
|
||||
image: popalogo,
|
||||
data: 'https://t.me/popa_popa_popa_bot?start=test',
|
||||
shape: 'square',
|
||||
margin: 10,
|
||||
dotsOptions: {
|
||||
gradient: {
|
||||
type: 'linear',
|
||||
colorStops: [
|
||||
{
|
||||
offset: 0,
|
||||
color: 'rgb(242,113,33)',
|
||||
},
|
||||
{
|
||||
offset: 1,
|
||||
color: 'rgb(233,64,87)',
|
||||
},
|
||||
],
|
||||
},
|
||||
type: 'extra-rounded',
|
||||
},
|
||||
imageOptions: {
|
||||
crossOrigin: 'anonymous',
|
||||
margin: 20,
|
||||
imageSize: 0.5,
|
||||
},
|
||||
backgroundOptions: {
|
||||
color: 'transparent',
|
||||
},
|
||||
});
|
||||
|
||||
newQrCode.update({
|
||||
data: `https://t.me/popa_popa_popa_bot?start=${username}`,
|
||||
});
|
||||
|
||||
setUrl(`https://t.me/popa_popa_popa_bot?start=${username}`);
|
||||
|
||||
newQrCode.append(ref.current);
|
||||
|
||||
const intervalId = setInterval(() => {
|
||||
handleVerifyCode();
|
||||
}, 5000);
|
||||
|
||||
return () => {
|
||||
clearInterval(intervalId);
|
||||
};
|
||||
}
|
||||
}, [activeStep]);
|
||||
|
||||
const handleGenerateVerificationCode = async (username: string) => {
|
||||
console.log(username);
|
||||
const response = await generateVerificationCode(username);
|
||||
setVerificationCode(response.code);
|
||||
};
|
||||
|
||||
const handleVerifyCode = async () => {
|
||||
const response = await getVerificationStatus(username);
|
||||
if (response.is_verified) {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenBot = () => {
|
||||
window.open(`https://t.me/popa_popa_popa_bot?start=${username}`, '_blank');
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
<Stepper
|
||||
activeStep={activeStep}
|
||||
alternativeLabel
|
||||
connector={<ColorlibConnector />}
|
||||
>
|
||||
{steps.map((label) => (
|
||||
<Step key={label}>
|
||||
<StepLabel
|
||||
sx={{
|
||||
'& .MuiStepLabel-label': {
|
||||
color: 'white',
|
||||
},
|
||||
'& .Mui-completed': {
|
||||
color: 'white !important',
|
||||
},
|
||||
'& .Mui-active': {
|
||||
backgroundImage:
|
||||
'linear-gradient( 136deg, rgb(242,113,33) 0%, rgb(233,64,87) 50%, rgb(138,35,135) 100%)',
|
||||
WebkitBackgroundClip: 'text',
|
||||
WebkitTextFillColor: 'transparent',
|
||||
},
|
||||
}}
|
||||
StepIconComponent={ColorlibStepIcon}
|
||||
>
|
||||
{label}
|
||||
</StepLabel>
|
||||
</Step>
|
||||
))}
|
||||
</Stepper>
|
||||
{activeStep === 0 && (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 2,
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6">Создание аккаунта</Typography>
|
||||
<Typography variant="body1">Введите ваш никнейм</Typography>
|
||||
<TextField
|
||||
required
|
||||
name="username"
|
||||
variant="outlined"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
sx={{
|
||||
width: '100%',
|
||||
// '& .MuiFormLabel-root': {
|
||||
// color: 'white',
|
||||
// },
|
||||
'& .MuiInputBase-input': {
|
||||
color: 'white',
|
||||
},
|
||||
'& .MuiInput-underline:after': {
|
||||
borderBottomColor: '#B2BAC2',
|
||||
},
|
||||
'& .MuiOutlinedInput-root': {
|
||||
'& fieldset': {
|
||||
borderColor: '#E0E3E7',
|
||||
color: 'white',
|
||||
},
|
||||
'&:hover fieldset': {
|
||||
borderColor: '#B2BAC2',
|
||||
},
|
||||
'&.Mui-focused fieldset': {
|
||||
borderColor: '#6F7E8C',
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<Typography variant="body1">Введите ваш пароль</Typography>
|
||||
<TextField
|
||||
required
|
||||
name="password"
|
||||
type="password"
|
||||
variant="outlined"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
sx={{
|
||||
width: '100%',
|
||||
// '& .MuiFormLabel-root': {
|
||||
// color: 'white',
|
||||
// },
|
||||
'& .MuiInputBase-input': {
|
||||
color: 'white',
|
||||
},
|
||||
'& .MuiInput-underline:after': {
|
||||
borderBottomColor: '#B2BAC2',
|
||||
},
|
||||
'& .MuiOutlinedInput-root': {
|
||||
'& fieldset': {
|
||||
borderColor: '#E0E3E7',
|
||||
color: 'white',
|
||||
},
|
||||
'&:hover fieldset': {
|
||||
borderColor: '#B2BAC2',
|
||||
},
|
||||
'&.Mui-focused fieldset': {
|
||||
borderColor: '#6F7E8C',
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="primary"
|
||||
sx={{ width: '100%', mt: 2 }}
|
||||
onClick={handleCreateAccount}
|
||||
>
|
||||
Создать
|
||||
</Button>
|
||||
</Box>
|
||||
)}
|
||||
{activeStep === 1 && (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 2,
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6">Откройте бота в телеграмме</Typography>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="primary"
|
||||
sx={{ width: '100%', mt: 2 }}
|
||||
onClick={handleOpenBot}
|
||||
>
|
||||
Открыть бота
|
||||
</Button>
|
||||
<div
|
||||
ref={ref}
|
||||
style={{
|
||||
minHeight: 300,
|
||||
}}
|
||||
/>
|
||||
<Typography variant="body1">
|
||||
Введите код верификации в боте
|
||||
</Typography>
|
||||
{verificationCode ? (
|
||||
<>
|
||||
<Typography
|
||||
variant="h2"
|
||||
sx={{
|
||||
backgroundImage:
|
||||
'linear-gradient( 136deg, rgb(242,113,33) 0%, rgb(233,64,87) 50%, rgb(138,35,135) 100%)',
|
||||
WebkitBackgroundClip: 'text',
|
||||
WebkitTextFillColor: 'transparent',
|
||||
}}
|
||||
>
|
||||
{verificationCode}
|
||||
</Typography>
|
||||
<Typography variant="body1">Ждем ответа от бота</Typography>
|
||||
<CircularProgress />
|
||||
</>
|
||||
) : (
|
||||
<CircularProgress />
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
<Snackbar
|
||||
open={open}
|
||||
autoHideDuration={6000}
|
||||
onClose={handleClose}
|
||||
message={message}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
};
|
130
src/renderer/pages/Shop.tsx
Normal file
130
src/renderer/pages/Shop.tsx
Normal file
@ -0,0 +1,130 @@
|
||||
import { Box } from '@mui/material';
|
||||
import { Typography } from '@mui/material';
|
||||
import CapeCard from '../components/CapeCard';
|
||||
import {
|
||||
Cape,
|
||||
fetchCapes,
|
||||
fetchCapesStore,
|
||||
purchaseCape,
|
||||
StoreCape,
|
||||
} from '../api';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export default function Shop() {
|
||||
const [storeCapes, setStoreCapes] = useState<StoreCape[]>([]);
|
||||
const [userCapes, setUserCapes] = useState<Cape[]>([]);
|
||||
const [username, setUsername] = useState<string>('');
|
||||
const [uuid, setUuid] = useState<string>('');
|
||||
const [loading, setLoading] = useState<boolean>(false);
|
||||
|
||||
// Функция для загрузки плащей из магазина
|
||||
const loadStoreCapes = async () => {
|
||||
try {
|
||||
const capes = await fetchCapesStore();
|
||||
setStoreCapes(capes);
|
||||
} catch (error) {
|
||||
console.error('Ошибка при получении плащей магазина:', error);
|
||||
setStoreCapes([]);
|
||||
}
|
||||
};
|
||||
|
||||
// Функция для загрузки плащей пользователя
|
||||
const loadUserCapes = async (username: string) => {
|
||||
try {
|
||||
const userCapes = await fetchCapes(username);
|
||||
setUserCapes(userCapes);
|
||||
} catch (error) {
|
||||
console.error('Ошибка при получении плащей пользователя:', error);
|
||||
setUserCapes([]);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePurchaseCape = async (cape_id: string) => {
|
||||
try {
|
||||
await purchaseCape(username, cape_id);
|
||||
await loadUserCapes(username);
|
||||
} catch (error) {
|
||||
console.error('Ошибка при покупке плаща:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Загружаем данные при монтировании
|
||||
useEffect(() => {
|
||||
const savedConfig = localStorage.getItem('launcher_config');
|
||||
if (savedConfig) {
|
||||
const config = JSON.parse(savedConfig);
|
||||
if (config.uuid && config.username) {
|
||||
setUsername(config.username);
|
||||
setUuid(config.uuid);
|
||||
|
||||
setLoading(true);
|
||||
|
||||
// Загружаем оба списка плащей
|
||||
Promise.all([loadStoreCapes(), loadUserCapes(config.username)]).finally(
|
||||
() => {
|
||||
setLoading(false);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Фильтруем плащи, которые уже куплены пользователем
|
||||
const availableCapes = storeCapes.filter(
|
||||
(storeCape) =>
|
||||
!userCapes.some((userCape) => userCape.cape_id === storeCape.id),
|
||||
);
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '2vw',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
}}
|
||||
>
|
||||
{loading ? (
|
||||
<Typography>Загрузка...</Typography>
|
||||
) : (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
flexWrap: 'wrap',
|
||||
alignContent: 'flex-start',
|
||||
width: '90%',
|
||||
height: '80%',
|
||||
gap: '2vw',
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6">Доступные плащи</Typography>
|
||||
{availableCapes.length > 0 ? (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'row',
|
||||
gap: '2vw',
|
||||
flexWrap: 'wrap',
|
||||
}}
|
||||
>
|
||||
{availableCapes.map((cape) => (
|
||||
<CapeCard
|
||||
key={cape.id}
|
||||
cape={cape}
|
||||
mode="shop"
|
||||
onAction={handlePurchaseCape}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
) : (
|
||||
<Typography>У вас уже есть все доступные плащи!</Typography>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
394
src/renderer/pages/VersionsExplorer.tsx
Normal file
394
src/renderer/pages/VersionsExplorer.tsx
Normal file
@ -0,0 +1,394 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
Grid,
|
||||
Card,
|
||||
CardMedia,
|
||||
CardContent,
|
||||
CardActions,
|
||||
Button,
|
||||
CircularProgress,
|
||||
Modal,
|
||||
List,
|
||||
ListItem,
|
||||
ListItemText,
|
||||
IconButton,
|
||||
} from '@mui/material';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import AddIcon from '@mui/icons-material/Add';
|
||||
import DownloadIcon from '@mui/icons-material/Download';
|
||||
|
||||
interface VersionCardProps {
|
||||
id: string;
|
||||
name: string;
|
||||
imageUrl: string;
|
||||
version: string;
|
||||
onSelect: (id: string) => void;
|
||||
}
|
||||
|
||||
const VersionCard: React.FC<VersionCardProps> = ({
|
||||
id,
|
||||
name,
|
||||
imageUrl,
|
||||
version,
|
||||
onSelect,
|
||||
}) => {
|
||||
return (
|
||||
<Card
|
||||
sx={{
|
||||
backgroundColor: 'rgba(30, 30, 50, 0.8)',
|
||||
backdropFilter: 'blur(10px)',
|
||||
width: '35vw',
|
||||
height: '35vh',
|
||||
minWidth: 'unset',
|
||||
minHeight: 'unset',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
borderRadius: '16px',
|
||||
boxShadow: '0 8px 32px rgba(0, 0, 0, 0.3)',
|
||||
transition: 'transform 0.3s, box-shadow 0.3s',
|
||||
overflow: 'hidden',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
onClick={() => onSelect(id)}
|
||||
>
|
||||
<CardContent
|
||||
sx={{
|
||||
flexGrow: 1,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
height: '10%',
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
gutterBottom
|
||||
variant="h5"
|
||||
component="div"
|
||||
sx={{
|
||||
fontWeight: 'bold',
|
||||
color: '#ffffff',
|
||||
fontSize: '1.5rem',
|
||||
}}
|
||||
>
|
||||
{name}
|
||||
</Typography>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
interface VersionInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
imageUrl?: string;
|
||||
config?: {
|
||||
downloadUrl: string;
|
||||
apiReleaseUrl: string;
|
||||
versionFileName: string;
|
||||
packName: string;
|
||||
memory: number;
|
||||
baseVersion: string;
|
||||
serverIp: string;
|
||||
fabricVersion: string;
|
||||
preserveFiles: string[];
|
||||
};
|
||||
}
|
||||
|
||||
interface AvailableVersionInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
imageUrl?: string;
|
||||
config: {
|
||||
downloadUrl: string;
|
||||
apiReleaseUrl: string;
|
||||
versionFileName: string;
|
||||
packName: string;
|
||||
memory: number;
|
||||
baseVersion: string;
|
||||
serverIp: string;
|
||||
fabricVersion: string;
|
||||
preserveFiles: string[];
|
||||
};
|
||||
}
|
||||
|
||||
// В компоненте VersionsExplorer
|
||||
export const VersionsExplorer = () => {
|
||||
const [installedVersions, setInstalledVersions] = useState<VersionInfo[]>([]);
|
||||
const [availableVersions, setAvailableVersions] = useState<
|
||||
AvailableVersionInfo[]
|
||||
>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [downloadLoading, setDownloadLoading] = useState<string | null>(null);
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
const fetchVersions = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
// Получаем список установленных версий через IPC
|
||||
const installedResult = await window.electron.ipcRenderer.invoke(
|
||||
'get-installed-versions',
|
||||
);
|
||||
if (installedResult.success) {
|
||||
setInstalledVersions(installedResult.versions);
|
||||
}
|
||||
|
||||
// Получаем доступные версии с GitHub Gist
|
||||
const availableResult = await window.electron.ipcRenderer.invoke(
|
||||
'get-available-versions',
|
||||
{
|
||||
gistUrl:
|
||||
'https://gist.githubusercontent.com/DIKER0K/06cd12fb3a4d08b1f0f8c763a7d05e06/raw/versions.json',
|
||||
},
|
||||
);
|
||||
if (availableResult.success) {
|
||||
setAvailableVersions(availableResult.versions);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при загрузке версий:', error);
|
||||
// Можно добавить обработку ошибки, например показать уведомление
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchVersions();
|
||||
}, []);
|
||||
|
||||
const handleSelectVersion = (version: VersionInfo) => {
|
||||
localStorage.setItem(
|
||||
'selected_version_config',
|
||||
JSON.stringify(version.config || {}),
|
||||
);
|
||||
navigate(`/launch/${version.id}`);
|
||||
};
|
||||
|
||||
const handleAddVersion = () => {
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const handleCloseModal = () => {
|
||||
setModalOpen(false);
|
||||
};
|
||||
|
||||
const handleDownloadVersion = async (version: AvailableVersionInfo) => {
|
||||
try {
|
||||
setDownloadLoading(version.id);
|
||||
|
||||
// Скачивание и установка выбранной версии
|
||||
const downloadResult = await window.electron.ipcRenderer.invoke(
|
||||
'download-and-extract',
|
||||
{
|
||||
downloadUrl: version.config.downloadUrl,
|
||||
apiReleaseUrl: version.config.apiReleaseUrl,
|
||||
versionFileName: version.config.versionFileName,
|
||||
packName: version.id,
|
||||
preserveFiles: version.config.preserveFiles || [],
|
||||
},
|
||||
);
|
||||
|
||||
if (downloadResult?.success) {
|
||||
// Добавляем скачанную версию в список установленных
|
||||
setInstalledVersions((prev) => [...prev, version]);
|
||||
setModalOpen(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Ошибка при скачивании версии ${version.id}:`, error);
|
||||
} finally {
|
||||
setDownloadLoading(null);
|
||||
}
|
||||
};
|
||||
|
||||
// Карточка добавления новой версии
|
||||
const AddVersionCard = () => (
|
||||
<Card
|
||||
sx={{
|
||||
backgroundColor: 'rgba(30, 30, 50, 0.8)',
|
||||
backdropFilter: 'blur(10px)',
|
||||
width: '35vw',
|
||||
height: '35vh',
|
||||
minWidth: 'unset',
|
||||
minHeight: 'unset',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
borderRadius: '16px',
|
||||
boxShadow: '0 8px 32px rgba(0, 0, 0, 0.3)',
|
||||
transition: 'transform 0.3s, box-shadow 0.3s',
|
||||
overflow: 'hidden',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
onClick={handleAddVersion}
|
||||
>
|
||||
<AddIcon sx={{ fontSize: 60, color: '#fff' }} />
|
||||
<Typography
|
||||
variant="h6"
|
||||
sx={{
|
||||
color: '#fff',
|
||||
}}
|
||||
>
|
||||
Добавить
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="h6"
|
||||
sx={{
|
||||
color: '#fff',
|
||||
}}
|
||||
>
|
||||
версию
|
||||
</Typography>
|
||||
</Card>
|
||||
);
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
paddingLeft: '5vw',
|
||||
paddingRight: '5vw',
|
||||
}}
|
||||
>
|
||||
{loading ? (
|
||||
<Box display="flex" justifyContent="center" my={5}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
) : (
|
||||
<Grid
|
||||
container
|
||||
spacing={3}
|
||||
sx={{
|
||||
width: '100%',
|
||||
overflowY: 'auto',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
{/* Показываем установленные версии или дефолтную, если она есть */}
|
||||
{installedVersions.length > 0 ? (
|
||||
installedVersions.map((version) => (
|
||||
<Grid
|
||||
key={version.id}
|
||||
size={{ xs: 'auto', sm: 'auto', md: 'auto' }}
|
||||
>
|
||||
<VersionCard
|
||||
id={version.id}
|
||||
name={version.name}
|
||||
imageUrl={
|
||||
version.imageUrl ||
|
||||
'https://via.placeholder.com/300x140?text=Minecraft'
|
||||
}
|
||||
version={version.version}
|
||||
onSelect={() => handleSelectVersion(version)}
|
||||
/>
|
||||
</Grid>
|
||||
))
|
||||
) : (
|
||||
// Если нет ни одной версии, показываем карточку добавления
|
||||
<Grid size={{ xs: 'auto', sm: 'auto', md: 'auto' }}>
|
||||
<AddVersionCard />
|
||||
</Grid>
|
||||
)}
|
||||
|
||||
{/* Всегда добавляем карточку для добавления новых версий */}
|
||||
{installedVersions.length > 0 && (
|
||||
<Grid size={{ xs: 'auto', sm: 'auto', md: 'auto' }}>
|
||||
<AddVersionCard />
|
||||
</Grid>
|
||||
)}
|
||||
</Grid>
|
||||
)}
|
||||
|
||||
{/* Модальное окно для выбора версии для скачивания */}
|
||||
<Modal
|
||||
open={modalOpen}
|
||||
onClose={handleCloseModal}
|
||||
aria-labelledby="modal-versions"
|
||||
aria-describedby="modal-available-versions"
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
top: '50%',
|
||||
left: '50%',
|
||||
transform: 'translate(-50%, -50%)',
|
||||
width: 400,
|
||||
maxHeight: '80vh',
|
||||
overflowY: 'auto',
|
||||
background: 'linear-gradient(45deg, #000000 10%, #3b4187 184.73%)',
|
||||
border: '2px solid #000',
|
||||
boxShadow: 24,
|
||||
p: 4,
|
||||
borderRadius: '3vw',
|
||||
gap: '1vh',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
backdropFilter: 'blur(10px)',
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6" component="h2" sx={{ color: '#fff' }}>
|
||||
Доступные версии для скачивания
|
||||
</Typography>
|
||||
|
||||
{availableVersions.length === 0 ? (
|
||||
<Typography sx={{ color: '#fff', mt: 2 }}>
|
||||
Загрузка доступных версий...
|
||||
</Typography>
|
||||
) : (
|
||||
<List sx={{ mt: 2 }}>
|
||||
{availableVersions.map((version) => (
|
||||
<ListItem
|
||||
key={version.id}
|
||||
sx={{
|
||||
borderRadius: '8px',
|
||||
mb: 1,
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.1)',
|
||||
cursor: 'pointer',
|
||||
'&:hover': {
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.2)',
|
||||
},
|
||||
}}
|
||||
onClick={() => handleSelectVersion(version)}
|
||||
>
|
||||
<ListItemText
|
||||
primary={version.name}
|
||||
secondary={version.version}
|
||||
primaryTypographyProps={{ color: '#fff' }}
|
||||
secondaryTypographyProps={{
|
||||
color: 'rgba(255,255,255,0.7)',
|
||||
}}
|
||||
/>
|
||||
</ListItem>
|
||||
))}
|
||||
</List>
|
||||
)}
|
||||
|
||||
<Button
|
||||
onClick={handleCloseModal}
|
||||
variant="outlined"
|
||||
sx={{
|
||||
mt: 3,
|
||||
alignSelf: 'center',
|
||||
borderColor: '#fff',
|
||||
color: '#fff',
|
||||
'&:hover': {
|
||||
borderColor: '#ccc',
|
||||
backgroundColor: 'rgba(255,255,255,0.1)',
|
||||
},
|
||||
}}
|
||||
>
|
||||
Закрыть
|
||||
</Button>
|
||||
</Box>
|
||||
</Modal>
|
||||
</Box>
|
||||
);
|
||||
};
|
128
src/renderer/utils/playerOnlineCheck.ts
Normal file
128
src/renderer/utils/playerOnlineCheck.ts
Normal file
@ -0,0 +1,128 @@
|
||||
import { fetchActiveServers, fetchOnlinePlayers, Server } from '../api';
|
||||
|
||||
/**
|
||||
* Проверяет, находится ли указанный игрок онлайн на любом из серверов
|
||||
* @param username Имя игрока для проверки
|
||||
* @returns {Promise<boolean>} true, если игрок онлайн хотя бы на одном сервере
|
||||
*/
|
||||
export async function isPlayerOnline(username: string): Promise<boolean> {
|
||||
try {
|
||||
console.log('Начинаем проверку статуса для:', username);
|
||||
|
||||
// Получаем список активных серверов (теперь это массив)
|
||||
const servers = await fetchActiveServers();
|
||||
console.log('Ответ API активных серверов:', servers);
|
||||
|
||||
// Фильтруем серверы с игроками
|
||||
const serversWithPlayers = servers.filter(
|
||||
(server) => server.online_players > 0,
|
||||
);
|
||||
|
||||
// Если нет серверов с игроками, игрок точно не онлайн
|
||||
if (serversWithPlayers.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Проверяем каждый сервер на наличие игрока
|
||||
const checkPromises = serversWithPlayers.map(async (server) => {
|
||||
try {
|
||||
const onlinePlayers = await fetchOnlinePlayers(server.id);
|
||||
|
||||
// Проверяем, есть ли игрок с указанным именем в списке
|
||||
// Предполагая, что онлайн игроки хранятся в массиве online_players
|
||||
return (
|
||||
Array.isArray(onlinePlayers.online_players) &&
|
||||
onlinePlayers.online_players.some(
|
||||
(player) => player.username === username,
|
||||
)
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(`Ошибка при проверке сервера ${server.id}:`, error);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
// Ожидаем результаты всех проверок
|
||||
const results = await Promise.all(checkPromises);
|
||||
|
||||
// Игрок онлайн, если хотя бы одна проверка вернула true
|
||||
return results.some((result) => result);
|
||||
} catch (error) {
|
||||
console.error('Ошибка при проверке онлайн-статуса игрока:', error);
|
||||
return false; // В случае ошибки считаем, что игрок не онлайн
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, находится ли указанный игрок онлайн на конкретном сервере
|
||||
* @param username Имя игрока для проверки
|
||||
* @param serverId ID сервера для проверки
|
||||
* @returns {Promise<boolean>} true, если игрок онлайн на указанном сервере
|
||||
*/
|
||||
export async function isPlayerOnlineOnServer(
|
||||
username: string,
|
||||
serverId: string,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const onlinePlayers = await fetchOnlinePlayers(serverId);
|
||||
|
||||
return (
|
||||
Array.isArray(onlinePlayers.online_players) &&
|
||||
onlinePlayers.online_players.some(
|
||||
(player) => player.username === username,
|
||||
)
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(`Ошибка при проверке игрока на сервере ${serverId}:`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, на каком сервере находится игрок
|
||||
* @param username Имя игрока для проверки
|
||||
* @returns Объект с информацией: онлайн ли игрок и на каком сервере
|
||||
*/
|
||||
export async function getPlayerServer(
|
||||
username: string,
|
||||
): Promise<{ online: boolean; server: Server | null }> {
|
||||
try {
|
||||
// Получаем список активных серверов
|
||||
const servers = await fetchActiveServers();
|
||||
|
||||
// Фильтруем серверы с игроками
|
||||
const serversWithPlayers = servers.filter(
|
||||
(server) => server.online_players > 0,
|
||||
);
|
||||
|
||||
// Если нет серверов с игроками, игрок точно не онлайн
|
||||
if (serversWithPlayers.length === 0) {
|
||||
return { online: false, server: null };
|
||||
}
|
||||
|
||||
// Проверяем каждый сервер на наличие игрока
|
||||
for (const server of serversWithPlayers) {
|
||||
try {
|
||||
const onlinePlayers = await fetchOnlinePlayers(server.id);
|
||||
|
||||
if (
|
||||
Array.isArray(onlinePlayers.online_players) &&
|
||||
onlinePlayers.online_players.some(
|
||||
(player) => player.username === username,
|
||||
)
|
||||
) {
|
||||
// Игрок найден на этом сервере
|
||||
return { online: true, server };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Ошибка при проверке сервера ${server.id}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// Игрок не найден ни на одном сервере
|
||||
return { online: false, server: null };
|
||||
} catch (error) {
|
||||
console.error('Ошибка при проверке сервера игрока:', error);
|
||||
return { online: false, server: null };
|
||||
}
|
||||
}
|
@ -1,5 +1,6 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"useUnknownInCatchVariables": false,
|
||||
"incremental": true,
|
||||
"target": "es2022",
|
||||
"module": "node16",
|
||||
|
Reference in New Issue
Block a user