Skip to content

Commit

Permalink
websocket support improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
ewsgit committed Jun 19, 2024
1 parent 3ee6b3e commit 49c9284
Show file tree
Hide file tree
Showing 15 changed files with 90 additions and 86 deletions.
6 changes: 2 additions & 4 deletions applications/photos/web/routes/album/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,9 @@ import ButtonWithIcon from "@yourdash/uikit/components/buttonWithIcon/buttonWith
import Heading from "@yourdash/uikit/components/heading/heading.js";
import { UKIcon } from "@yourdash/uikit/components/icon/iconDictionary.js";
import IconButton from "@yourdash/uikit/components/iconButton/iconButton.js";
import useResource from "@yourdash/web/src/lib/useResource.js";
import useResource from "@yourdash/csi/useResource";
import { FC, useEffect, useState } from "react";
import EndpointMediaAlbumLargeGrid, {
MediaAlbumLargeGridItem,
} from "../../../shared/types/endpoints/media/album/large-grid.js";
import EndpointMediaAlbumLargeGrid, { MediaAlbumLargeGridItem } from "../../../shared/types/endpoints/media/album/large-grid.js";
import { useNavigate, useSearchParams } from "react-router-dom";
import path from "path-browserify";
import { MEDIA_TYPE } from "../../../shared/types/mediaType";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import csi from "@yourdash/csi/csi.js";
import Card from "@yourdash/uikit/components/card/card.js";
import Heading from "@yourdash/uikit/components/heading/heading.js";
import Text from "@yourdash/uikit/components/text/text.js";
import useResource from "@yourdash/web/src/lib/useResource.js";
import useResource from "@yourdash/csi/useResource";
import { FC } from "react";
import { Albums } from "../../../../shared/types/endpoints/albums";
import { useNavigate } from "react-router-dom";
Expand Down
2 changes: 1 addition & 1 deletion applications/photos/web/routes/search/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import csi from "@yourdash/csi/csi.js";
import { UKIcon } from "@yourdash/uikit/components/icon/iconDictionary.js";
import TextInput from "@yourdash/uikit/components/textInput/textInput.js";
import useResource from "@yourdash/web/src/lib/useResource.js";
import useResource from "@yourdash/csi/useResource";
import React, { FC } from "react";
import EndpointMediaSearch from "../../../shared/types/endpoints/media/search.js";
import Albums from "./components/albums.js";
Expand Down
2 changes: 1 addition & 1 deletion applications/photos/web/routes/view/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import Heading from "@yourdash/uikit/components/heading/heading.js";
import { UKIcon } from "@yourdash/uikit/components/icon/iconDictionary.js";
import IconButton from "@yourdash/uikit/components/iconButton/iconButton";
import PanAndZoom from "@yourdash/uikit/views/panAndZoom/panAndZoom.js";
import useResource from "@yourdash/web/src/lib/useResource.js";
import useResource from "@yourdash/csi/useResource";
import { FC } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import EndpointMediaRaw from "../../../shared/types/endpoints/media/album/raw.js";
Expand Down
2 changes: 1 addition & 1 deletion applications/settings/web/routes/cat/categoryName.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import csi from "@yourdash/csi/csi";
import Heading from "@yourdash/uikit/components/heading/heading";
import Spinner from "@yourdash/uikit/components/spinner/spinner";
import SidebarToggleButton from "@yourdash/uikit/views/sidebar/SidebarToggleButton";
import useResource from "@yourdash/web/src/lib/useResource";
import useResource from "@yourdash/csi/useResource";
import React from "react";
import { useParams } from "react-router";
import EndpointSettingsCategory from "../../../shared/types/endpoints/setting/category";
Expand Down
62 changes: 21 additions & 41 deletions main/backend/src/core/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,10 +279,7 @@ export class Core {
next();
});

this.log.success(
"core:requests",
`Started the requests logger${options && " (logging options requests is also enabled)"}`,
);
this.log.success("core:requests", `Started the requests logger${options && " (logging options requests is also enabled)"}`);
}

private async loadCoreEndpoints() {
Expand Down Expand Up @@ -388,9 +385,7 @@ export class Core {

const user = new YourDashUser(username);

const savedHashedPassword = await (
await this.fs.getFile(path.join(user.path, "core/password.enc"))
).read("string");
const savedHashedPassword = await (await this.fs.getFile(path.join(user.path, "core/password.enc"))).read("string");

return compareHashString(savedHashedPassword, password)
.then(async (result) => {
Expand Down Expand Up @@ -428,19 +423,14 @@ export class Core {
try {
const user = new YourDashUser(username);
// @ts-ignore
this.users.__internal__getSessionsDoNotUseOutsideOfCore()[username] =
(await user.getAllLoginSessions()) || [];
this.users.__internal__getSessionsDoNotUseOutsideOfCore()[username] = (await user.getAllLoginSessions()) || [];
} catch (_err) {
this.log.info("login", `User with username ${username} not found`);
return res.json({ error: true });
}
}

if (
this.users
.__internal__getSessionsDoNotUseOutsideOfCore()
[username].find((session) => session.sessionToken === token)
) {
if (this.users.__internal__getSessionsDoNotUseOutsideOfCore()[username].find((session) => session.sessionToken === token)) {
return res.json({ success: true });
}

Expand All @@ -461,9 +451,7 @@ export class Core {
this.request.get("/login/instance/metadata", async (_req, res) => {
return res.json(<EndpointResponseLoginInstanceMetadata>{
title: this.globalDb.get("core:instance:name") || "Placeholder name",
message:
this.globalDb.get("core:instance:message") ||
"Placeholder message. Hey system admin, you should change this!",
message: this.globalDb.get("core:instance:message") || "Placeholder message. Hey system admin, you should change this!",
loginLayout: this.globalDb.get("core:instance:login:layout") || LoginLayout.CARDS,
});
});
Expand All @@ -475,19 +463,25 @@ export class Core {
try {
this.webdav.__internal__loadEndpoints();
} catch (e) {
this.log.error("webdav", "Error caught in loadWebdavEndpoints", e);
this.log.error("webdav", "Error caught in webdav.__internal__loadEndpoints(); ", e);
}

try {
this.image.__internal__loadEndpoints();
} catch (e) {
this.log.error("image", "Error caught in loadImageEndpoints", e);
this.log.error("image", "Error caught in image.__internal__loadEndpoints(); ", e);
}

try {
this.video.__internal__loadEndpoints();
} catch (e) {
this.log.error("image", "Error caught in loadImageEndpoints", e);
this.log.error("video", "Error caught in video.__internal__loadEndpoints(); ", e);
}

try {
this.log.__internal__loadEndpoints();
} catch (e) {
this.log.error("log", "Error caught in log.__internal__loadEndpoints(); ", e);
}

try {
Expand All @@ -506,9 +500,7 @@ export class Core {

try {
console.time("core:load_modules");
loadedModules = (await this.moduleManager.loadInstalledApplications()).filter(
(x) => x !== undefined && x !== null,
);
loadedModules = (await this.moduleManager.loadInstalledApplications()).filter((x) => x !== undefined && x !== null);

console.timeEnd("core:load_modules");
this.log.info("startup", "All modules loaded successfully");
Expand Down Expand Up @@ -550,8 +542,7 @@ export class Core {
const user = this.users.get(username);

// @ts-ignore
this.users.__internal__getSessionsDoNotUseOutsideOfCore()[username] =
(await user.getAllLoginSessions()) || [];
this.users.__internal__getSessionsDoNotUseOutsideOfCore()[username] = (await user.getAllLoginSessions()) || [];

const database = await (await this.fs.getFile(path.join(user.path, "core/user_db.json"))).read("string");

Expand All @@ -566,11 +557,7 @@ export class Core {
}
}

if (
this.users
.__internal__getSessionsDoNotUseOutsideOfCore()
[username]?.find((session) => session.sessionToken === token)
) {
if (this.users.__internal__getSessionsDoNotUseOutsideOfCore()[username]?.find((session) => session.sessionToken === token)) {
return next();
}

Expand Down Expand Up @@ -623,9 +610,7 @@ export class Core {

this.request.get("/core/applications", async (_req, res) => {
return res.json(<EndpointResponseCoreApplications>{
applications: (
await (await this.fs.getDirectory(path.join(process.cwd(), "../../applications/"))).getChildren()
).map((app) => {
applications: (await (await this.fs.getDirectory(path.join(process.cwd(), "../../applications/"))).getChildren()).map((app) => {
return {
id: path.basename(app.path) || "unknown",
// TODO: support other types of applications
Expand Down Expand Up @@ -667,10 +652,7 @@ export class Core {

if (!this.isDevMode) {
this.request.use(async (req, res) => {
this.log.info(
"request:404",
`${chalk.bgRed(chalk.black(" 404 "))} ${req.path} (the path was not answered by the backend)`,
);
this.log.info("request:404", `${chalk.bgRed(chalk.black(" 404 "))} ${req.path} (the path was not answered by the backend)`);
return res.status(404).json({ error: "this endpoint does not exist!" });
});
}
Expand Down Expand Up @@ -704,16 +686,14 @@ export class Core {

try {
this.globalDb
.__internal__doNotUseOnlyIntendedForShutdownSequenceWriteToDisk(
path.resolve(process.cwd(), "./fs/global_database.json"),
)
.__internal__doNotUseOnlyIntendedForShutdownSequenceWriteToDisk(path.resolve(process.cwd(), "./fs/global_database.json"))
.then(() => {
this.log.info("global_db", "Successfully saved global database");
});
} catch (e) {
this.log.error(
"global_db",
"[EXTREME SEVERITY] Shutdown Error! failed to save global database. User data will have been lost! (approx < past 5 minutes)",
"[EXTREME SEVERITY] Shutdown Error! failed to save global database. User data will have been lost! (approx <= past 5 minutes)",
);
}

Expand Down
43 changes: 13 additions & 30 deletions main/backend/src/core/coreLog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import chalk from "chalk";
import { Core } from "./core.js";
import WebsocketManagerServer from "./websocketManager/websocketManagerServer.js";

export enum LOG_TYPE {
INFO,
Expand All @@ -23,6 +24,7 @@ export default class CoreLog {
level: string;
message: (string | Uint8Array)[];
}[] = [];
private websocketServer: WebsocketManagerServer;

constructor(core: Core) {
this.core = core;
Expand Down Expand Up @@ -62,6 +64,8 @@ export default class CoreLog {

process.stdout.write(message.slice(1).join(" ").toString() + "\n");

this.websocketServer.emit(type.toString(), [level, ...message]);

return this;
}

Expand All @@ -74,12 +78,7 @@ export default class CoreLog {
throw new Error("log message is empty");
}

return this.log(
LOG_TYPE.INFO,
level,
chalk.bold(`${chalk.white("[")}${chalk.blue("INF")}${chalk.white("]")}`),
...message,
);
return this.log(LOG_TYPE.INFO, level, chalk.bold(`${chalk.white("[")}${chalk.blue("INF")}${chalk.white("]")}`), ...message);
}

success(level: string, ...message: (string | Uint8Array)[]) {
Expand All @@ -91,12 +90,7 @@ export default class CoreLog {
throw new Error("log message is empty");
}

return this.log(
LOG_TYPE.SUCCESS,
level,
chalk.bold(`${chalk.white("[")}${chalk.green("SUC")}${chalk.white("]")}`),
...message,
);
return this.log(LOG_TYPE.SUCCESS, level, chalk.bold(`${chalk.white("[")}${chalk.green("SUC")}${chalk.white("]")}`), ...message);
}

warning(level: string, ...message: (string | Uint8Array)[]) {
Expand All @@ -108,12 +102,7 @@ export default class CoreLog {
throw new Error("log message is empty");
}

return this.log(
LOG_TYPE.WARNING,
level,
chalk.bold(`${chalk.white("[")}${chalk.yellow("WAR")}${chalk.white("]")}`),
...message,
);
return this.log(LOG_TYPE.WARNING, level, chalk.bold(`${chalk.white("[")}${chalk.yellow("WAR")}${chalk.white("]")}`), ...message);
}

error(level: string, ...message: (string | Uint8Array)[]) {
Expand All @@ -123,12 +112,7 @@ export default class CoreLog {

console.log(new Error().stack);

return this.log(
LOG_TYPE.ERROR,
level,
chalk.bold(`${chalk.white("[")}${chalk.red("ERR")}${chalk.white("]")}`),
...message,
);
return this.log(LOG_TYPE.ERROR, level, chalk.bold(`${chalk.white("[")}${chalk.red("ERR")}${chalk.white("]")}`), ...message);
}

debug(level: string, ...message: (string | Uint8Array)[]) {
Expand All @@ -144,11 +128,10 @@ export default class CoreLog {
throw new Error("log message is empty");
}

return this.log(
LOG_TYPE.DEBUG,
level,
chalk.bold(`${chalk.white("[")}${chalk.magenta("DBG")}${chalk.white("]")}`),
...message,
);
return this.log(LOG_TYPE.DEBUG, level, chalk.bold(`${chalk.white("[")}${chalk.magenta("DBG")}${chalk.white("]")}`), ...message);
}

__internal__loadEndpoints() {
this.websocketServer = this.core.websocketManager.createServer("/core::log/");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,15 @@ export default class WebsocketManagerServer {
this.server.on("connection", (socketConnection) => {
// TODO: check for auth (token, username)

this.onConnectionListeners.forEach((listener) =>
listener(new WebsocketManagerConnection(this.server, socketConnection)),
);
this.onConnectionListeners.forEach((listener) => listener(new WebsocketManagerConnection(this.server, socketConnection)));
});
}

onConnection(cb: (connection: WebsocketManagerConnection) => void) {
this.onConnectionListeners.push(cb);
}

emit(channel: string, ...args: unknown[]) {
this.server.emit(channel, args);
}
}
15 changes: 14 additions & 1 deletion main/web/src/WebsocketToasts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,21 @@
* YourDash is licensed under the MIT License. (https://mit.ewsgit.uk)
*/

import useWebsocketConnection from "@yourdash/csi/useWebsocketConnection";
import React, { useEffect } from "react";

const WebsocketToasts: React.FC = () => {
const wsc = useWebsocketConnection();
const wsc = useWebsocketConnection("/core::log");

useEffect(() => {
if (!wsc) return;

wsc.on("info", (data) => {
console.log("INFO", data);
});
}, []);

return <></>;
};

export default WebsocketToasts;
2 changes: 1 addition & 1 deletion main/web/src/login/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import csi from "@yourdash/csi/csi.js";
import { LoginLayout } from "@yourdash/shared/core/login/loginLayout.js";
import Spinner from "@yourdash/uikit/components/spinner/spinner.js";
import useResource from "../lib/useResource";
import useResource from "@yourdash/csi/useResource";
import IndexCardsPage from "./index.cards.js";
import styles from "./index.module.scss";
import { FC, Suspense } from "react";
Expand Down
2 changes: 1 addition & 1 deletion main/web/src/login/success/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import Heading from "@yourdash/uikit/components/heading/heading";
import Redirect from "@yourdash/uikit/components/redirect/redirect";
import Subtext from "@yourdash/uikit/components/subtext/subtext";
import Text from "@yourdash/uikit/components/text/text";
import useResource from "../../lib/useResource";
import useResource from "@yourdash/csi/useResource";
import styles from "./index.module.scss";
import { FC } from "react";
import { useNavigate } from "react-router";
Expand Down
2 changes: 2 additions & 0 deletions main/web/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import ProjectsIndexPage from "./root/projects/Index";
import ChipletRootIntegration from "@yourdash/chiplet/RootIntegration";
import LinkerDesktopClientStartupPage from "./root/linkerDesktopClientStartup/Index";
import HostedApplicationRouter from "./app/HostedApplicationRouter";
import WebsocketToasts from "./WebsocketToasts";

const AppRouter = loadable(() => import("./app/AppRouter"));
const DocsRouter = loadable(() => import("./root/docs/DocsRouter"));
Expand All @@ -35,6 +36,7 @@ function main() {
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<ChipletRootIntegration>
<UIKitRoot>
<WebsocketToasts />
<RouterProvider
router={createBrowserRouter(
createRoutesFromElements(
Expand Down
4 changes: 3 additions & 1 deletion packages/csi/csi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,9 @@ class __internalClientServerInteraction {

// returns the Websocket version of the URL of the current instance
getInstanceWebsocketUrl(): string {
return localStorage.getItem("instance_url") || "";
console.log(localStorage.getItem("instance_url"));

return localStorage.getItem("instance_url")?.replace("http", "ws").replace("https", "wss") || "";
}

// returns the list of saved instance's urls
Expand Down
File renamed without changes.
Loading

0 comments on commit 49c9284

Please sign in to comment.