Skip to content

Commit

Permalink
wip: remove ptero
Browse files Browse the repository at this point in the history
  • Loading branch information
GregTCLTK committed Nov 2, 2023
1 parent 5fb91da commit 26bc707
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 106 deletions.
80 changes: 10 additions & 70 deletions pages/hosting/loading.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { HmRequest, LoginRequest, MessageType, SyncResponse, TriggerRequest } from "https://deno.land/x/hmsys_connector@0.9.0/mod.ts";
import { LoginRequest, MessageType, SyncResponse, TriggerRequest } from "https://deno.land/x/hmsys_connector@0.9.0/mod.ts";
import { API, ProgressTracker } from "shared";
import { Deferred, deferred } from "std/async/deferred.ts";
import { decodeBase64, encodeBase64 } from "std/encoding/base64.ts";
import { Pointer, State, asPointer, lazyInit } from "webgen/mod.ts";
import { Server, ServerDetails, SidecarRequest, SidecarResponse } from "../../spec/music.ts";
import { Pointer, State, asPointer } from "webgen/mod.ts";
import { Server, SidecarRequest, SidecarResponse } from "../../spec/music.ts";
import { activeUser, tokens } from "../_legacy/helper.ts";
import { state } from "./data.ts";
import { canWriteInFolder, currentFiles } from "./views/state.ts";


export async function refreshState() {
state.servers = State((await API.hosting.servers()).map(x => State(x)));
state.meta = State(await API.hosting.meta());
Expand Down Expand Up @@ -64,65 +63,6 @@ export function listener() {
ws.onclose = () => setTimeout(() => listener(), 1000);
}

export const currentDetailsTarget = asPointer(<string | undefined>undefined);
export const currentDetailsSource = asPointer((_data: ServerDetails) => { });

export const messageQueue = <HmRequest[]>[];
// deno-lint-ignore require-await
export const streamingPool = lazyInit(async () => {
function connect() {
const ws = new WebSocket(API.WS_URL);
let firstTime = true;
ws.onmessage = ({ data }) => {
const json = JSON.parse(data);

if (json.login === "require authentication" && tokens.accessToken) ws.send(JSON.stringify(<LoginRequest>{
action: MessageType.Login,
type: "client",
token: API.getToken(),
id: activeUser.id
}));

if (json.login === true && firstTime === true) {
firstTime = false;
currentDetailsTarget.listen((id, _oldId) => {
if (id)
ws.send(JSON.stringify(<TriggerRequest>{
action: MessageType.Trigger,
type: "@bbn/hosting/details",
data: {
id
},
auth: {
token: API.getToken(),
id: activeUser.id
}
}));
else if (_oldId != undefined) {
// Else somehow unregister the oldId
// Can't current unregister the conversation. Thats why we just restart the pool.
ws.close();
}

});
}
if (json.type == "sync" && json.data.type == "@bbn/hosting/details") {
currentDetailsSource.getValue()?.(json.data.data);
}
};
ws.onerror = () => {

};
setInterval(() => {
if (ws.readyState != ws.OPEN || messageQueue.length == 0) return;

ws.send(JSON.stringify(messageQueue.shift()));
}, 100);
ws.onclose = () => setTimeout(() => connect(), 1000);
}
connect();
});

export let messageQueueSidecar = <{ request: SidecarRequest, response: Deferred<SidecarResponse>; }[]>[];
let activeSideCar: Deferred<void> | undefined = undefined;
export const isSidecarConnect = asPointer(false);
Expand All @@ -137,7 +77,7 @@ export async function startSidecarConnection(id: string) {
}

const url = new URL(`wss://bbn.one/api/@bbn/sidecar/${id}/ws`);
url.searchParams.set("TOKEN", localStorage[ "access-token" ]);
url.searchParams.set("TOKEN", API.getToken());
const ws = new WebSocket(url.toString());
activeSideCar = deferred();

Expand Down Expand Up @@ -192,12 +132,12 @@ export async function startSidecarConnection(id: string) {
ws.close();
}

export async function listFiles(_path: string) {
export async function listFiles(path: string) {
const response = deferred<SidecarResponse>();
messageQueueSidecar.push({
request: {
type: "list",
path: _path
path
},
response
});
Expand All @@ -216,7 +156,7 @@ export function downloadFile(path: string) {
messageQueueSidecar.push({
request: {
type: firstTime ? "read" : "next-chunk",
path: path
path
},
response: nextChunk
});
Expand All @@ -235,12 +175,12 @@ export function downloadFile(path: string) {
}
});
}
export async function uploadFile(_path: string, file: File, progress: Pointer<number>) {
export async function uploadFile(path: string, file: File, progress: Pointer<number>) {
const check = deferred<SidecarResponse>();
messageQueueSidecar.push({
request: {
type: "write",
path: _path
path
},
response: check
});
Expand All @@ -253,7 +193,7 @@ export async function uploadFile(_path: string, file: File, progress: Pointer<nu
messageQueueSidecar.push({
request: {
type: "write",
path: _path,
path,
chunk: encodeBase64(iterator)
},
response: nextChunk
Expand Down
6 changes: 3 additions & 3 deletions pages/hosting/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import '../../assets/css/main.css';
import { DynaNavigation } from "../../components/nav.ts";
import { RegisterAuthRefresh, changeThemeColor, renewAccessTokenIfNeeded } from "../_legacy/helper.ts";
import { state } from "./data.ts";
import { listFiles, listener, refreshState, startSidecarConnection, streamingPool } from "./loading.ts";
import { listFiles, listener, refreshState, startSidecarConnection } from "./loading.ts";
import { hostingMenu } from "./views/menu.ts";

import '../../assets/css/hosting.css';
Expand Down Expand Up @@ -31,8 +31,8 @@ renewAccessTokenIfNeeded()
const [ source, serverId, subView ] = urlPath.split("/");
if (source === "servers" && serverId) {
const server = await API.hosting.serverId(serverId).get().then(stupidErrorAlert);
state.servers.push(State(server));
await streamingPool();
if (!state.servers.find(s => s._id == serverId))
state.servers.push(State(server));
if (!server.identifier)
startSidecarConnection(serverId);
if (subView === "storage") {
Expand Down
64 changes: 34 additions & 30 deletions pages/hosting/views/ServerDetails.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { API, stupidErrorAlert } from "shared";
import { deferred } from "std/async/deferred.ts";
import { Box, Button, Custom, Entry, Form, Grid, State, StateHandler, TextInput, isMobile, refMerge } from "webgen/mod.ts";
import { Box, Button, Custom, Entry, Form, Grid, Label, State, StateHandler, TextInput, isMobile, refMerge } from "webgen/mod.ts";
import { Server, SidecarResponse } from "../../../spec/music.ts";
import { currentDetailsTarget, isSidecarConnect, listFiles, messageQueueSidecar, sidecarDetailsSource } from "../loading.ts";
import { isSidecarConnect, listFiles, messageQueueSidecar, sidecarDetailsSource } from "../loading.ts";
import { ServerStaticInfo } from "./ServerStaticInfo.ts";
import { editServerDialog } from "./dialogs/editServerDialog.ts";
import { auditEntry, hostingMenu } from "./menu.ts";
Expand All @@ -22,7 +22,6 @@ export function ServerDetails(server: StateHandler<Server>) {

terminal.connected.listen(val => {
if (val) {
currentDetailsTarget.setValue(server._id);
sidecarDetailsSource.setValue((data: SidecarResponse) => {
if (data.type == "log") {
if (data.backlog)
Expand All @@ -45,32 +44,38 @@ export function ServerDetails(server: StateHandler<Server>) {
.map(({ connected, mobile }) => (() => {
const items = Grid(
...ServerStaticInfo(mobile, server, input),
!server.identifier && !connected
? DisconnectedScreen()
: Entry(
Grid(
Box(Custom(terminal).addClass("terminal-window")).removeFromLayout(),
Form(Grid(
TextInput("text", "Send a Command")
.sync(input, "message"),
Button("Send")
.setId("submit-button")
.onClick(() => {
messageQueueSidecar.push({
request: {
type: "command",
command: input.message
},
response: deferred()
});
input.message = "";
})
)
.setRawColumns("auto max-content")
.setGap(".5rem"))
.activeSubmitTo("#submit-button")
).addClass("internal-grid")
).addClass("terminal-card"),
server.identifier ? Grid(
Grid(
Label("Please migrate", "h1"),
Label("This server is still running on our legacy system. Please re-create it.", "h2")
).setJustify("center")
).addClass("disconnected-screen") :
connected
? Entry(
Grid(
Box(Custom(terminal).addClass("terminal-window")).removeFromLayout(),
Form(Grid(
TextInput("text", "Send a Command")
.sync(input, "message"),
Button("Send")
.setId("submit-button")
.onClick(() => {
messageQueueSidecar.push({
request: {
type: "command",
command: input.message
},
response: deferred()
});
input.message = "";
})
)
.setRawColumns("auto max-content")
.setGap(".5rem"))
.activeSubmitTo("#submit-button")
).addClass("internal-grid")
).addClass("terminal-card")
: DisconnectedScreen(),
server.identifier ? Grid(
Entry({
title: "Settings",
Expand Down Expand Up @@ -99,7 +104,6 @@ export function ServerDetails(server: StateHandler<Server>) {
title: "Storage",
subtitle: "Manage your persistence",
}).onClick(async () => {
console.log(hostingMenu.path.getValue());
await listFiles("/");
path.setValue("/");
hostingMenu.path.setValue(`${hostingMenu.path.getValue()}storage/`);
Expand Down
5 changes: 2 additions & 3 deletions pages/hosting/views/menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import serverTypes from "../../../data/servers.json" assert { type: "json" };
import { Addon, AuditTypes, SidecarResponse } from "../../../spec/music.ts";
import { activeUser, showProfilePicture } from "../../_legacy/helper.ts";
import { state } from "../data.ts";
import { messageQueueSidecar, startSidecarConnection, stopSidecarConnection, streamingPool } from "../loading.ts";
import { messageQueueSidecar, startSidecarConnection, stopSidecarConnection } from "../loading.ts";
import { profileView } from "../views/profile.ts";
import { ChangeStateButton } from "./changeStateButton.ts";
import './details.css';
Expand Down Expand Up @@ -52,8 +52,7 @@ export const hostingMenu = Navigation({
.setGap("1rem")
.setAlign("center"),
suffix: ChangeStateButton(server),
clickHandler: async () => {
await streamingPool();
clickHandler: () => {
if (!server.identifier)
startSidecarConnection(server._id);
// TODO wait until first data is showing to prevent blinking
Expand Down
1 change: 1 addition & 0 deletions pages/shared/restSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ function blob() {
return await asExternal(rsp.blob());
};
}
}

export function stupidErrorAlert<T>(data: PromiseSettledResult<T>): T {
if (data.status === "fulfilled")
Expand Down

0 comments on commit 26bc707

Please sign in to comment.