Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
kamil-stasiak committed Oct 31, 2024
1 parent 2518d69 commit d5d8949
Show file tree
Hide file tree
Showing 17 changed files with 125 additions and 161 deletions.
2 changes: 1 addition & 1 deletion e2e-tests/ts-client/app/playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default defineConfig({
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: 1,
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: [
["list"],
Expand Down
5 changes: 0 additions & 5 deletions e2e-tests/ts-client/app/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,20 +75,15 @@ class RemoteStore {
}

snapshot() {
console.log("Snapshot");

const newTracks = webrtc.getRemoteTracks();
const newEndpoints = webrtc.getRemoteEndpoints();
const ids =
Object.keys(newTracks).sort().join(":") +
Object.keys(newEndpoints).sort().join(":");
if (!(ids in this.cache) || this.invalidateCache) {
console.log({ name: "Update cache", newEndpoints, newTracks });
this.cache[ids] = [newEndpoints, newTracks];
this.invalidateCache = false;
}
console.log("Use cache");

return this.cache[ids];
}
}
Expand Down
75 changes: 22 additions & 53 deletions examples/ts-client/simple-app/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,7 @@ inputArray.forEach((input) => {
});
});

const TrackTypeValues = ["screensharing", "camera", "audio"] as const;
export type TrackType = (typeof TrackTypeValues)[number];
export type TrackType = "screensharing" | "camera" | "audio";

export type PeerMetadata = {
name: string;
Expand All @@ -94,40 +93,7 @@ export type TrackMetadata = {
active: boolean;
};

const isPeerMetadata = (input: unknown): input is PeerMetadata => {
return (
typeof input === "object" &&
input !== null &&
"name" in input &&
typeof input["name"] === "string"
);
};

const isTrackType = (input: unknown): input is TrackType =>
TrackTypeValues.includes(input as TrackType);

const isTrackMetadata = (input: unknown): input is TrackMetadata =>
typeof input === "object" &&
input !== null &&
"type" in input &&
isTrackType(input.type) &&
"active" in input &&
typeof input.active === "boolean";

const trackMetadataParser = (input: unknown): TrackMetadata => {
if (isTrackMetadata(input)) return input;
throw Error("Invalid track metadata");
};

const peerMetadataParser = (input: unknown): PeerMetadata => {
if (isPeerMetadata(input)) return input;

throw Error("Invalid peer metadata");
};

const client: FishjamClient<PeerMetadata, TrackMetadata> = new FishjamClient({
peerMetadataParser,
trackMetadataParser,
reconnect: true,
});

Expand Down Expand Up @@ -157,34 +123,37 @@ client.on("trackAdded", (ctx) => {
console.log({ name: "trackAdded", ctx });
});

client.on("joined", (_peerId: string, peersInRoom: Peer[]) => {
console.log("Join success!");
toastSuccess(`Joined room`);
const template = document.querySelector("#remote-peer-template-card")!;
const remotePeers = document.querySelector("#remote-peers")!;
client.on(
"joined",
(_peerId: string, peersInRoom: Peer<PeerMetadata, TrackMetadata>[]) => {
console.log("Join success!");
toastSuccess(`Joined room`);
const template = document.querySelector("#remote-peer-template-card")!;
const remotePeers = document.querySelector("#remote-peers")!;

(peersInRoom || []).forEach((peer: Peer) => {
// @ts-ignore
const clone = template.content.cloneNode(true);
const card = clone.firstElementChild;
card.dataset.peerId = peer.id;
(peersInRoom || []).forEach((peer: Peer<PeerMetadata, TrackMetadata>) => {
// @ts-ignore
const clone = template.content.cloneNode(true);
const card = clone.firstElementChild;
card.dataset.peerId = peer.id;

const peerId = clone.querySelector(".remote-peer-template-id");
peerId.innerHTML = peer.id;
const peerId = clone.querySelector(".remote-peer-template-id");
peerId.innerHTML = peer.id;

clone.firstElementChild.dataset.peerId = peer.id;
clone.firstElementChild.dataset.peerId = peer.id;

document.querySelector(`div[data-peer-id="${peer.id}"`)?.remove();
remotePeers.appendChild(clone);
});
});
document.querySelector(`div[data-peer-id="${peer.id}"`)?.remove();
remotePeers.appendChild(clone);
});
},
);

client.on("joinError", (metadata) => {
console.log({ name: "joinError", metadata });
toastAlert("Join error");
});

client.on("peerJoined", (peer: Peer) => {
client.on("peerJoined", (peer: Peer<PeerMetadata, TrackMetadata>) => {
console.log("Peer join success!");

const template = document.querySelector("#remote-peer-template-card")!;
Expand Down
6 changes: 3 additions & 3 deletions packages/react-client/src/hooks/useFishjamClientState.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useCallback, useMemo, useRef, useSyncExternalStore } from "react";
import type { Component, Endpoint, MessageEvents, Peer, FishjamClient } from "@fishjam-cloud/ts-client";
import type { Component, MessageEvents, Peer, FishjamClient } from "@fishjam-cloud/ts-client";
import type { PeerId, PeerMetadata, TrackMetadata } from "../types/internal";

const eventNames = [
Expand Down Expand Up @@ -43,9 +43,9 @@ const eventNames = [
] as const satisfies (keyof MessageEvents<unknown, unknown>)[];

export interface FishjamClientState {
peers: Record<PeerId, Peer>;
peers: Record<PeerId, Peer<PeerMetadata, TrackMetadata>>;
components: Record<string, Component>;
localPeer: Endpoint | null;
localPeer: Peer<PeerMetadata, TrackMetadata> | null;
isReconnecting: boolean;
}

Expand Down
14 changes: 7 additions & 7 deletions packages/react-client/src/hooks/usePeers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Component, Endpoint, Peer, TrackContext } from "@fishjam-cloud/ts-client";
import type { FishjamPeerMetadata, PeerState, TrackId, TrackMetadata } from "../types/internal";
import type { Component, Endpoint, FishjamTrackContext, Peer } from "@fishjam-cloud/ts-client";
import type { PeerMetadata, PeerState, TrackId, TrackMetadata } from "../types/internal";
import type { PeerWithTracks, Track } from "../types/public";
import { useFishjamContext } from "./useFishjamContext";

Expand All @@ -14,9 +14,9 @@ function getPeerWithDistinguishedTracks(peerState: PeerState): PeerWithTracks {
return { ...peerState, cameraTrack, microphoneTrack, screenShareVideoTrack, screenShareAudioTrack };
}

function trackContextToTrack(track: TrackContext): Track {
function trackContextToTrack(track: FishjamTrackContext<TrackMetadata>): Track {
return {
metadata: track.metadata as TrackMetadata,
metadata: track.metadata,
trackId: track.trackId,
stream: track.stream,
simulcastConfig: track.simulcastConfig ?? null,
Expand All @@ -26,14 +26,14 @@ function trackContextToTrack(track: TrackContext): Track {
};
}

function endpointToPeerState(peer: Peer | Component | Endpoint): PeerState {
function endpointToPeerState(peer: Peer<PeerMetadata, TrackMetadata> | Component | Endpoint): PeerState {
const tracks = [...peer.tracks].reduce(
(acc, [, track]) => ({ ...acc, [track.trackId]: trackContextToTrack(track) }),
(acc, [, track]) => ({ ...acc, [track.trackId]: trackContextToTrack(track as FishjamTrackContext<TrackMetadata>) }),
{} as Record<TrackId, Track>,
);

return {
metadata: peer.metadata as FishjamPeerMetadata,
metadata: peer.metadata as Peer<PeerMetadata, TrackMetadata>["metadata"],
id: peer.id,
tracks,
};
Expand Down
1 change: 0 additions & 1 deletion packages/react-client/src/hooks/useScreenShare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ export const useScreenShareManager = ({
const stream = state.stream ?? null;
const [videoTrack, audioTrack] = stream ? getTracksFromStream(stream) : [null, null];

// @ts-ignore
const getDisplayName = () => fishjamClient.getLocalPeer()?.metadata?.peer?.displayName;

const startStreaming: ScreenshareApi["startStreaming"] = async (props) => {
Expand Down
1 change: 0 additions & 1 deletion packages/react-client/src/hooks/useTrackManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ export const useTrackManager = ({
// see `getRemoteOrLocalTrackContext()` explanation
setCurrentTrackId(media.track.id);

// @ts-ignore
const displayName = tsClient.getLocalPeer()?.metadata?.peer?.displayName;

const deviceType = getDeviceType(mediaManager);
Expand Down
8 changes: 2 additions & 6 deletions packages/react-client/src/types/internal.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
import type { DeviceType } from "../DeviceManager";
import type { StartStreamingProps, Track, TrackMiddleware, TracksMiddleware } from "./public";
import type { Peer } from "@fishjam-cloud/ts-client";

export type TrackId = string;
export type PeerId = string;

export type PeerState = {
id: PeerId;
metadata?: FishjamPeerMetadata;
metadata?: Peer<PeerMetadata, TrackMetadata>["metadata"];
tracks: Record<TrackId, Track>;
};

export type FishjamPeerMetadata = {
peer: PeerMetadata;
server?: Record<string, unknown>;
};

export type PeerMetadata = {
displayName?: string;
};
Expand Down
22 changes: 9 additions & 13 deletions packages/react-client/src/utils/track.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,15 @@ const getRemoteOrLocalTrackContext = <PeerMetadata, TrackMetadata>(
return trackByLocalId ? trackByLocalId : null;
};

const getTrackFromContext = (context: TrackContext): Track => {
return {
// todo typescript client should parse this metadata
// @ts-ignore
metadata: context.metadata as TrackMetadata, // todo parse metadata
trackId: context.trackId,
stream: context.stream,
simulcastConfig: context.simulcastConfig || null,
encoding: context.encoding || null,
vadStatus: context.vadStatus,
track: context.track,
};
};
const getTrackFromContext = (context: TrackContext): Track => ({
metadata: context.metadata as TrackMetadata,
trackId: context.trackId,
stream: context.stream,
simulcastConfig: context.simulcastConfig || null,
encoding: context.encoding || null,
vadStatus: context.vadStatus,
track: context.track,
});

export const getRemoteOrLocalTrack = (
tsClient: FishjamClient<PeerMetadata, TrackMetadata>,
Expand Down
Loading

0 comments on commit d5d8949

Please sign in to comment.