Update server ports and Livekit URLs in backend tutorials and JS and Angular client tutorials

This commit is contained in:
juancarmore 2024-04-16 04:11:31 +02:00
parent 3145698c70
commit 791c6d8110
13 changed files with 62 additions and 98 deletions

View File

@ -8,7 +8,11 @@ import {
RemoteTrack,
LocalTrackPublication,
} from 'livekit-client';
import { environment } from '../environments/environment';
// For local development, leave these variables empty
// For production, configure them with correct URLs depending on your deployment
let APPLICATION_SERVER_URL = '';
let LIVEKIT_URL = '';
@Component({
selector: 'app-root',
@ -16,7 +20,6 @@ import { environment } from '../environments/environment';
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnDestroy {
APPLICATION_SERVER_URL = environment.applicationServerUrl;
room: Room;
localPublication: LocalTrackPublication;
remotePublications: RemoteTrackPublication[] = [];
@ -30,9 +33,30 @@ export class AppComponent implements OnDestroy {
mainPublication: LocalTrackPublication | RemoteTrackPublication;
constructor(private httpClient: HttpClient) {
this.generateUrls();
this.generateParticipantInfo();
}
generateUrls() {
// If APPLICATION_SERVER_URL is not configured, use default value from local development
if (!APPLICATION_SERVER_URL) {
if (window.location.hostname === 'localhost') {
APPLICATION_SERVER_URL = 'http://localhost:6080/';
} else {
APPLICATION_SERVER_URL = 'https://' + window.location.hostname + ':6443/';
}
}
// If LIVEKIT_URL is not configured, use default value from local development
if (!LIVEKIT_URL) {
if (window.location.hostname !== 'localhost') {
LIVEKIT_URL = 'ws://localhost:7880/';
} else {
LIVEKIT_URL = 'wss://' + window.location.hostname + ':7443/';
}
}
}
@HostListener('window:beforeunload')
beforeunloadHandler() {
// On window closed leave session
@ -82,11 +106,9 @@ export class AppComponent implements OnDestroy {
// Get a token from the application backend
this.getToken(this.myRoomName, this.myParticipantName).then(
async (token) => {
const livekitUrl = this.getLivekitUrlFromMetadata(token);
// First param is the LiveKit server URL. Second param is the access token
try {
await this.room.connect(livekitUrl, token);
await this.room.connect(LIVEKIT_URL, token);
// --- 4) Publish your local tracks ---
await this.room.localParticipant.setMicrophoneEnabled(true);
const videoPublication =
@ -161,32 +183,6 @@ export class AppComponent implements OnDestroy {
this.mainPublication = publication;
}
private getLivekitUrlFromMetadata(token: string): string {
if (!token)
throw new Error('Trying to get room metadata from an empty token');
try {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(
window
.atob(base64)
.split('')
.map((c) => {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
})
.join('')
);
const payload = JSON.parse(jsonPayload);
if (!payload?.metadata)
throw new Error('Token does not contain metadata');
const metadata = JSON.parse(payload.metadata);
return metadata.livekitUrl;
} catch (error) {
throw new Error('Error decoding and parsing token: ' + error);
}
}
/**
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
@ -202,11 +198,10 @@ export class AppComponent implements OnDestroy {
* Visit https://docs.openvidu.io/en/stable/application-server to learn
* more about the integration of OpenVidu in your application server.
*/
async getToken(roomName: string, participantName: string): Promise<string> {
return this.httpClient
.post(
this.APPLICATION_SERVER_URL + 'token',
APPLICATION_SERVER_URL + 'token',
{ roomName, participantName },
{
headers: { 'Content-Type': 'application/json' },

View File

@ -1,4 +1,3 @@
export const environment = {
production: true,
applicationServerUrl: '',
};

View File

@ -4,7 +4,6 @@
export const environment = {
production: false,
applicationServerUrl: 'http://localhost:5000/',
};
/*

View File

@ -35,11 +35,6 @@
<artifactId>livekit-server</artifactId>
<version>0.5.7</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20231013</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>

View File

@ -2,7 +2,6 @@ package io.openvidu.basic.java;
import java.util.Map;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@ -17,9 +16,6 @@ import io.livekit.server.*;
@RestController
public class Controller {
@Value("${LIVEKIT_URL}")
private String LIVEKIT_URL;
@Value("${LIVEKIT_API_KEY}")
private String LIVEKIT_API_KEY;
@ -44,12 +40,6 @@ public class Controller {
AccessToken token = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET);
token.setName(participantName);
token.setIdentity(participantName);
JSONObject metadata = new JSONObject();
metadata.put("livekitUrl", LIVEKIT_URL);
// add metadata to the token, which will be available in the participant's metadata
token.setMetadata(metadata.toString());
token.addGrants(new RoomJoin(true), new RoomName(roomName));
return new ResponseEntity<>(token.toJwt(), HttpStatus.OK);

View File

@ -1,6 +1,5 @@
server.port: 5000
server.port: 6080
server.ssl.enabled: false
LIVEKIT_URL: ws://localhost:7880/
LIVEKIT_API_KEY: http://localhost:4443/
LIVEKIT_API_SECRET: MY_SECRET
LIVEKIT_API_KEY: devkey
LIVEKIT_API_SECRET: secret

View File

@ -1,4 +1,3 @@
SERVER_PORT=5000
LIVEKIT_URL=ws://localhost:7880/
SERVER_PORT=6080
LIVEKIT_API_KEY=devkey
LIVEKIT_API_SECRET=secret

View File

@ -9,7 +9,7 @@ var cors = require('cors');
var app = express();
// Environment variable: PORT where the node server is listening
var SERVER_PORT = process.env.SERVER_PORT || 5000;
var SERVER_PORT = process.env.SERVER_PORT || 6080;
// Environment variable: api key shared with our LiveKit deployment
var LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY || 'devkey';
// Environment variable: api secret shared with our LiveKit deployment
@ -48,8 +48,6 @@ app.post('/token', (req, res) => {
const at = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, {
identity: participantName,
// add metadata to the token, which will be available in the participant's metadata
metadata: JSON.stringify({ livekitUrl: process.env.LIVEKIT_URL }),
});
at.addGrant({ roomJoin: true, room: roomName });
const token = at.toJwt();

View File

@ -1,4 +1,3 @@
SERVER_PORT=5000
LIVEKIT_URL=ws://localhost:7880/
SERVER_PORT=6080
LIVEKIT_API_KEY=devkey
LIVEKIT_API_SECRET=secret

View File

@ -3,6 +3,9 @@ import requests
import livekit
from flask import Flask, request
from flask_cors import CORS
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
@ -11,7 +14,6 @@ cors = CORS(app, resources={r"/*": {"origins": "*"}})
# Load env variables
SERVER_PORT = os.environ.get("SERVER_PORT")
LIVEKIT_URL = os.environ.get("LIVEKIT_URL")
LIVEKIT_API_KEY = os.environ.get("LIVEKIT_API_KEY")
LIVEKIT_API_SECRET = os.environ.get("LIVEKIT_API_SECRET")
@ -28,9 +30,8 @@ def getToken():
# Create a VideoGrant with the necessary permissions
grant = livekit.VideoGrant(room_join=True, room=room_name)
# Create an AccessToken with your API key, secret, and the VideoGrant
# Create an AccessToken with your API key, secret and the VideoGrant
access_token = livekit.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, grant=grant, identity=participant_name)
access_token.metadata = {"livekitUrl": LIVEKIT_URL}
# Generate the token
return access_token.to_jwt()

View File

@ -9,7 +9,6 @@ require './env.rb'
# Load env variables
SERVER_PORT = ENV['SERVER_PORT']
LIVEKIT_URL = ENV['LIVEKIT_URL']
LIVEKIT_API_KEY = ENV['LIVEKIT_API_KEY']
LIVEKIT_API_SECRET = ENV['LIVEKIT_API_SECRET']
@ -39,7 +38,6 @@ post '/token' do
token.identity = participant_name
token.name = participant_name
token.add_grant(roomJoin: true, room: room_name)
token.metadata = { "livekitUrl" => LIVEKIT_URL}
token.to_jwt
end

View File

@ -1,4 +1,3 @@
ENV['SERVER_PORT'] = '5000'
ENV['LIVEKIT_URL'] = 'ws://localhost:7880/'
ENV['SERVER_PORT'] = '6080'
ENV['LIVEKIT_API_KEY'] = 'devkey'
ENV['LIVEKIT_API_SECRET'] = 'secret'

View File

@ -1,3 +1,25 @@
// For local development, leave these variables empty
// For production, configure them with correct URLs depending on your deployment
var APPLICATION_SERVER_URL = '';
var LIVEKIT_URL = '';
// If APPLICATION_SERVER_URL is not configured, use default value from local development
if (!APPLICATION_SERVER_URL) {
if (window.location.hostname === 'localhost') {
APPLICATION_SERVER_URL = 'http://localhost:6080/';
} else {
APPLICATION_SERVER_URL = 'https://' + window.location.hostname + ':6443/';
}
}
// If LIVEKIT_URL is not configured, use default value from local development
if (!LIVEKIT_URL) {
if (window.location.hostname === 'localhost') {
LIVEKIT_URL = 'ws://localhost:7880/';
} else {
LIVEKIT_URL = 'wss://' + window.location.hostname + ':7443/';
}
}
var LivekitClient = window.LivekitClient;
var room;
@ -39,10 +61,8 @@ function joinRoom() {
// Get a token from the application backend
getToken(myRoomName, myUserName).then(token => {
const livekitUrl = getLivekitUrlFromMetadata(token);
// First param is the LiveKit server URL. Second param is the access token
room.connect(livekitUrl, token)
room.connect(LIVEKIT_URL, token)
.then(() => {
// --- 4) Set page layout for active call ---
@ -140,30 +160,6 @@ function initMainVideo(videoElement, userData) {
document.querySelector('#main-video video')['muted'] = true;
}
function getLivekitUrlFromMetadata(token) {
if (!token) throw new Error('Trying to get metadata from an empty token');
try {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(
window
.atob(base64)
.split('')
.map((c) => {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
})
.join('')
);
const payload = JSON.parse(jsonPayload);
if (!payload?.metadata) throw new Error('Token does not contain metadata');
const metadata = JSON.parse(payload.metadata);
return metadata.livekitUrl;
} catch (error) {
throw new Error('Error decoding and parsing token: ' + error);
}
}
/**
* --------------------------------------------
@ -178,9 +174,6 @@ function getLivekitUrlFromMetadata(token) {
* access to the endpoints.
*
*/
var APPLICATION_SERVER_URL = "http://localhost:5000/";
function getToken(roomName, participantName) {
return new Promise((resolve, reject) => {
$.ajax({