Skip to content

Commit

Permalink
WIP logo/terminal stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
TheArcaneBrony committed Oct 30, 2024
1 parent a4a70cf commit 70cbd7d
Show file tree
Hide file tree
Showing 15 changed files with 1,552 additions and 26 deletions.
Binary file added assets/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions src/api/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,15 @@ try {
}

if (cluster.isPrimary && process.env.NODE_ENV == "production") {
console.log(`Primary ${process.pid} is running`);
console.log(`Primary PID: ${process.pid}`);

// Fork workers.
for (let i = 0; i < cores; i++) {
cluster.fork();
}

cluster.on("exit", (worker) => {
console.log(`worker ${worker.process.pid} died, restart worker`);
console.log(`Worker ${worker.process.pid} died, restarting worker`);
cluster.fork();
});
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/bundle/Server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ async function main() {

Sentry.errorHandler(app);

console.log(`[Server] ${green(`listening on port ${bold(port)}`)}`);
console.log(`[Server] ${green(`Listening on port ${bold(port)}`)}`);
}

main().catch(console.error);
35 changes: 17 additions & 18 deletions src/bundle/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

// process.env.MONGOMS_DEBUG = "true";
import moduleAlias from "module-alias";

moduleAlias(__dirname + "../../../package.json");

import "reflect-metadata";
Expand All @@ -26,8 +27,10 @@ import os from "os";
import { red, bold, yellow, cyan } from "picocolors";
import { initStats } from "./stats";
import { config } from "dotenv";

config();
import { execSync } from "child_process";
import { centerString, Logo } from "@spacebar/util";

const cores = process.env.THREADS ? parseInt(process.env.THREADS) : 1;

Expand All @@ -41,23 +44,19 @@ function getCommitOrFail() {

if (cluster.isPrimary) {
const commit = getCommitOrFail();

Logo.printLogo();
console.log(
bold(`
███████╗██████╗ █████╗ ██████╗███████╗██████╗ █████╗ ██████╗
██╔════╝██╔══██╗██╔══██╗██╔════╝██╔════╝██╔══██╗██╔══██╗██╔══██╗
███████╗██████╔╝███████║██║ █████╗ ██████╔╝███████║██████╔╝
╚════██║██╔═══╝ ██╔══██║██║ ██╔══╝ ██╔══██╗██╔══██║██╔══██╗
███████║██║ ██║ ██║╚██████╗███████╗██████╔╝██║ ██║██║ ██║
╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝
spacebar-server | ${yellow(
`Pre-release (${
commit !== null
? commit.slice(0, 7)
: "Unknown (Git cannot be found)"
})`,
)}
${centerString(
`spacebar-server | ${yellow(
`Pre-release (${
commit !== null
? commit.slice(0, 7)
: "Unknown (Git cannot be found)"
})`,
)}`,
64,
)}
Commit Hash: ${
commit !== null
Expand All @@ -74,7 +73,7 @@ Cores: ${cyan(os.cpus().length)} (Using ${cores} thread(s).)

initStats();

console.log(`[Process] starting with ${cores} threads`);
console.log(`[Process] Starting with ${cores} threads`);

if (cores === 1) {
require("./Server");
Expand All @@ -87,7 +86,7 @@ Cores: ${cyan(os.cpus().length)} (Using ${cores} thread(s).)
const delay = process.env.DATABASE?.includes("://") ? 0 : i * 1000;
setTimeout(() => {
cluster.fork();
console.log(`[Process] worker ${cyan(i)} started.`);
console.log(`[Process] Worker ${cyan(i)} started.`);
}, delay);
}

Expand All @@ -102,7 +101,7 @@ Cores: ${cyan(os.cpus().length)} (Using ${cores} thread(s).)
cluster.on("exit", (worker) => {
console.log(
`[Worker] ${red(
`died with PID: ${worker.process.pid} , restarting ...`,
`PID ${worker.process.pid} died, restarting ...`,
)}`,
);
cluster.fork();
Expand Down
36 changes: 31 additions & 5 deletions src/bundle/stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,44 @@

import os from "os";
import osu from "node-os-utils";
import { readFileSync } from "node:fs";
import { red } from "picocolors";

export function initStats() {
console.log(`[Path] running in ${__dirname}`);
console.log(`[Path] Running in ${process.cwd()}`);
console.log(`[Path] Running from ${__dirname}`);
try {
console.log(`[CPU] ${osu.cpu.model()} Cores x${osu.cpu.count()}`);
console.log(`[CPU] ${osu.cpu.model()} (x${osu.cpu.count()})`);
} catch {
console.log("[CPU] Failed to get cpu model!");
console.log("[CPU] Failed to get CPU model!");
}

console.log(`[System] ${os.platform()} ${os.arch()}`);
console.log(`[Process] running with PID: ${process.pid}`);
console.log(`[System] ${os.platform()} ${os.release()} ${os.arch()}`);
if (os.platform() == "linux") {
try {
const osReleaseLines = readFileSync(
"/etc/os-release",
"utf8",
).split("\n");
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
const osRelease: any = {};
for (const line of osReleaseLines) {
if (!line) continue;
const [key, value] = line.match(/(.*?)="?([^"]*)"?/)!.slice(1);
osRelease[key] = value;
}
console.log(
`[System]\x1b[${osRelease.ANSI_COLOR}m ${osRelease.NAME ?? "Unknown"} ${osRelease.VERSION ?? "Unknown"} (${osRelease.BUILD_ID ?? "No build ID"})\x1b[0m`,
);
} catch (e) {
console.log(
"[System] Unknown Linux distribution (missing /etc/os-release)",
);
console.log(e);
}
}
console.log(`[Process] Running with PID: ${process.pid}`);
if (process.getuid && process.getuid() === 0) {
console.warn(
red(
Expand Down
141 changes: 141 additions & 0 deletions src/util/util/KittyLogo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import { readFileSync } from "node:fs";
import fs from "fs";

var util = require("util");

// noinspection ES6ConvertRequireIntoImport
// const ioctl = require("ioctl");
// import ref from "ref";
// import ArrayType from "ref-array";
// import StructType from "ref-struct";
// import os from "os";

// const winsize = StructType({
// ws_row : ref.types.ushort,
// ws_col : ref.types.ushort,
// ws_xpixel : ref.types.ushort,
// ws_ypixel : ref.types.ushort
// });

// const originalConsoleLog = console.log;
// console.error =
// console.log =
// console.debug =
// function (message: object, ...optionalParams: object[]) {
// KittyLogo.printWithIcon(message + " " + optionalParams.join(" "));
// };

export class KittyLogo {
public static printLogo(): void {
const data = readFileSync(__dirname + "/../../../assets/logo.png", {
encoding: "base64",
});
KittyLogo.writeImage({
base64Data: data,
width: 70,
addNewline: true,
});
}

public static printWithIcon(text?: string): void {
if (text) {
const lines = text.split("\n");
for (const line of lines) {
this.writeIcon();
process.stdout.write(" " + line + "\n");
}
}
}

private static writeIcon(): void {
const data = readFileSync(__dirname + "/../../../assets/icon.png", {
encoding: "base64",
});
KittyLogo.writeImage({
base64Data: data,
width: 2,
addNewline: false,
});
}

private static checkSupport(cb: void): boolean {
process.stdin.setEncoding("utf8");
process.stdin.setRawMode(true);
let resp = "";
process.stdin.once("data", function (key) {
console.log(util.inspect(key));
process.stdin.setRawMode(false);
process.stdin.pause();
resp = key.toString();
});
process.stdout.write(
"\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\\x1b[c",
);

while(resp == "") {
console.log("waiting");
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1000);
}

return false;
}

// private static sleep(ms: number): void {
// Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
// }

private static writeImage(request: KittyImageMetadata): void {
if (this.checkSupport()) return;
let pngData = request.base64Data;

// Ga=T,q=2,o=z,s=1022,v=181,X=5;
const chunkSize = 1024;

//#region Header
let header = `\x1b_G`; // enable graphics
header += "a=T"; // action = transmit & display
header += ",q=2"; // suppress response
header += ",f=100"; // image format = png
header += ",t=d"; // transmission = direct
header += ",x=0"; // current x position
header += ",y=0"; // current y position
if (request.width) header += `,c=${request.width}`; // width (columns)
if (request.height) header += `,r=${request.height}`; // height (rows)
if (request.widthPixels) header += `,w=${request.widthPixels}`; // width (pixels)
if (request.heightPixels) header += `,h=${request.heightPixels}`; // height (pixels)
//#endregion

while (pngData.length > 0) {
const dataSize = Math.min(pngData.length, chunkSize);

process.stdout.write(
header + `,m=${dataSize == chunkSize ? 1 : 0};`,
);
process.stdout.write(pngData.slice(0, chunkSize));
pngData = pngData.slice(chunkSize);
process.stdout.write("\x1b\\");
}

if (request.addNewline) process.stdout.write("\n");
}
}

export class KittyImageMetadata {
public base64Data: string;
public width?: number;
public height?: number;
public widthPixels?: number;
public heightPixels?: number;
public addNewline?: boolean;
}

KittyLogo.printLogo();

//
// for (let i = 0; i < 10; i++) {
// KittyLogo.printLogo();
// }
// for (let i = 0; i < 10; i++) {
//
// console.log(" ".repeat(i)+"meow");
// }
55 changes: 55 additions & 0 deletions src/util/util/Logo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { execSync } from "child_process";
import findOnPath from "./os-utils/OsUtils";
// noinspection ES6ConvertRequireIntoImport
import terminfo from "./os-utils/TermInfo/TermInfo";
import { KittyLogo } from "./KittyLogo";


export class Logo {
public static printLogo() {
KittyLogo.printLogo();
// const chafaPath = findOnPath("chafa");
// console.log("Chafa path: " + chafaPath);
// const info = terminfo.parse({debug: true});
// process.exit(0);
return;
// console.log(info);
// if (chafaPath)
// return execSync(
// "chafa Spacebar__Logo-Blue.png -s 70",
// {
// env: process.env,
// encoding: "utf-8",
// stdio: "inherit"
// }
// );
// else console.log(Logo.logoVersions["1"] as string);
}

private static getConsoleColors(): number {
return 1;
if (!process.env.TERM) return 1;
else {
switch (process.env.TERM) {
case "":
break;

default:
break;
}
}
return 1;
}
private static logoVersions: any = {
"1": `
███████╗██████╗ █████╗ ██████╗███████╗██████╗ █████╗ ██████╗
██╔════╝██╔══██╗██╔══██╗██╔════╝██╔════╝██╔══██╗██╔══██╗██╔══██╗
███████╗██████╔╝███████║██║ █████╗ ██████╔╝███████║██████╔╝
╚════██║██╔═══╝ ██╔══██║██║ ██╔══╝ ██╔══██╗██╔══██║██╔══██╗
███████║██║ ██║ ██║╚██████╗███████╗██████╔╝██║ ██║██║ ██║
╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝`,
"2": ``
};
}

Logo.printLogo();
6 changes: 6 additions & 0 deletions src/util/util/String.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,9 @@ export function trimSpecial(str?: string): string {
if (!str) return "";
return str.replace(SPECIAL_CHAR, "").trim();
}

export function centerString(str: string, len: number): string {
const pad = len - str.length;
const padLeft = Math.floor(pad / 2) + str.length;
return str.padStart(padLeft).padEnd(len);
}
1 change: 1 addition & 0 deletions src/util/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,4 @@ export * from "./TraverseDirectory";
export * from "./WebAuthn";
export * from "./Gifs";
export * from "./Application";
export * from "./Logo";
21 changes: 21 additions & 0 deletions src/util/util/os-utils/OsUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { existsSync, statSync } from "fs";
import os from "os";

export default function findOnPath(binary: string): string | null {
const paths =
(os.platform() == "win32"
? process.env.PATH?.split(";")
: process.env.PATH?.split(":")) || [];

if (os.platform() == "win32") {
binary += ".exe";
}

for (const path of paths) {
if (existsSync(`${path}/${binary}`)) {
const stat = statSync(`${path}/${binary}`);
if (stat.isFile() && stat.mode & 0o111) return `${path}/${binary}`;
}
}
return null;
}
Loading

0 comments on commit 70cbd7d

Please sign in to comment.