### Install FastAPI for Python
Source: https://docs.fishjam.io/0.22.0/tutorials/backend-quick-start
Commands to install the FastAPI framework and its standard dependencies using pip or poetry.
```bash
pip install fastapi[standard]
```
```bash
poetry add fastapi[standard]
```
--------------------------------
### Install Express.js for Node.js/TypeScript
Source: https://docs.fishjam.io/0.22.0/tutorials/backend-quick-start
Commands to install the Express.js framework and its TypeScript types using npm, yarn, or pnpm.
```bash
npm install express @types/express
```
```bash
yarn add express @types/express
```
```bash
pnpm add express @types/express
```
--------------------------------
### Complete Python Fishjam Backend Example with FastAPI
Source: https://docs.fishjam.io/0.22.0/tutorials/backend-quick-start
A full working example of a Python backend server using FastAPI and Fishjam SDK to create rooms and peers.
```python
import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from fishjam import FishjamClient, PeerOptions
app = FastAPI()
fishjam_client = FishjamClient(
os.environ["FISHJAM_ID"],
os.environ["FISHJAM_MANAGEMENT_TOKEN"]
)
class JoinRoomRequest(BaseModel):
room_name: str
peer_name: str
@app.post("/join-room")
async def join_room(request: JoinRoomRequest):
try:
room = fishjam_client.create_room()
options = PeerOptions(metadata={"name": request.peer_name})
peer, peer_token = fishjam_client.create_peer(room.id, options=options)
return {
"room_id": room.id,
"peer_token": peer_token
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
```
--------------------------------
### Complete Fishjam Backend Example (Node.js/TypeScript)
Source: https://docs.fishjam.io/0.23.0/tutorials/backend-quick-start
This is a complete working example of a backend server using Node.js and Express to interact with the Fishjam API. It sets up an Express app, initializes the Fishjam client, and defines a `/join-room` POST endpoint to create rooms and peers.
```typescript
import express from 'express';
import { FishjamClient } from '@fishjam-cloud/js-server-sdk';
const app = express();
app.use(express.json());
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.FISHJAM_MANAGEMENT_TOKEN!
});
app.post('/join-room', async (req, res) => {
try {
const { roomName, peerName } = req.body;
const room = await fishjamClient.createRoom();
const { peer, peerToken } = await fishjamClient.createPeer(room.id, {
metadata: { name: peerName },
});
res.json({
roomId: room.id,
peerToken,
});
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000, () => {
console.log('Fishjam backend running on port 3000');
});
```
--------------------------------
### Complete Node.js/TypeScript Fishjam Backend Example
Source: https://docs.fishjam.io/0.22.0/tutorials/backend-quick-start
A full working example of a Node.js/TypeScript backend server using Express.js and Fishjam SDK to create rooms and peers.
```typescript
import express from 'express';
import { FishjamClient } from '@fishjam-cloud/js-server-sdk';
const app = express();
app.use(express.json());
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.FISHJAM_MANAGEMENT_TOKEN!
});
app.post('/join-room', async (req, res) => {
try {
const { roomName, peerName } = req.body;
const room = await fishjamClient.createRoom();
const { peer, peerToken } = await fishjamClient.createPeer(room.id, {
metadata: { name: peerName },
});
res.json({
roomId: room.id,
peerToken,
});
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000, () => {
console.log('Fishjam backend running on port 3000');
});
```
--------------------------------
### Complete Fishjam React Native App Example
Source: https://docs.fishjam.io/0.22.0/tutorials/react-native-quick-start
A comprehensive example integrating all previously shown components: starting a stream, displaying connection status, showing the local video preview, and rendering streams from other participants within a React Native application. It requires setting up the FISHJAM_ID environment variable.
```javascript
import { Text, View, Button } from "react-native";
import {
usePeers,
useCamera,
useConnection,
useSandbox,
VideoRendererView,
VideoPreviewView,
} from "@fishjam-cloud/react-native-client";
import React, { useCallback } from "react";
// Check https://fishjam.io/app for your Fishjam ID
const FISHJAM_ID = `${process.env.EXPO_PUBLIC_FISHJAM_ID}`;
function StartStreamingButton({
roomName,
peerName,
}: { roomName: string; peerName: string }) {
const { prepareCamera } = useCamera();
const { joinRoom } = useConnection();
const { getSandboxPeerToken } = useSandbox({ fishjamId: FISHJAM_ID });
const startStreaming = useCallback(async () => {
const peerToken = await getSandboxPeerToken(roomName, peerName);
await prepareCamera({ cameraEnabled: true });
await joinRoom({ peerToken, fishjamId: FISHJAM_ID });
}, [joinRoom, prepareCamera, roomName, peerName]);
return ;
}
function ConnectionStatus() {
const { peerStatus } = useConnection();
return Status: {peerStatus};
}
function StreamPreview() {
return ;
}
function ParticipantsView() {
const { remotePeers } = usePeers();
const videoTracks = remotePeers.flatMap((peer) =>
peer.tracks.filter((track) => track.type === "Video" && track.isActive),
);
return (
{videoTracks.map((track) => (
))}
);
}
export default function Index() {
return (
Your Stream:Other Participants:
);
}
```
--------------------------------
### FastAPI Minimal Setup with FishjamClient
Source: https://docs.fishjam.io/0.22.0/how-to/backend/fastapi-example
This snippet demonstrates the minimal setup for a FastAPI application using the Fishjam SDK. It configures the FishjamClient as a dependency for FastAPI routes, allowing easy access to Fishjam functionalities. Ensure FISHJAM_ID and FISHJAM_MANAGEMENT_TOKEN environment variables are set. This setup promotes code reusability and simplifies testing.
```python
import os
from typing import Annotated
from fastapi import Depends, FastAPI
from fishjam import FishjamClient
app = FastAPI()
def fishjam_client():
fishjam_id = os.environ["FISHJAM_ID"]
management_token = os.environ["FISHJAM_MANAGEMENT_TOKEN"]
return FishjamClient(fishjam_id=fishjam_id, management_token=management_token)
@app.get("/")
async def get_rooms(fishjam_client: Annotated[FishjamClient, Depends(fishjam_client)]):
rooms = fishjam_client.get_all_rooms()
return {"rooms": rooms}
```
--------------------------------
### Setup Fishjam Client
Source: https://docs.fishjam.io/0.23.0/how-to/backend/server-setup
Guide to setting up the Fishjam client by obtaining credentials from the developer panel and initializing the client in TypeScript and Python.
```APIDOC
## Setup Fishjam Client
This section outlines how to set up your client to communicate with a Fishjam instance using your Fishjam ID and Management Token.
### TypeScript
```typescript
import { FishjamClient } from '@fishjam-cloud/js-server-sdk';
const fishjamId = process.env.FISHJAM_ID;
const managementToken = process.env.FISHJAM_MANAGEMENT_TOKEN;
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
```
### Python
```python
import os
from fishjam import FishjamClient
fishjam_id = os.environ["FISHJAM_ID"]
management_token = os.environ["FISHJAM_MANAGEMENT_TOKEN"]
fishjam_client = FishjamClient(fishjam_id, management_token)
```
```
--------------------------------
### Install Fishjam React Client with Bun
Source: https://docs.fishjam.io/0.22.0/how-to/react/installation
Installs the Fishjam React client package using Bun. Bun is a new, fast JavaScript runtime, bundler, transpiler, and package manager.
```bash
bun add @fishjam-cloud/react-client
```
--------------------------------
### Install Node.js SDK for Fishjam
Source: https://docs.fishjam.io/0.22.0/tutorials/backend-quick-start
Installs the JavaScript server SDK for Fishjam using npm, yarn, or pnpm. This package is essential for interacting with the Fishjam backend services.
```bash
npm install @fishjam-cloud/js-server-sdk
```
```bash
yarn add @fishjam-cloud/js-server-sdk
```
```bash
pnpm add @fishjam-cloud/js-server-sdk
```
--------------------------------
### Install Fishjam Client with Bun
Source: https://docs.fishjam.io/0.22.0/tutorials/react-native-quick-start
Installs the Fishjam React Native client package using Bun. Bun is a fast JavaScript runtime and toolkit.
```bash
bun add @fishjam-cloud/react-native-client
```
--------------------------------
### Install Fishjam Server SDK (pnpm)
Source: https://docs.fishjam.io/0.23.0/tutorials/backend-quick-start
Installs the JavaScript server SDK for Fishjam using pnpm. This command uses the pnpm package manager to add the SDK.
```bash
pnpm add @fishjam-cloud/js-server-sdk
```
--------------------------------
### Install Fishjam Client with npm
Source: https://docs.fishjam.io/0.22.0/tutorials/react-native-quick-start
Installs the Fishjam React Native client package using npm. This is a common package manager for Node.js projects.
```bash
npm install @fishjam-cloud/react-native-client
```
--------------------------------
### Install Fishjam React Client with Yarn
Source: https://docs.fishjam.io/0.22.0/how-to/react/installation
Installs the Fishjam React client package using Yarn. This command is an alternative to npm for managing project dependencies.
```bash
yarn add @fishjam-cloud/react-client
```
--------------------------------
### Production Livestreaming Setup - Python
Source: https://docs.fishjam.io/0.23.0/tutorials/livestreaming
Presents a Python example using the `fishjam` server SDK to set up a production livestream. It covers creating a room, generating streamer tokens, and generating viewer tokens.
```APIDOC
## Production Livestreaming Setup - Python
### Description
This example demonstrates how to initialize a Fishjam backend application using the `fishjam` server SDK in Python. It outlines the necessary steps to create a livestream room, generate a streamer token, and generate a viewer token, which are essential for production environments.
### Method
N/A (Server-side SDK usage)
### Endpoint
N/A (Server-side SDK usage)
### Parameters
- **fishjam_id** (str) - Required - The ID of your Fishjam instance.
- **management_token** (str) - Required - The management token for authenticating with the Fishjam API.
- **room.id** (str) - The ID of the created room.
### Request Example
```python
from fishjam import FishjamClient
fishjam_client = FishjamClient(
fishjam_id=fishjam_id,
management_token=management_token,
);
# 1. Create a room of 'livestream' type
room = fishjam_client.create_room(room_type="livestream")
# 2. Create a streamer token for the room
streamer_token = fishjam_client.create_livestream_streamer_token(room.id)
# 3. Create a viewer token for the room
viewer_token = fishjam_client.create_livestream_viewer_token(room.id)
# These tokens should then be supplied to your frontend applications.
```
### Response
#### Success Response (200)
- **room** (object) - The created room object, containing `id`.
- **streamer_token** (str) - The generated token for streamers.
- **viewer_token** (str) - The generated token for viewers.
#### Response Example
N/A (Example shows SDK usage, not direct API response)
```
--------------------------------
### Test Python API Endpoint
Source: https://docs.fishjam.io/0.22.0/tutorials/backend-quick-start
Example `curl` command to send a POST request to the Python '/join-room' endpoint with JSON payload.
```bash
curl -X POST http://localhost:3000/join-room \
-H "Content-Type: application/json" \
-d '{"room_name": "test-room", "peer_name": "test-user"}'
```
--------------------------------
### Install Fishjam React Client with npm
Source: https://docs.fishjam.io/0.22.0/how-to/react/installation
Installs the Fishjam React client package using npm. This is a prerequisite for integrating Fishjam features into a React application.
```bash
npm install @fishjam-cloud/react-client
```
--------------------------------
### Install Fishjam Client with pnpm
Source: https://docs.fishjam.io/0.22.0/tutorials/react-native-quick-start
Installs the Fishjam React Native client package using pnpm. pnpm is a performant package manager known for its efficiency.
```bash
pnpm add @fishjam-cloud/react-native-client
```
--------------------------------
### Install Fishjam React Client using npm, Yarn, pnpm, or Bun
Source: https://docs.fishjam.io/how-to/react/installation
Install the Fishjam React Client package using your preferred JavaScript package manager. This command adds the necessary library to your project's dependencies, enabling its use in your React application.
```bash
npm install @fishjam-cloud/react-client
```
```bash
yarn add @fishjam-cloud/react-client
```
```bash
pnpm add @fishjam-cloud/react-client
```
```bash
bun add @fishjam-cloud/react-client
```
--------------------------------
### Install Fishjam React Client with pnpm
Source: https://docs.fishjam.io/0.22.0/how-to/react/installation
Installs the Fishjam React client package using pnpm. pnpm is a performant package manager that saves disk space and speeds up installations.
```bash
pnpm add @fishjam-cloud/react-client
```
--------------------------------
### Build Native Dependencies with Expo
Source: https://docs.fishjam.io/0.22.0/tutorials/react-native-quick-start
Triggers the prebuilding process for Expo projects to generate native project files, essential after installing or updating native dependencies.
```bash
npx expo prebuild
```
--------------------------------
### Install Fishjam Client with Yarn
Source: https://docs.fishjam.io/0.22.0/tutorials/react-native-quick-start
Installs the Fishjam React Native client package using Yarn. Yarn is another popular package manager for JavaScript.
```bash
yarn add @fishjam-cloud/react-native-client
```
--------------------------------
### Install the SDK
Source: https://docs.fishjam.io/0.22.0/how-to/backend/server-setup
Instructions for installing the Fishjam server SDK for Node.js (NPM, YARN) and Python (PIP, POETRY). Alternatively, you can use the bare REST API.
```APIDOC
## Install the SDK
Install the SDK for the language of your choice. We provide libraries for **Node** and **Python**. It's also possible to use the bare REST API, in this case you can skip this step.
### NPM
```bash
npm install @fishjam-cloud/js-server-sdk
```
### YARN
```bash
yarn add @fishjam-cloud/js-server-sdk
```
### PIP
```bash
pip install fishjam-server-sdk
```
### POETRY
```bash
poetry add fishjam-server-sdk
```
```
--------------------------------
### Test Node.js/TypeScript API Endpoint
Source: https://docs.fishjam.io/0.22.0/tutorials/backend-quick-start
Example `curl` command to send a POST request to the Node.js/TypeScript '/join-room' endpoint with JSON payload.
```bash
curl -X POST http://localhost:3000/join-room \
-H "Content-Type: application/json" \
-d '{"roomName": "test-room", "peerName": "test-user"}'
```
--------------------------------
### Setup Fishjam Fastify Plugin with JS Server SDK
Source: https://docs.fishjam.io/0.22.0/how-to/backend/fastify-example
Encapsulates Fishjam client initialization within a Fastify plugin. It extends the FastifyInstance interface to include the 'fishjam' property for accessing the FishjamClient and declares the plugin using 'fastify-plugin'. The client is configured using environment variables loaded previously.
```javascript
import fastifyPlugin from "fastify-plugin";
import { FishjamClient } from "@fishjam-cloud/js-server-sdk";
declare module "fastify" {
interface FastifyInstance {
fishjam: FishjamClient;
config: {
FISHJAM_ID: string;
FISHJAM_MANAGEMENT_TOKEN: string;
};
}
}
export const fishjamPlugin = fastifyPlugin((fastify) => {
const fishjamClient = new FishjamClient({
fishjamId: fastify.config.FISHJAM_ID,
managementToken: fastify.config.FISHJAM_MANAGEMENT_TOKEN,
});
fastify.decorate("fishjam", fishjamClient);
});
```
--------------------------------
### Production Livestreaming Setup - TypeScript
Source: https://docs.fishjam.io/0.23.0/tutorials/livestreaming
Provides a TypeScript example using the `@fishjam-cloud/js-server-sdk` to set up a production livestream. It covers creating a room, generating streamer tokens, and generating viewer tokens.
```APIDOC
## Production Livestreaming Setup - TypeScript
### Description
This example demonstrates how to initialize a Fishjam backend application using the `@fishjam-cloud/js-server-sdk` in TypeScript. It outlines the necessary steps to create a livestream room, generate a streamer token, and generate a viewer token, which are essential for production environments.
### Method
N/A (Server-side SDK usage)
### Endpoint
N/A (Server-side SDK usage)
### Parameters
- **fishjamId** (string) - Required - The ID of your Fishjam instance.
- **managementToken** (string) - Required - The management token for authenticating with the Fishjam API.
- **room.id** (string) - The ID of the created room.
### Request Example
```typescript
import { FishjamClient } from '@fishjam-cloud/js-server-sdk';
const fishjamClient = new FishjamClient({
fishjamId,
managementToken,
});
// 1. Create a room of 'livestream' type
const room = await fishjamClient.createRoom({ roomType: 'livestream' });
// 2. Create a streamer token for the room
const { token: streamerToken } = await fishjamClient.createLivestreamStreamerToken(room.id);
// 3. Create a viewer token for the room
const { token: viewerToken } = await fishjamClient.createLivestreamViewerToken(room.id);
// These tokens should then be supplied to your frontend applications.
```
### Response
#### Success Response (200)
- **room** (object) - The created room object, containing `id`.
- **streamerToken** (string) - The generated token for streamers.
- **viewerToken** (string) - The generated token for viewers.
#### Response Example
N/A (Example shows SDK usage, not direct API response)
```
--------------------------------
### Setup Fishjam WebSocket Notifier Plugin for Fastify
Source: https://docs.fishjam.io/0.22.0/how-to/backend/fastify-example
Creates a Fastify plugin to establish a WebSocket connection with Fishjam for real-time event notifications. It initializes 'FishjamWSNotifier' using environment variables and sets up listeners for events like 'roomCreated' and 'peerAdded'. Error and closure handlers are also configured.
```javascript
import { type FastifyInstance } from "fastify";
import fp from "fastify-plugin";
import { FishjamWSNotifier } from "@fishjam-cloud/js-server-sdk";
export const fishjamNotifierPlugin = fp((fastify) => {
const fishjamId = fastify.config.FISHJAM_ID;
const managementToken = fastify.config.FISHJAM_MANAGEMENT_TOKEN;
const fishjamNotifier = new FishjamWSNotifier(
{ fishjamId, managementToken },
(err) => fastify.log.error(err),
() => fastify.log.info("Websocket connection to Fishjam closed"),
);
// handle the messages
const handleRoomCreated = console.log;
const handlePeerAdded = console.log;
fishjamNotifier.on("roomCreated", handleRoomCreated);
fishjamNotifier.on("peerAdded", handlePeerAdded);
});
```
--------------------------------
### Production Livestream Setup with Server SDKs
Source: https://docs.fishjam.io/0.22.0/tutorials/livestreaming
Provides examples for setting up a production backend to manage livestreams. It demonstrates creating a room, generating streamer tokens, and generating viewer tokens using both TypeScript and Python server SDKs.
```typescript
import { FishjamClient } from '@fishjam-cloud/js-server-sdk';
const fishjamClient = new FishjamClient({
fishjamId,
managementToken,
});
// 1.
const room = await fishjamClient.createRoom({ roomType: 'livestream' });
// 2.
const { token: streamerToken } = await fishjamClient.createLivestreamStreamerToken(room.id);
// 3.
const { token: viewerToken } = await fishjamClient.createLivestreamViewerToken(room.id);
```
```python
from fishjam import FishjamClient
fishjam_client = FishjamClient(
fishjam_id=fishjam_id,
management_token=management_token,
);
# 1.
room = fishjam_client.create_room(room_type="livestream")
# 2.
streamer_token = fishjam_client.create_livestream_streamer_token(room.id)
# 3.
viewer_token = fishjam_client.create_livestream_viewer_token(room.id)
```
--------------------------------
### Setup Fishjam Context with FishjamProvider
Source: https://docs.fishjam.io/0.22.0/how-to/react/installation
Sets up the Fishjam context in a React application by wrapping the main App component with FishjamProvider. Requires a Fishjam ID obtained from the Fishjam Dashboard. This allows child components to access Fishjam functionalities.
```javascript
import React from "react";
import ReactDOM from "react-dom/client";
// import App from "./App";
import { FishjamProvider } from "@fishjam-cloud/react-client";
// Check https://fishjam.io/app/ for your Fishjam ID
const FISHJAM_ID = "your-fishjam-id";
ReactDOM.createRoot(document.getElementById("root")!).render(
,
);
```
--------------------------------
### Join Room and Start Streaming Button (React Native)
Source: https://docs.fishjam.io/tutorials/react-native-quick-start
This component creates a button that, when pressed, prepares the camera, obtains a peer token (using a sandbox API in this example), and joins a specified Fishjam room. It utilizes hooks from '@fishjam-cloud/react-native-client' for camera management and connection.
```javascript
import React, { useCallback } from "react";
import { Button } from "react-native";
import {
useCamera,
useConnection,
useSandbox,
} from "@fishjam-cloud/react-native-client";
// Check https://fishjam.io/app for your Fishjam ID
const FISHJAM_ID = "YOUR_FISHJAM_ID";
export function StartStreamingButton({
roomName,
peerName,
}: { roomName: string; peerName: string }) {
const { prepareCamera } = useCamera();
const { joinRoom } = useConnection();
const { getSandboxPeerToken } = useSandbox({ fishjamId: FISHJAM_ID });
const startStreaming = useCallback(async () => {
// In sandbox environment, you can get the peer token from our sandbox API
// In production environment, you need to get it from your backend
const peerToken = await getSandboxPeerToken(roomName, peerName);
// Prepare camera
await prepareCamera({ cameraEnabled: true });
// Join the room
await joinRoom({ peerToken, fishjamId: FISHJAM_ID });
}, [joinRoom, prepareCamera, roomName, peerName]);
return ;
}
```
--------------------------------
### Install Fishjam Server SDK
Source: https://docs.fishjam.io/0.23.0/how-to/backend/server-setup
Instructions for installing the Fishjam server SDK using package managers for Node.js (npm, yarn) and Python (pip, poetry).
```APIDOC
## Install Fishjam Server SDK
This section provides installation instructions for the Fishjam server SDK for both Node.js and Python environments.
### Node.js
**Using npm:**
```bash
npm install @fishjam-cloud/js-server-sdk
```
**Using yarn:**
```bash
yarn add @fishjam-cloud/js-server-sdk
```
### Python
**Using pip:**
```bash
pip install fishjam-server-sdk
```
**Using poetry:**
```bash
poetry add fishjam-server-sdk
```
```
--------------------------------
### Curated Stage & Audience Example (Python)
Source: https://docs.fishjam.io/next/how-to/features/selective-subscriptions
This example demonstrates how to implement a curated stage and audience system using FishJam IO in Python. It shows how to create an audience peer in manual subscription mode and subscribe the audience to all current speakers.
```APIDOC
## Step 5 — Example: Curated Stage & Audience (Python)
### Description
Implement a "stage" system where speakers are in auto mode and audience members are manual subscribers.
### Method
N/A (Client-side code example)
### Endpoint
N/A (Client-side code example)
### Parameters
N/A (Client-side code example)
### Request Example
```python
audience = fishjam_client.create_peer(room.id, PeerOptions(subscribe_mode="manual"))
current_speakers = fishjam_client.get_room(room.id).peers
# audience peer already exists (manual)
for speaker in current_speakers:
fishjam_client.subscribe_peer(room.id, audience.id, speaker.id)
```
### Response
N/A (Client-side code example)
```
--------------------------------
### Join Room and Start Streaming with Fishjam React Native
Source: https://docs.fishjam.io/0.22.0/tutorials/react-native-quick-start
This component allows a user to join a Fishjam room and start streaming their video. It utilizes hooks from the '@fishjam-cloud/react-native-client' library to manage camera preparation and room connection. Ensure you have a valid FISHJAM_ID.
```javascript
import React, { useCallback } from "react";
import { Button } from "react-native";
import {
useCamera,
useConnection,
useSandbox,
} from "@fishjam-cloud/react-native-client";
// Check https://fishjam.io/app for your Fishjam ID
const FISHJAM_ID = "YOUR_FISHJAM_ID";
export function StartStreamingButton({
roomName,
peerName,
}: { roomName: string; peerName: string }) {
const { prepareCamera } = useCamera();
const { joinRoom } = useConnection();
const { getSandboxPeerToken } = useSandbox({ fishjamId: FISHJAM_ID });
const startStreaming = useCallback(async () => {
// In sandbox environment, you can get the peer token from our sandbox API
// In production environment, you need to get it from your backend
const peerToken = await getSandboxPeerToken(roomName, peerName);
// Prepare camera
await prepareCamera({ cameraEnabled: true });
// Join the room
await joinRoom({ peerToken, fishjamId: FISHJAM_ID });
}, [joinRoom, prepareCamera, roomName, peerName]);
return ;
}
```
--------------------------------
### Install Fishjam React Native Client
Source: https://docs.fishjam.io/0.22.0/how-to/react-native/installation
Commands to install the '@fishjam-cloud/react-native-client' package using different package managers: npm, Yarn, pnpm, and Bun. Choose the command that corresponds to your project's package manager.
```bash
npm install @fishjam-cloud/react-native-client
```
```bash
yarn add @fishjam-cloud/react-native-client
```
```bash
pnpm add @fishjam-cloud/react-native-client
```
```bash
bun add @fishjam-cloud/react-native-client
```
--------------------------------
### Install Fishjam and Google GenAI SDK (TypeScript)
Source: https://docs.fishjam.io/0.23.0/tutorials/gemini-live-integration
Installs the Fishjam JavaScript server SDK and the Google GenAI SDK for TypeScript projects. This is a prerequisite for integrating Fishjam with Google services.
```bash
npm install @fishjam-cloud/js-server-sdk @google/genai
```
--------------------------------
### Install Fishjam with Gemini Extra (Python)
Source: https://docs.fishjam.io/0.23.0/tutorials/gemini-live-integration
Installs the Fishjam Python server SDK with the 'gemini' extra, which includes the necessary libraries for Google Gemini integration. This command ensures all required dependencies are met.
```bash
pip install "fishjam-server-sdk[gemini]"
```
--------------------------------
### Join Room and Start Streaming in React
Source: https://docs.fishjam.io/0.22.0/tutorials/react-quick-start
A React component that handles joining a room and starting video streaming. It uses Fishjam hooks to initialize devices, get a sandbox peer token, and join the room. Note that in production, the peer token should be obtained from your backend.
```jsx
import React from "react";
import {
useConnection,
useCamera,
useInitializeDevices,
useSandbox,
} from "@fishjam-cloud/react-client";
export function JoinRoomButton() {
const { joinRoom } = useConnection();
const { selectCamera } = useCamera();
const { initializeDevices } = useInitializeDevices();
const { getSandboxPeerToken } = useSandbox();
const handleJoinRoom = async () => {
const roomName = "testRoom";
const peerName = "testUser";
// In sandbox environment, you can get the peer token from our sandbox API
// In production environment, you need to get it from your backend
const peerToken = await getSandboxPeerToken(roomName, peerName);
// Start camera by selecting the first available camera
await initializeDevices({ enableAudio: false }); // or just initializeDevices(); if you want both camera and mic
// Join the room
await joinRoom({ peerToken });
};
return ;
}
```
--------------------------------
### Request Camera and Microphone Permissions with Hooks
Source: https://docs.fishjam.io/next/how-to/react-native/installation
Example of using `useCameraPermissions` and `useMicrophonePermissions` hooks from the Fishjam client to request camera and microphone permissions in a React Native component. It demonstrates how to get the permission status and trigger the request.
```javascript
import {
useCameraPermissions,
useMicrophonePermissions,
} from "@fishjam-cloud/react-native-client";
import { useEffect } from "react";
const [cameraPermission, requestCameraPermission, getCameraPermission] =
useCameraPermissions();
const [
microphonePermission,
requestMicrophonePermission,
getMicrophonePermission,
] =
useMicrophonePermissions();
useEffect(() => {
requestCameraPermission();
requestMicrophonePermission();
}, []);
```
--------------------------------
### Run Python Server with FastAPI
Source: https://docs.fishjam.io/0.22.0/tutorials/backend-quick-start
Command to run the FastAPI Python server, specifying the port.
```bash
fastapi run --port 3000
```
--------------------------------
### Run Node.js/TypeScript Server
Source: https://docs.fishjam.io/0.22.0/tutorials/backend-quick-start
Commands to execute the Node.js/TypeScript backend server, either directly using tsx or by compiling to JavaScript first.
```bash
# If using TypeScript directly
npx tsx server.ts
# Or compile and run
npx tsc server.ts && node server.js
```
--------------------------------
### Setup your client
Source: https://docs.fishjam.io/0.22.0/how-to/backend/server-setup
Set up your client to communicate with a Fishjam instance by obtaining your Fishjam ID and Management Token from the developer panel and initializing the client.
```APIDOC
## Setup your client
Let's setup everything you need to start communicating with a Fishjam instance. First of all, view your app in the **Fishjam developer panel** and copy your **Fishjam ID** and the **Management Token**. They are required to proceed. Now, we are ready to dive into the code.
### Typescript
```typescript
import { FishjamClient } from '@fishjam-cloud/js-server-sdk';
const fishjamId = process.env.FISHJAM_ID;
const managementToken = process.env.FISHJAM_MANAGEMENT_TOKEN;
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
```
### Python
```python
import os
from fishjam import FishjamClient
fishjam_id = os.environ["FISHJAM_ID"]
management_token = os.environ["FISHJAM_MANAGEMENT_TOKEN"]
fishjam_client = FishjamClient(fishjam_id, management_token)
```
```
--------------------------------
### POST /join-room
Source: https://docs.fishjam.io/0.22.0/tutorials/backend-quick-start
Creates a new room and adds a peer to it. It returns the room ID and a peer token for the client to join the room.
```APIDOC
## POST /join-room
### Description
Creates a new room and adds a peer to it. It returns the room ID and a peer token for the client to join the room.
### Method
POST
### Endpoint
/join-room
### Parameters
#### Request Body
- **roomName** (string) - Required - The name of the room to create.
- **peerName** (string) - Required - The name of the peer to add to the room.
### Request Example (Node.js/TypeScript)
```json
{
"roomName": "test-room",
"peerName": "test-user"
}
```
### Request Example (Python)
```json
{
"room_name": "test-room",
"peer_name": "test-user"
}
```
### Response
#### Success Response (200)
- **roomId** / **room_id** (string) - The ID of the created room.
- **peerToken** / **peer_token** (string) - The token for the client to join the room.
#### Response Example (Node.js/TypeScript)
```json
{
"roomId": "some-room-id",
"peerToken": "some-peer-token"
}
```
#### Response Example (Python)
```json
{
"room_id": "some-room-id",
"peer_token": "some-peer-token"
}
```
```
--------------------------------
### Join Room and Start Streaming with React Native
Source: https://docs.fishjam.io/0.23.0/tutorials/react-native-quick-start
This component joins a specified room and initiates video streaming. It utilizes the `useCamera`, `useConnection`, and `useSandbox` hooks from the Fishjam React Native client. The `getSandboxPeerToken` function is used for obtaining a peer token, followed by preparing the camera and joining the room.
```javascript
import React, { useCallback } from "react";
import { Button } from "react-native";
import {
useCamera,
useConnection,
useSandbox,
} from "@fishjam-cloud/react-native-client";
// Check https://fishjam.io/app for your Fishjam ID
const FISHJAM_ID = "YOUR_FISHJAM_ID";
export function StartStreamingButton({
roomName,
peerName,
}: {
roomName: string;
peerName: string;
}) {
const { prepareCamera } = useCamera();
const { joinRoom } = useConnection();
const { getSandboxPeerToken } = useSandbox({ fishjamId: FISHJAM_ID });
const startStreaming = useCallback(async () => {
// In sandbox environment, you can get the peer token from our sandbox API
// In production environment, you need to get it from your backend
const peerToken = await getSandboxPeerToken(roomName, peerName);
// Prepare camera
await prepareCamera({ cameraEnabled: true });
// Join the room
await joinRoom({ peerToken, fishjamId: FISHJAM_ID });
}, [joinRoom, prepareCamera, roomName, peerName]);
return ;
}
```
--------------------------------
### Request Camera and Microphone Permissions using Hooks
Source: https://docs.fishjam.io/0.22.0/how-to/react-native/installation
Example of using the `useCameraPermissions` and `useMicrophonePermissions` hooks from '@fishjam-cloud/react-native-client' to request and manage camera and microphone permissions. The example demonstrates requesting permissions on component mount using `useEffect`.
```javascript
import {
useCameraPermissions,
useMicrophonePermissions,
} from "@fishjam-cloud/react-native-client";
import { useEffect } from "react";
const [cameraPermission, requestCameraPermission, getCameraPermission] =
useCameraPermissions();
const [
microphonePermission,
requestMicrophonePermission,
getMicrophonePermission,
] = useMicrophonePermissions();
useEffect(() => {
requestCameraPermission();
requestMicrophonePermission();
}, []);
```
--------------------------------
### Curated Stage & Audience Example (Python)
Source: https://docs.fishjam.io/0.23.0/how-to/features/selective-subscriptions
This example demonstrates how to set up a curated stage and audience system using the Fishjam client in Python. It shows how to fetch room peers and subscribe audience members in manual mode to specific speakers.
```APIDOC
### Request Example (Python)
```python
audience = fishjam_client.create_peer(room.id, PeerOptions(subscribe_mode="manual"))
current_speakers = fishjam_client.get_room(room.id).peers
# audience peer already exists (manual)
for speaker in current_speakers:
fishjam_client.subscribe_peer(room.id, audience.id, speaker.id)
```
As new speakers join, simply call `subscribe_peer` again to add them to the audience’s feed.
```
--------------------------------
### Configure iOS Info.plist Entries for Permissions
Source: https://docs.fishjam.io/0.22.0/tutorials/react-native-quick-start
Provides the specific key-value pairs for camera and microphone usage descriptions to be added to the Info.plist file for iOS applications.
```xml
NSCameraUsageDescriptionAllow $(PRODUCT_NAME) to access your camera.NSMicrophoneUsageDescriptionAllow $(PRODUCT_NAME) to access your microphone.
```
--------------------------------
### Constructor: FishjamAgent
Source: https://docs.fishjam.io/api/server/classes/FishjamAgent
Initializes a new FishjamAgent instance.
```APIDOC
## Constructor: FishjamAgent
### Description
Initializes a new FishjamAgent instance.
### Method
`new FishjamAgent`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```json
{
"config": "FishjamConfig",
"agentToken": "string",
"callbacks?": "AgentCallbacks"
}
```
### Response
#### Success Response (200)
`FishjamAgent`
#### Response Example
```json
{
"instance": "FishjamAgent"
}
```
```
--------------------------------
### Complete Picture in Picture Example with Video Call
Source: https://docs.fishjam.io/0.23.0/how-to/react-native/picture-in-picture
A comprehensive React Native example showcasing the implementation of Picture in Picture mode within a video call interface using the FishJam client. It utilizes `PipContainerView` with automatic start and stop configurations, and renders local and remote video tracks.
```javascript
import React from "react";
import { FlatList, StyleSheet, View } from "react-native";
import {
PipContainerView,
usePeers,
VideoRendererView,
} from "@fishjam-cloud/react-native-client";
export function VideoCallScreen() {
const { localPeer, remotePeers } = usePeers();
return (
{/* Render local video */}
{localPeer?.tracks.map((track) => {
if (track.type === "Video") {
return (
);
}
})}
{/* Render remote videos */}
peer.id}
renderItem={({ item: peer }) => (
{peer.tracks.map((track) => {
if (track.type === "Video") {
return (
);
}
})}
)}
/>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
video: {
width: "100%",
height: 200,
},
});
```
--------------------------------
### Create Fishjam Room and Peer (Python)
Source: https://docs.fishjam.io/0.22.0/tutorials/agents
Initializes the Fishjam client and creates a room and a peer within that room using the Python SDK. This is a prerequisite for creating agents.
```python
from fishjam import FishjamClient
fishjam_client = FishjamClient(fishjam_id, management_token)
room = fishjam_client.create_room()
peer = fishjam_client.create_peer(room.id)
```
--------------------------------
### Add Peer to Room (Node.js)
Source: https://docs.fishjam.io/0.23.0/tutorials/backend-quick-start
Adds a peer to a specified room and generates a peer token for client authentication. The peer's ID and token are logged, and both are returned.
```javascript
async function addPeer(roomId, peerName) {
const { peer, peerToken } = await fishjamClient.createPeer(roomId, {
metadata: { name: peerName },
});
console.log('Peer created:', peer.id);
console.log('Peer token:', peerToken);
return { peer, peerToken };
}
```
--------------------------------
### Configure iOS Info.plist for Permissions
Source: https://docs.fishjam.io/0.22.0/tutorials/react-native-quick-start
Sets up descriptions for camera and microphone usage alerts in the app.json for Expo projects, which are reflected in the Info.plist file on iOS.
```json
{
"expo": {
...
"ios": {
...
"infoPlist": {
"NSCameraUsageDescription": "Allow $(PRODUCT_NAME) to access your camera.",
"NSMicrophoneUsageDescription": "Allow $(PRODUCT_NAME) to access your microphone."
}
},
}
}
```
--------------------------------
### Add Peer to Room (Python)
Source: https://docs.fishjam.io/0.23.0/tutorials/backend-quick-start
Adds a peer to a specified room with given metadata and generates a peer token. The peer ID and token are printed, and the peer and token objects are returned.
```python
from fishjam import PeerOptions
def add_peer(room_id, peer_name):
options = PeerOptions(metadata={"name": peer_name})
peer, peer_token = fishjam_client.create_peer(room_id, options=options)
print(f'Peer created: {peer.id}')
print(f'Peer token: {peer_token}')
return peer, peer_token
```
--------------------------------
### Create Python API Endpoint for Fishjam using FastAPI
Source: https://docs.fishjam.io/next/tutorials/backend-quick-start
This snippet demonstrates creating a simple HTTP POST endpoint '/join-room' using Python and FastAPI. It uses the Fishjam Python SDK to create a room and add a peer, returning the room ID and a peer token. Requires FastAPI and the Fishjam Python SDK.
```python
import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from fishjam import FishjamClient, PeerOptions
app = FastAPI()
fishjam_client = FishjamClient(
os.environ["FISHJAM_ID"],
os.environ["FISHJAM_MANAGEMENT_TOKEN"]
)
class JoinRoomRequest(BaseModel):
room_name: str
peer_name: str
@app.post("/join-room")
async def join_room(request: JoinRoomRequest):
try:
# Create room
room = fishjam_client.create_room()
# Add peer
options = PeerOptions(metadata={"name": request.peer_name})
peer, peer_token = fishjam_client.create_peer(room.id, options=options)
return {
"room_id": room.id,
"peer_token": peer_token,
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
```
--------------------------------
### Register Fishjam and Notifier Plugins in Fastify
Source: https://docs.fishjam.io/0.22.0/how-to/backend/fastify-example
Shows the final step of registering both the Fishjam client plugin and the Fishjam WebSocket notifier plugin within a Fastify application. This ensures that both functionalities are available after the server starts.
```javascript
await fastify.register(fishjamPlugin);
await fastify.register(fishjamNotifierPlugin);
```
--------------------------------
### Load Environment Variables to Fastify with @fastify/env
Source: https://docs.fishjam.io/0.22.0/how-to/backend/fastify-example
Loads environment variables required for Fishjam into a Fastify instance using the '@fastify/env' package. It expects 'FISHJAM_ID' and 'FISHJAM_MANAGEMENT_TOKEN' to be defined in the environment. This setup is crucial before registering the Fishjam plugin.
```javascript
import Fastify from "fastify";
import fastifyEnv from "@fastify/env";
const fastify = Fastify();
const envSchema = {
type: "object",
required: ["FISHJAM_ID", "FISHJAM_MANAGEMENT_TOKEN"],
properties: {
FISHJAM_ID: {
type: "string",
},
FISHJAM_MANAGEMENT_TOKEN: {
type: "string",
},
},
};
await fastify.register(fastifyEnv, { schema: envSchema });
fastify.listen({ port: 3000 });
```
--------------------------------
### Manage Rooms (Python)
Source: https://docs.fishjam.io/how-to/backend/server-setup
Shows how to create, retrieve, and delete a room using the FishjamClient in Python. Assumes the FishjamClient has been initialized.
```python
created_room = fishjam_client.create_room()
the_same_room = fishjam_client.get_room(created_room.id)
fishjam_client.delete_room(the_same_room.id)
# puff, it's gone!
```
--------------------------------
### Display Local Camera Stream in React
Source: https://docs.fishjam.io/0.22.0/tutorials/react-quick-start
A React component that displays the local user's video stream. It utilizes the `useCamera` hook from the Fishjam client to access the `cameraStream` and passes it to the `VideoPlayer` component.
```jsx
import React from "react";
import { useCamera } from "@fishjam-cloud/react-client";
// Assuming VideoPlayer component is defined elsewhere and accepts a stream prop
// function VideoPlayer({ stream }: { stream: MediaStream | null | undefined }) { ... }
export function MyVideo() {
const { cameraStream } = useCamera();
return ;
}
```
--------------------------------
### Monitor Connection Status in React
Source: https://docs.fishjam.io/0.22.0/tutorials/react-quick-start
A React component that displays the current connection status of the user. It uses the `useConnection` hook to access the `peerStatus` and renders it to the UI. This helps in providing feedback to the user about their connection state.
```jsx
import React from "react";
import { useConnection } from "@fishjam-cloud/react-client";
export function ConnectionStatus() {
const { peerStatus } = useConnection();
return
Status: {peerStatus}
;
}
```
--------------------------------
### Set up FishjamProvider in React App
Source: https://docs.fishjam.io/0.22.0/tutorials/react-quick-start
Wraps your React application with the FishjamProvider component. This context is essential for using Fishjam hooks and managing the connection within your app. Ensure you replace 'YOUR_FISHJAM_ID' with your actual Fishjam ID.
```jsx
// Check https://fishjam.io/app/ for your Fishjam ID
const FISHJAM_ID = "YOUR_FISHJAM_ID";
ReactDOM.createRoot(document.getElementById("root")!).render(
,
);
```
--------------------------------
### React Video Player Component
Source: https://docs.fishjam.io/0.22.0/tutorials/react-quick-start
A React component to display a media stream in a video element. It utilizes `useRef` to access the video element and `useEffect` to set the `srcObject` when the stream changes. It requires a `MediaStream` object as a prop.
```jsx
function VideoPlayer({ stream }: { stream: MediaStream | null | undefined }) {
const videoRef = useRef(null);
useEffect(() => {
if (!videoRef.current) return;
videoRef.current.srcObject = stream ?? null;
}, [stream]);
return ;
}
```