Create basic client tutorial for Angular

This commit is contained in:
juancarmore 2024-05-07 08:29:45 +02:00
parent 040d08efd1
commit ee80b29d87
27 changed files with 13479 additions and 1 deletions

View File

@ -0,0 +1,17 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
max_line_length = 120
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false

42
basic/frontend/angular/.gitignore vendored Normal file
View File

@ -0,0 +1,42 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db

View File

@ -0,0 +1,27 @@
# Angular
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 17.3.6.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities.
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page.

View File

@ -0,0 +1,95 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"angular": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/angular",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "angular:build:production"
},
"development": {
"buildTarget": "angular:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"buildTarget": "angular:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing"
],
"tsConfig": "tsconfig.spec.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
}
}
}
}
}
}

12585
basic/frontend/angular/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,36 @@
{
"name": "basic-angular",
"version": "1.0.0",
"scripts": {
"start": "ng serve --port=5080 --host=0.0.0.0 --disable-host-check",
"build": "ng build"
},
"private": true,
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"livekit-client": "2.1.3",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.3.6",
"@angular/cli": "^17.3.6",
"@angular/compiler-cli": "^17.3.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.4.2"
}
}

View File

@ -0,0 +1,138 @@
#join {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#openvidu-logo {
height: 150px;
width: auto;
margin-top: 3em;
margin-bottom: 3em;
}
#join-dialog {
width: 70%;
max-width: 900px;
padding: 60px;
border-radius: 6px;
text-align: center;
background-color: #f0f0f0;
}
#join-dialog h2 {
color: #4d4d4d;
font-size: 60px;
font-weight: bold;
text-align: center;
}
#join-dialog form {
text-align: left;
}
#join-dialog label {
display: block;
margin-bottom: 10px;
color: #0088aa;
font-weight: bold;
font-size: 20px;
}
.form-control {
width: 100%;
padding: 8px;
margin-bottom: 10px;
box-sizing: border-box;
color: #0088aa;
font-weight: bold;
}
.form-control:focus {
color: #0088aa;
border-color: #0088aa;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(0, 136, 170, 0.6);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(0, 136, 170, 0.6);
}
#join-dialog button {
display: block;
margin: 20px auto 0;
}
.btn {
font-weight: bold;
}
.btn-success {
background-color: #06d362;
border-color: #06d362;
}
.btn-success:hover {
background-color: #1abd61;
border-color: #1abd61;
}
#room {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#room-header {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
padding: 0 20px;
margin-bottom: 20px;
}
#room-title {
font-size: 2em;
font-weight: bold;
margin: 0;
}
#layout-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 10px;
justify-content: center;
align-items: center;
width: 100%;
max-width: 1250px;
height: 100%;
}
/* Media Queries */
@media screen and (max-width: 768px) {
#openvidu-logo {
height: 100px;
margin-top: 2em;
margin-bottom: 2em;
}
#join-dialog {
width: 90%;
padding: 30px;
}
#join-dialog h2 {
font-size: 40px;
}
}
@media screen and (max-width: 480px) {
#join-dialog {
width: 100%;
padding: 20px;
}
#join-dialog h2 {
font-size: 30px;
}
}

View File

@ -0,0 +1,41 @@
@if (!room) {
<div id="join">
<a href="http://www.openvidu.io/" target="_blank">
<img id="openvidu-logo" src="assets/images/openvidu_logo.png" alt="OpenVidu logo" />
</a>
<div id="join-dialog">
<h2>Join a Video Room</h2>
<form [formGroup]="roomForm" (ngSubmit)="joinRoom()">
<div>
<label for="participant-name">Participant</label>
<input formControlName="participantName" id="participant-name" class="form-control" type="text" />
</div>
<div>
<label for="room-name">Room</label>
<input formControlName="roomName" id="room-name" class="form-control" type="text" />
</div>
<button class="btn btn-lg btn-success" type="submit" [disabled]="!roomForm.valid">Join!</button>
</form>
</div>
</div>
} @else {
<div id="room">
<div id="room-header">
<h2 id="room-title">{{ roomForm.value.roomName }}</h2>
<button class="btn btn-danger" id="leave-room-button" (click)="leaveRoom()">Leave Room</button>
</div>
<div id="layout-container">
@if (localTrack) {
<video-component
[track]="localTrack"
[participantIdentity]="roomForm.value.participantName!"
[isLocal]="true"
></video-component>
} @for (publication of remoteTrackPublications.keys(); track publication.trackSid) { @if (publication.kind === "video") {
<video-component [track]="publication.videoTrack!" [participantIdentity]="getParticipantIdentity(publication)"></video-component>
} @else {
<audio-component [track]="castToRemoteAudioTrack(publication.audioTrack!)" hidden></audio-component>
} }
</div>
</div>
}

View File

@ -0,0 +1,138 @@
import { Component } from '@angular/core';
import { ReactiveFormsModule, FormControl, FormGroup, Validators } from '@angular/forms';
import {
LocalAudioTrack,
LocalVideoTrack,
RemoteAudioTrack,
RemoteParticipant,
RemoteTrack,
RemoteTrackPublication,
Room,
RoomEvent,
} from 'livekit-client';
import { VideoComponent } from './video/video.component';
import { AudioComponent } from './audio/audio.component';
import { HttpClient } from '@angular/common/http';
import { lastValueFrom } from 'rxjs';
// 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 = '';
@Component({
selector: 'app-root',
standalone: true,
imports: [ReactiveFormsModule, AudioComponent, VideoComponent],
templateUrl: './app.component.html',
styleUrl: './app.component.css',
})
export class AppComponent {
roomForm = new FormGroup({
roomName: new FormControl('Test Room', Validators.required),
participantName: new FormControl('Participant' + Math.floor(Math.random() * 100), Validators.required),
});
room?: Room;
localTrack?: LocalVideoTrack;
remoteTrackPublications: Map<RemoteTrackPublication, string> = new Map();
constructor(private httpClient: HttpClient) {
this.configureUrls();
}
configureUrls() {
// 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/';
}
}
}
async joinRoom() {
// 1. Get a Room object
this.room = new Room();
// 2. Specify the actions when events take place in the room
// On every new Track received...
this.room.on(
RoomEvent.TrackSubscribed,
(_track: RemoteTrack, publication: RemoteTrackPublication, participant: RemoteParticipant) => {
this.remoteTrackPublications.set(publication, participant.identity);
}
);
// On every new Track destroyed...
this.room.on(
RoomEvent.TrackUnsubscribed,
(_track: RemoteTrack, publication: RemoteTrackPublication, _participant: RemoteParticipant) => {
this.remoteTrackPublications.delete(publication);
}
);
// 3. Connect to the room with a valid access token
try {
// Get a token from the application backend
const roomName = this.roomForm.value.roomName!;
const participantName = this.roomForm.value.participantName!;
const token = await this.getToken(roomName, participantName);
await this.room.connect(LIVEKIT_URL, token);
// 4. Publish your local tracks
await this.room.localParticipant.setMicrophoneEnabled(true);
const publication = await this.room.localParticipant.setCameraEnabled(true);
this.localTrack = publication?.videoTrack;
} catch (error: any) {
console.log('There was an error connecting to the room:', error?.message);
}
}
async leaveRoom() {
// 5. Leave the room by calling 'disconnect' method over the Room object
await this.room?.disconnect();
// Empty all properties...
delete this.room;
delete this.localTrack;
this.remoteTrackPublications.clear();
}
getParticipantIdentity(publication: RemoteTrackPublication): string {
return this.remoteTrackPublications.get(publication) || '';
}
castToRemoteAudioTrack(audioTrack: LocalAudioTrack | RemoteAudioTrack): RemoteAudioTrack {
return audioTrack as RemoteAudioTrack;
}
/**
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
* --------------------------------------------
* The method below request the creation of a token to
* your application server. This prevents the need to expose
* your LiveKit API key and secret to the client side.
*
* In this sample code, there is no user control at all. Anybody could
* access your application server endpoints. In a real production
* environment, your application server must identify the user to allow
* access to the endpoints.
*/
async getToken(roomName: string, participantName: string): Promise<string> {
return lastValueFrom(
this.httpClient.post<string>(APPLICATION_SERVER_URL + 'token', { roomName, participantName })
);
}
}

View File

@ -0,0 +1,6 @@
import { provideHttpClient } from '@angular/common/http';
import { ApplicationConfig } from '@angular/core';
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient()],
};

View File

@ -0,0 +1 @@
<audio #audioElement></audio>

View File

@ -0,0 +1,30 @@
import { Component, ElementRef, Input, ViewChild } from '@angular/core';
import { RemoteAudioTrack } from 'livekit-client';
@Component({
selector: 'audio-component',
standalone: true,
imports: [],
templateUrl: './audio.component.html',
styleUrl: './audio.component.css',
})
export class AudioComponent {
@ViewChild('audioElement') audioElement?: ElementRef<HTMLAudioElement>;
_track?: RemoteAudioTrack;
ngAfterViewInit() {
if (this._track && this.audioElement) {
this._track.attach(this.audioElement.nativeElement);
}
}
@Input()
set track(track: RemoteAudioTrack) {
this._track = track;
if (this.audioElement) {
this._track.attach(this.audioElement.nativeElement);
}
}
}

View File

@ -0,0 +1,44 @@
.video-container {
position: relative;
background: #3b3b3b;
aspect-ratio: 16/9;
border-radius: 6px;
overflow: hidden;
}
.video-container video {
width: 100%;
height: 100%;
}
.video-container .participant-data {
position: absolute;
top: 0;
left: 0;
}
.participant-data p {
background: #f8f8f8;
margin: 0;
padding: 0 5px;
color: #777777;
font-weight: bold;
border-bottom-right-radius: 4px;
}
/* Media Queries */
@media screen and (max-width: 768px) {
#layout-container {
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
}
@media screen and (max-width: 480px) {
#layout-container {
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
}
.video-container {
aspect-ratio: 9/16;
}
}

View File

@ -0,0 +1,6 @@
<div id="camera-{{ participantIdentity }}" class="video-container">
<div class="participant-data">
<p>{{ participantIdentity }} @if (isLocal) { (You)}</p>
</div>
<video #videoElement></video>
</div>

View File

@ -0,0 +1,32 @@
import { Component, ElementRef, Input, ViewChild } from '@angular/core';
import { LocalVideoTrack, RemoteVideoTrack } from 'livekit-client';
@Component({
selector: 'video-component',
standalone: true,
imports: [],
templateUrl: './video.component.html',
styleUrl: './video.component.css',
})
export class VideoComponent {
@ViewChild('videoElement') videoElement?: ElementRef<HTMLVideoElement>;
private _track?: LocalVideoTrack | RemoteVideoTrack;
@Input() participantIdentity?: string;
@Input() isLocal = false;
ngAfterViewInit() {
if (this._track && this.videoElement) {
this._track.attach(this.videoElement.nativeElement);
}
}
@Input()
set track(track: LocalVideoTrack | RemoteVideoTrack) {
this._track = track;
if (this.videoElement) {
this._track.attach(this.videoElement.nativeElement);
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

View File

@ -0,0 +1,64 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Basic Angular</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<!-- Bootstrap -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
crossorigin="anonymous"
/>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
crossorigin="anonymous"
></script>
<!-- Font Awesome -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
integrity="sha512-SnH5WK+bZxgPHs44uWIX+LLJAJ9/2PkPKZ5QiAj6Ta86w+fsb2TkcmfRyVX3pBnMFcV7oQPJkl9QevSCWr3W6A=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
</head>
<body>
<header>
<a href="/" title="Home"><h1>Basic JavaScript</h1></a>
<div id="links">
<a
href="https://github.com/OpenVidu/openvidu-livekit-tutorials/tree/master/basic/frontend/javascript"
title="GitHub Repository"
target="_blank"
>
<i class="fa-brands fa-github"></i>
</a>
<a
href="https://livekit-tutorials.openvidu.io/basic/frontend/javascript"
title="Documentation"
target="_blank"
>
<i class="fa-solid fa-book"></i>
</a>
</div>
</header>
<main>
<app-root></app-root>
</main>
<footer>
<p class="text">Made with love by <span>OpenVidu Team</span></p>
<a href="http://www.openvidu.io/" target="_blank">
<img id="openvidu-isotype" src="assets/images/openvidu_isotype.png" alt="OpenVidu isotype" />
</a>
</footer>
</body>
</html>

View File

@ -0,0 +1,6 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));

View File

@ -0,0 +1,110 @@
html {
height: 100%;
}
body {
margin: 0;
padding: 0;
padding-top: 50px;
display: flex;
flex-direction: column;
height: 100%;
}
header {
height: 50px;
width: 100%;
position: fixed;
top: 0;
left: 0;
z-index: 1;
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 30px;
background-color: #4d4d4d;
}
header h1 {
margin: 0;
font-size: 1.5em;
font-weight: bold;
}
header a {
color: #ccc;
text-decoration: none;
}
header a:hover {
color: #a9a9a9;
}
header i {
padding: 5px 5px;
font-size: 2em;
}
main {
flex: 1;
padding: 20px;
}
footer {
height: 60px;
width: 100%;
padding: 10px 30px;
display: flex;
justify-content: space-between;
align-items: center;
background-color: #4d4d4d;
}
footer a {
color: #ffffff;
text-decoration: none;
}
footer .text {
color: #ccc;
margin: 0;
}
footer .text span {
color: white;
font-weight: bold;
}
#openvidu-isotype {
height: 35px;
-webkit-transition: all 0.1s ease-in-out;
-moz-transition: all 0.1s ease-in-out;
-o-transition: all 0.1s ease-in-out;
transition: all 0.1s ease-in-out;
}
#openvidu-isotype:hover {
-webkit-filter: grayscale(0.5);
filter: grayscale(0.5);
}
/* Media Queries */
@media screen and (max-width: 768px) {
header {
padding: 10px 15px;
}
footer {
padding: 10px 15px;
}
}
@media screen and (max-width: 480px) {
header {
padding: 10px;
}
footer {
padding: 10px;
}
}

View File

@ -0,0 +1,14 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts"
],
"include": [
"src/**/*.d.ts"
]
}

View File

@ -0,0 +1,32 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"esModuleInterop": true,
"sourceMap": true,
"declaration": false,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "ES2022",
"module": "ES2022",
"useDefineForClassFields": false,
"lib": [
"ES2022",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}

View File

@ -0,0 +1,14 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}

View File

@ -22,7 +22,7 @@ cd openvidu-livekit-tutorials/basic/frontend/javascript
To run this tutorial, you will need a HTTP web server installed on your development computer. If you have Node.js installed, you can easily set up [http-server](https://github.com/indexzero/http-server):
```bash
npm install --global http-server
npm install -g http-server
```
After installing http-server, serve the tutorial: