Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature counters manager #65

Merged
merged 26 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
10f7d3e
feat: Switch from `unzipper` to `adm-zip`
cyperdark Feb 21, 2024
f7aeba9
fix: Add encoding to responses
cyperdark Feb 21, 2024
0d52588
fix: Remove download bar after it's finished
cyperdark Feb 21, 2024
35face6
feat: Add pathname to request
cyperdark Feb 21, 2024
9d134af
feat: PP Counters Manager
cyperdark Feb 21, 2024
b5c9dc0
feat: add search to counters page
cyperdark Feb 21, 2024
f7f3d7a
feat: Add button to open counter folder
cyperdark Feb 21, 2024
326c825
fix: Fix closing old websocket connections
cyperdark Feb 21, 2024
9a97e64
fix: Iframe size fix + no counters message
cyperdark Feb 21, 2024
c4cf5e8
feat: Add body parsing for POST, PATCH, PUT requests
cyperdark Feb 22, 2024
11fea7b
feat: Show `config reloaded` message only on if settings was updated
cyperdark Feb 22, 2024
d667bcb
feat: Add settings page
cyperdark Feb 22, 2024
707793b
fix: Create file only when request is started
cyperdark Feb 22, 2024
ae5b874
fix: Sort files by date
cyperdark Feb 22, 2024
0f82b69
fix: .prettierignore
cyperdark Feb 22, 2024
6765241
fix: Host files localy
cyperdark Feb 22, 2024
33b4253
feat: Add header
cyperdark Feb 22, 2024
4518544
fix: Minor api fixes
cyperdark Feb 22, 2024
59c1741
feat: Instruction page
cyperdark Feb 28, 2024
6b2859b
change commi
cyperdark Feb 28, 2024
46b8458
chore: rebase
KotRikD Feb 28, 2024
a2922fc
feat: package htmls into production build
KotRikD Feb 28, 2024
4124294
fix: o7 unzipper
cyperdark Feb 28, 2024
1d0e4ea
fix: empty counters, missing option, delete local counter
cyperdark Feb 28, 2024
fd9a0cc
fix: Add error handle to main page
cyperdark Feb 28, 2024
8bd7840
fix: Add confirm menu for counter delete button
cyperdark Feb 28, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.vscode/
node_modules/
dist/
static/
static/
packages/server/assets/homepage.js
2 changes: 2 additions & 0 deletions packages/common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ export * from './utils/platforms';
export * from './utils/agruments';
export * from './utils/sleep';
export * from './utils/config';
export * from './utils/unzip';
export * from './utils/directories';
1 change: 1 addition & 0 deletions packages/common/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"build": "tsc"
},
"dependencies": {
"adm-zip": "^0.5.10",
"dotenv": "^16.0.3",
"winston": "^3.8.2"
}
Expand Down
49 changes: 36 additions & 13 deletions packages/common/utils/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import path from 'path';
import { configureLogger, wLogger } from './logger';

const configPath = path.join(
process.env.NODE_ENV === 'development'
? process.cwd()
: path.dirname(process.execPath),
'pkg' in process ? path.dirname(process.execPath) : process.cwd(),
'tsosu.env'
);
if (!fs.existsSync(configPath)) {
Expand Down Expand Up @@ -45,7 +43,8 @@ SERVER_IP=127.0.0.1
# The port on which the websocket api server will run
SERVER_PORT=24050
# The folder from which the overlays will be taken.
STATIC_FOLDER_PATH=./static`
STATIC_FOLDER_PATH=./static`,
'utf8'
);
}

Expand Down Expand Up @@ -107,7 +106,7 @@ export const updateConfigFile = () => {
}

if (!process.env.ENABLE_GOSU_OVERLAY) {
newOptions += 'nENABLE_GOSU_OVERLAY, ';
newOptions += 'ENABLE_GOSU_OVERLAY, ';
fs.appendFileSync(configPath, '\nENABLE_GOSU_OVERLAY=false', 'utf8');
}

Expand All @@ -127,6 +126,7 @@ export const watchConfigFile = ({ httpServer }: { httpServer: any }) => {
};

export const refreshConfig = (httpServer: any, refresh: boolean) => {
let updated = false;
const status = refresh == true ? 'reload' : 'load';

const { parsed, error } = dotenv.config({ path: configPath });
Expand All @@ -136,9 +136,26 @@ export const refreshConfig = (httpServer: any, refresh: boolean) => {
}

const debugLogging = (parsed.DEBUG_LOG || '') === 'true';

const serverIP = parsed.SERVER_IP || '127.0.0.1';
const serverPort = Number(parsed.SERVER_PORT || '24050');
const calculatePP = (parsed.CALCULATE_PP || '') === 'true';
const enableKeyOverlay = (parsed.ENABLE_KEY_OVERLAY || '') === 'true';
const pollRate = Number(parsed.POLL_RATE || '500');
const keyOverlayPollRate = Number(parsed.KEYOVERLAY_POLL_RATE || '100');
const staticFolderPath = parsed.STATIC_FOLDER_PATH || './static';
const enableGosuOverlay = (parsed.ENABLE_GOSU_OVERLAY || '') === 'true';

// determine whether config actually was updated or not
updated =
config.debugLogging != debugLogging ||
config.calculatePP != calculatePP ||
config.enableKeyOverlay != enableKeyOverlay ||
config.pollRate != pollRate ||
config.keyOverlayPollRate != keyOverlayPollRate ||
config.staticFolderPath != staticFolderPath ||
config.enableGosuOverlay != enableGosuOverlay ||
config.serverIP != serverIP ||
config.serverPort != serverPort;

if (config.serverIP != serverIP || config.serverPort != serverPort) {
config.serverIP = serverIP;
Expand All @@ -148,12 +165,13 @@ export const refreshConfig = (httpServer: any, refresh: boolean) => {
}

config.debugLogging = debugLogging;
config.calculatePP = (parsed.CALCULATE_PP || '') === 'true';
config.enableKeyOverlay = (parsed.ENABLE_KEY_OVERLAY || '') === 'true';
config.pollRate = Number(parsed.POLL_RATE || '500');
config.keyOverlayPollRate = Number(parsed.KEYOVERLAY_POLL_RATE || '100');
config.staticFolderPath = parsed.STATIC_FOLDER_PATH || './static';
config.enableGosuOverlay = (parsed.ENABLE_GOSU_OVERLAY || '') === 'true';
config.calculatePP = calculatePP;
config.enableKeyOverlay = enableKeyOverlay;
config.pollRate = pollRate >= 0 ? pollRate : 100;
config.keyOverlayPollRate =
keyOverlayPollRate >= 0 ? keyOverlayPollRate : 100;
config.staticFolderPath = staticFolderPath;
config.enableGosuOverlay = enableGosuOverlay;

if (
config.staticFolderPath == './static' &&
Expand All @@ -162,6 +180,11 @@ export const refreshConfig = (httpServer: any, refresh: boolean) => {
fs.mkdirSync(path.join(process.cwd(), 'static'));
}

wLogger.info(`Config ${status}ed`);
if (updated) wLogger.info(`Config ${status}ed`);
configureLogger();
};

export const writeConfig = (httpServer: any, text: string) => {
fs.writeFileSync(configPath, text, 'utf8');
refreshConfig(httpServer, true);
};
29 changes: 29 additions & 0 deletions packages/common/utils/directories.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import fs from 'fs';
import path from 'path';

export function recursiveFilesSearch({
dir,
filename,
fileList
}: {
dir: string;
filename: string;
fileList: { filePath: string; created: number }[];
}) {
const files = fs.readdirSync(dir);
files.forEach((file) => {
const filePath = path.join(dir, file);
const stats = fs.statSync(filePath);
if (stats.isDirectory()) {
recursiveFilesSearch({ dir: filePath, filename, fileList });
} else if (filePath.includes(filename)) {
const stats = fs.statSync(filePath);

fileList.push({ filePath, created: stats.mtimeMs });
}
});

fileList.sort((a, b) => a.created - b.created);

return fileList.map((r) => r.filePath);
}
27 changes: 14 additions & 13 deletions packages/common/utils/downloader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ const updateProgressBar = (progress: number): void => {
);

if (progress === 1) {
process.stdout.write('\n');
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
}
};

Expand All @@ -34,18 +35,6 @@ export const downloadFile = (
}
};

const file = fs.createWriteStream(destination);

file.on('error', (err) => {
fs.unlinkSync(destination);
reject(err);
});

file.on('finish', () => {
file.close();
resolve(destination);
});

// find url
https
.get(url, options, (response) => {
Expand All @@ -56,6 +45,18 @@ export const downloadFile = (
return;
}

const file = fs.createWriteStream(destination);

file.on('error', (err) => {
fs.unlinkSync(destination);
reject(err);
});

file.on('finish', () => {
file.close();
resolve(destination);
});

const totalSize = parseInt(
response.headers['content-length']!,
10
Expand Down
54 changes: 54 additions & 0 deletions packages/common/utils/unzip.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import AdmZip from 'adm-zip';
import fs from 'fs';
import path from 'path';

import { wLogger } from './logger';

export const unzipTosu = (
zipPath: string,
extractPath: string
): Promise<string> =>
new Promise((resolve, reject) => {
const zip = new AdmZip(zipPath);

zip.getEntries().some((entry) => {
if (entry.entryName === 'tosu' || entry.entryName === 'tosu.exe') {
const fileName = path.basename(entry.entryName);
const { name, ext } = path.parse(fileName);
const modifyName = path.join(extractPath, `${name}_new${ext}`);

return fs.writeFile(
modifyName,
entry.getData(),
{ flag: 'w' },
(err) => {
if (err) {
return reject(err);
}

return resolve(modifyName);
}
);
}
});

reject('No matching entry found in the zip file.');
});

export const unzip = (zipPath: string, extractPath: string): Promise<string> =>
new Promise((resolve, reject) => {
if (!fs.existsSync(extractPath)) {
fs.mkdirSync(extractPath);
}

const zip = new AdmZip(zipPath);

try {
// Extract all contents of the zip file to the specified destination
zip.extractAllTo(extractPath, /*overwrite*/ true);
resolve(extractPath);
} catch (error) {
wLogger.error((error as any).message);
reject(error);
}
});
56 changes: 56 additions & 0 deletions packages/server/assets/filesList.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<html>

<head>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap" rel="stylesheet">
<title>{PAGE_URL}</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
min-width: 0;
}

body {
font-size: 2.5em;
font-family: 'Roboto', sans-serif;
font-weight: 600;
color: #c9abae;
background: #110d0d;
}

ul {
margin: 30px;
list-style: decimal-leading-zero;
display: grid;
grid-template-columns: 25% 25% 25% 25%;
padding: 0;
}

li {
margin-left: 2em;
}

a {
color: #b5616b;
text-decoration: underline;
text-underline-offset: 6px;
transition: 0.2s ease;
transition-property: text-underline-offset, color;
overflow-wrap: break-word;
}

a:hover {
color: #c9abae;
text-underline-offset: 4px;
}
</style>
</head>

<body>
<ul id="overlays-list">{OVERLAYS_LIST}</ul>
</body>

</html>
51 changes: 51 additions & 0 deletions packages/server/assets/homepage.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<html>

<head>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,400;0,700;1,400;1,700&display=swap"
rel="stylesheet">

<link rel="stylesheet" href="/homepage.min.css">
<title>tosu dashboard</title>
<style>

</style>
</head>

<body>
<header class="flexer">
<a href="https://osuck.link/tosu" target="_blank" class="flexer github">
github
</a>
<div>‧</div>
<a href="https://osuck.link/tosu-discord" target="_blank" class="flexer discord">
discord
</a>
<a href="https://osuck.link/tosu-counter-submit" target="_blank" class="flexer indent-left sbmt">
submit pp counter
</a>
</header>
<main>
<div class="tabs flexer">
<a href="/?tab=0" class="tab-item">Installed</a>
<a href="/?tab=1" class="tab-item">Available</a>
<a href="/?tab=2" class="tab-item">Settings</a>
<a href="/?tab=3" class="tab-item">How to add counter</a>
<div class="indent-left">
<input class="search-bar" type="text" placeholder="search">
<!-- <a href="https://github.com/cyperdark/osu-counters/?tab=readme-ov-file#how-to-submit-pp-counter" target="_blank" class="button submit-button">Submit</a> -->
</div>
</div>
<div class="results">
{{LIST}}
</div>
</main>
<footer>
<span>created by </span><a href="https://osuck.net/" target="_blank">cyperdark</a>
</footer>
<script src="/homepage.js" defer></script>
</body>


</html>
2 changes: 2 additions & 0 deletions packages/server/assets/homepage.js

Large diffs are not rendered by default.

Loading
Loading