├── ui
├── src
│ ├── assets
│ │ └── .gitkeep
│ ├── app
│ │ ├── app.component.css
│ │ ├── app.component.html
│ │ ├── call
│ │ │ ├── Sdp.ts
│ │ │ ├── call.component.css
│ │ │ ├── call.component.html
│ │ │ ├── call.component.spec.ts
│ │ │ └── call.component.ts
│ │ ├── app.component.ts
│ │ ├── app-routing.module.ts
│ │ ├── app.module.ts
│ │ └── app.component.spec.ts
│ ├── favicon.ico
│ ├── environments
│ │ ├── environment.prod.ts
│ │ └── environment.ts
│ ├── styles.css
│ ├── index.html
│ ├── main.ts
│ ├── test.ts
│ └── polyfills.ts
├── proxyconfig.json
├── e2e
│ ├── tsconfig.json
│ ├── src
│ │ ├── app.po.ts
│ │ └── app.e2e-spec.ts
│ └── protractor.conf.js
├── .editorconfig
├── tsconfig.app.json
├── tsconfig.spec.json
├── browserslist
├── tsconfig.json
├── .gitignore
├── README.md
├── karma.conf.js
├── package.json
├── tslint.json
└── angular.json
├── server
├── .gitignore
├── signal.go
└── main.go
└── README.md
/ui/src/assets/.gitkeep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ui/src/app/app.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/server/.gitignore:
--------------------------------------------------------------------------------
1 | video
2 | go.mod
3 | go.sum
4 | info.log
--------------------------------------------------------------------------------
/ui/src/app/app.component.html:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ui/src/app/call/Sdp.ts:
--------------------------------------------------------------------------------
1 | export interface Sdp {
2 | Sdp: string;
3 | }
--------------------------------------------------------------------------------
/ui/src/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Ramez-/go-video-conference/HEAD/ui/src/favicon.ico
--------------------------------------------------------------------------------
/ui/src/environments/environment.prod.ts:
--------------------------------------------------------------------------------
1 | export const environment = {
2 | production: true
3 | };
4 |
--------------------------------------------------------------------------------
/ui/src/styles.css:
--------------------------------------------------------------------------------
1 | /* You can add global styles to this file, and also import other style files */
2 |
--------------------------------------------------------------------------------
/ui/src/app/call/call.component.css:
--------------------------------------------------------------------------------
1 | .layer2 {
2 | position: absolute;
3 | top: 0;
4 | }
5 |
6 | .container_row {
7 | height: 50px;
8 | margin-top: 100px;
9 | position: relative;
10 | }
--------------------------------------------------------------------------------
/ui/proxyconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "/webrtc/*": {
3 | "target": "http://localhost:8080",
4 | "secure": false,
5 | "localLever": "debug",
6 | "changeOrigin": true,
7 | "logLevel": "debug"
8 | }
9 | }
--------------------------------------------------------------------------------
/ui/src/app/app.component.ts:
--------------------------------------------------------------------------------
1 | import { Component } from '@angular/core';
2 |
3 | @Component({
4 | selector: 'app-root',
5 | templateUrl: './app.component.html',
6 | styleUrls: ['./app.component.css']
7 | })
8 | export class AppComponent {
9 | title = 'ui';
10 | }
11 |
--------------------------------------------------------------------------------
/ui/e2e/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../out-tsc/e2e",
5 | "module": "commonjs",
6 | "target": "es5",
7 | "types": [
8 | "jasmine",
9 | "jasminewd2",
10 | "node"
11 | ]
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/ui/.editorconfig:
--------------------------------------------------------------------------------
1 | # Editor configuration, see https://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | indent_style = space
7 | indent_size = 2
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.md]
12 | max_line_length = off
13 | trim_trailing_whitespace = false
14 |
--------------------------------------------------------------------------------
/ui/e2e/src/app.po.ts:
--------------------------------------------------------------------------------
1 | import { browser, by, element } from 'protractor';
2 |
3 | export class AppPage {
4 | navigateTo() {
5 | return browser.get(browser.baseUrl) as Promise;
6 | }
7 |
8 | getTitleText() {
9 | return element(by.css('app-root .content span')).getText() as Promise;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/ui/src/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Ui
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/ui/tsconfig.app.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "./out-tsc/app",
5 | "types": []
6 | },
7 | "files": [
8 | "src/main.ts",
9 | "src/polyfills.ts"
10 | ],
11 | "include": [
12 | "src/**/*.ts"
13 | ],
14 | "exclude": [
15 | "src/test.ts",
16 | "src/**/*.spec.ts"
17 | ]
18 | }
19 |
--------------------------------------------------------------------------------
/ui/tsconfig.spec.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "./out-tsc/spec",
5 | "types": [
6 | "jasmine",
7 | "node"
8 | ]
9 | },
10 | "files": [
11 | "src/test.ts",
12 | "src/polyfills.ts"
13 | ],
14 | "include": [
15 | "src/**/*.spec.ts",
16 | "src/**/*.d.ts"
17 | ]
18 | }
19 |
--------------------------------------------------------------------------------
/ui/src/app/call/call.component.html:
--------------------------------------------------------------------------------
1 |
4 |
5 |
--------------------------------------------------------------------------------
/ui/src/app/app-routing.module.ts:
--------------------------------------------------------------------------------
1 | import { NgModule } from '@angular/core';
2 | import { Routes, RouterModule } from '@angular/router';
3 | import { CallComponent } from './call/call.component';
4 |
5 |
6 | const routes: Routes = [{path: 'call', component: CallComponent }];
7 |
8 | @NgModule({
9 | imports: [RouterModule.forRoot(routes)],
10 | exports: [RouterModule]
11 | })
12 | export class AppRoutingModule { }
13 |
--------------------------------------------------------------------------------
/ui/src/main.ts:
--------------------------------------------------------------------------------
1 | import { enableProdMode } from '@angular/core';
2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
3 |
4 | import { AppModule } from './app/app.module';
5 | import { environment } from './environments/environment';
6 |
7 | if (environment.production) {
8 | enableProdMode();
9 | }
10 |
11 | platformBrowserDynamic().bootstrapModule(AppModule)
12 | .catch(err => console.error(err));
13 |
--------------------------------------------------------------------------------
/ui/browserslist:
--------------------------------------------------------------------------------
1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
2 | # For additional information regarding the format and rule options, please see:
3 | # https://github.com/browserslist/browserslist#queries
4 |
5 | # You can see what browsers were selected by your queries by running:
6 | # npx browserslist
7 |
8 | > 0.5%
9 | last 2 versions
10 | Firefox ESR
11 | not dead
12 | not IE 9-11 # For IE 9-11 support, remove 'not'.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # go-video-confrence
2 | Create a video conference application using Golang.
3 |
4 | This repository is part of a [medium post tutorial](https://medium.com/@ramezemadaiesec/from-zero-to-fully-functional-video-conference-app-using-go-and-webrtc-7d073c9287da)
5 | for creating a fully functional video confrence application from the complete beginning using webRTC in under 100 lines of code.
6 |
7 | ## Technologies used
8 |
9 | * [Golang](https://github.com/golang/go)
10 | * [Pion](https://github.com/pion/webrtc)
11 | * [Gin](https://github.com/gin-gonic/gin)
12 | * [Angular](https://github.com/angular/angular)
13 |
--------------------------------------------------------------------------------
/ui/src/app/app.module.ts:
--------------------------------------------------------------------------------
1 | import { BrowserModule } from '@angular/platform-browser';
2 | import { NgModule } from '@angular/core';
3 | import { HttpClientModule } from '@angular/common/http';
4 |
5 | import { AppRoutingModule } from './app-routing.module';
6 | import { AppComponent } from './app.component';
7 | import { CallComponent } from './call/call.component';
8 |
9 | @NgModule({
10 | declarations: [
11 | AppComponent,
12 | CallComponent
13 | ],
14 | imports: [
15 | BrowserModule,
16 | AppRoutingModule,
17 | HttpClientModule
18 | ],
19 | providers: [],
20 | bootstrap: [AppComponent]
21 | })
22 | export class AppModule { }
23 |
--------------------------------------------------------------------------------
/ui/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compileOnSave": false,
3 | "compilerOptions": {
4 | "baseUrl": "./",
5 | "outDir": "./dist/out-tsc",
6 | "sourceMap": true,
7 | "declaration": false,
8 | "downlevelIteration": true,
9 | "experimentalDecorators": true,
10 | "module": "esnext",
11 | "moduleResolution": "node",
12 | "importHelpers": true,
13 | "target": "es2015",
14 | "typeRoots": [
15 | "node_modules/@types"
16 | ],
17 | "lib": [
18 | "es2018",
19 | "dom"
20 | ]
21 | },
22 | "angularCompilerOptions": {
23 | "fullTemplateTypeCheck": true,
24 | "strictInjectionParameters": true
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/ui/src/test.ts:
--------------------------------------------------------------------------------
1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files
2 |
3 | import 'zone.js/dist/zone-testing';
4 | import { getTestBed } from '@angular/core/testing';
5 | import {
6 | BrowserDynamicTestingModule,
7 | platformBrowserDynamicTesting
8 | } from '@angular/platform-browser-dynamic/testing';
9 |
10 | declare const require: any;
11 |
12 | // First, initialize the Angular testing environment.
13 | getTestBed().initTestEnvironment(
14 | BrowserDynamicTestingModule,
15 | platformBrowserDynamicTesting()
16 | );
17 | // Then we find all the tests.
18 | const context = require.context('./', true, /\.spec\.ts$/);
19 | // And load the modules.
20 | context.keys().map(context);
21 |
--------------------------------------------------------------------------------
/ui/e2e/src/app.e2e-spec.ts:
--------------------------------------------------------------------------------
1 | import { AppPage } from './app.po';
2 | import { browser, logging } from 'protractor';
3 |
4 | describe('workspace-project App', () => {
5 | let page: AppPage;
6 |
7 | beforeEach(() => {
8 | page = new AppPage();
9 | });
10 |
11 | it('should display welcome message', () => {
12 | page.navigateTo();
13 | expect(page.getTitleText()).toEqual('ui app is running!');
14 | });
15 |
16 | afterEach(async () => {
17 | // Assert that there are no errors emitted from the browser
18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER);
19 | expect(logs).not.toContain(jasmine.objectContaining({
20 | level: logging.Level.SEVERE,
21 | } as logging.Entry));
22 | });
23 | });
24 |
--------------------------------------------------------------------------------
/ui/src/app/call/call.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { CallComponent } from './call.component';
4 |
5 | describe('CallComponent', () => {
6 | let component: CallComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ CallComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(CallComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/ui/src/environments/environment.ts:
--------------------------------------------------------------------------------
1 | // This file can be replaced during build by using the `fileReplacements` array.
2 | // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
3 | // The list of file replacements can be found in `angular.json`.
4 |
5 | export const environment = {
6 | production: false
7 | };
8 |
9 | /*
10 | * For easier debugging in development mode, you can import the following file
11 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
12 | *
13 | * This import should be commented out in production mode because it will have a negative impact
14 | * on performance if an error is thrown.
15 | */
16 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI.
17 |
--------------------------------------------------------------------------------
/ui/.gitignore:
--------------------------------------------------------------------------------
1 | # See http://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # compiled output
4 | /dist
5 | /tmp
6 | /out-tsc
7 | # Only exists if Bazel was run
8 | /bazel-out
9 |
10 | # dependencies
11 | /node_modules
12 |
13 | # profiling files
14 | chrome-profiler-events*.json
15 | speed-measure-plugin*.json
16 |
17 | # IDEs and editors
18 | /.idea
19 | .project
20 | .classpath
21 | .c9/
22 | *.launch
23 | .settings/
24 | *.sublime-workspace
25 |
26 | # IDE - VSCode
27 | .vscode/*
28 | !.vscode/settings.json
29 | !.vscode/tasks.json
30 | !.vscode/launch.json
31 | !.vscode/extensions.json
32 | .history/*
33 |
34 | # misc
35 | /.sass-cache
36 | /connect.lock
37 | /coverage
38 | /libpeerconnection.log
39 | npm-debug.log
40 | yarn-error.log
41 | testem.log
42 | /typings
43 |
44 | # System Files
45 | .DS_Store
46 | Thumbs.db
47 |
--------------------------------------------------------------------------------
/ui/e2e/protractor.conf.js:
--------------------------------------------------------------------------------
1 | // @ts-check
2 | // Protractor configuration file, see link for more information
3 | // https://github.com/angular/protractor/blob/master/lib/config.ts
4 |
5 | const { SpecReporter } = require('jasmine-spec-reporter');
6 |
7 | /**
8 | * @type { import("protractor").Config }
9 | */
10 | exports.config = {
11 | allScriptsTimeout: 11000,
12 | specs: [
13 | './src/**/*.e2e-spec.ts'
14 | ],
15 | capabilities: {
16 | 'browserName': 'chrome'
17 | },
18 | directConnect: true,
19 | baseUrl: 'http://localhost:4200/',
20 | framework: 'jasmine',
21 | jasmineNodeOpts: {
22 | showColors: true,
23 | defaultTimeoutInterval: 30000,
24 | print: function() {}
25 | },
26 | onPrepare() {
27 | require('ts-node').register({
28 | project: require('path').join(__dirname, './tsconfig.json')
29 | });
30 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
31 | }
32 | };
--------------------------------------------------------------------------------
/ui/README.md:
--------------------------------------------------------------------------------
1 | # Ui
2 |
3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 8.3.3.
4 |
5 | ## Development server
6 |
7 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
8 |
9 | ## Code scaffolding
10 |
11 | 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`.
12 |
13 | ## Build
14 |
15 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
16 |
17 | ## Running unit tests
18 |
19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
20 |
21 | ## Running end-to-end tests
22 |
23 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
24 |
25 | ## Further help
26 |
27 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
28 |
--------------------------------------------------------------------------------
/ui/karma.conf.js:
--------------------------------------------------------------------------------
1 | // Karma configuration file, see link for more information
2 | // https://karma-runner.github.io/1.0/config/configuration-file.html
3 |
4 | module.exports = function (config) {
5 | config.set({
6 | basePath: '',
7 | frameworks: ['jasmine', '@angular-devkit/build-angular'],
8 | plugins: [
9 | require('karma-jasmine'),
10 | require('karma-chrome-launcher'),
11 | require('karma-jasmine-html-reporter'),
12 | require('karma-coverage-istanbul-reporter'),
13 | require('@angular-devkit/build-angular/plugins/karma')
14 | ],
15 | client: {
16 | clearContext: false // leave Jasmine Spec Runner output visible in browser
17 | },
18 | coverageIstanbulReporter: {
19 | dir: require('path').join(__dirname, './coverage/ui'),
20 | reports: ['html', 'lcovonly', 'text-summary'],
21 | fixWebpackSourcePaths: true
22 | },
23 | reporters: ['progress', 'kjhtml'],
24 | port: 9876,
25 | colors: true,
26 | logLevel: config.LOG_INFO,
27 | autoWatch: true,
28 | browsers: ['Chrome'],
29 | singleRun: false,
30 | restartOnFileChange: true
31 | });
32 | };
33 |
--------------------------------------------------------------------------------
/ui/src/app/app.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed, async } from '@angular/core/testing';
2 | import { RouterTestingModule } from '@angular/router/testing';
3 | import { AppComponent } from './app.component';
4 |
5 | describe('AppComponent', () => {
6 | beforeEach(async(() => {
7 | TestBed.configureTestingModule({
8 | imports: [
9 | RouterTestingModule
10 | ],
11 | declarations: [
12 | AppComponent
13 | ],
14 | }).compileComponents();
15 | }));
16 |
17 | it('should create the app', () => {
18 | const fixture = TestBed.createComponent(AppComponent);
19 | const app = fixture.debugElement.componentInstance;
20 | expect(app).toBeTruthy();
21 | });
22 |
23 | it(`should have as title 'ui'`, () => {
24 | const fixture = TestBed.createComponent(AppComponent);
25 | const app = fixture.debugElement.componentInstance;
26 | expect(app.title).toEqual('ui');
27 | });
28 |
29 | it('should render title', () => {
30 | const fixture = TestBed.createComponent(AppComponent);
31 | fixture.detectChanges();
32 | const compiled = fixture.debugElement.nativeElement;
33 | expect(compiled.querySelector('.content span').textContent).toContain('ui app is running!');
34 | });
35 | });
36 |
--------------------------------------------------------------------------------
/ui/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ui",
3 | "version": "0.0.0",
4 | "scripts": {
5 | "ng": "ng",
6 | "start": "ng serve",
7 | "build": "ng build",
8 | "test": "ng test",
9 | "lint": "ng lint",
10 | "e2e": "ng e2e"
11 | },
12 | "private": true,
13 | "dependencies": {
14 | "@angular/animations": "~8.2.4",
15 | "@angular/common": "~8.2.4",
16 | "@angular/compiler": "~8.2.4",
17 | "@angular/core": "~8.2.4",
18 | "@angular/forms": "~8.2.4",
19 | "@angular/platform-browser": "~8.2.4",
20 | "@angular/platform-browser-dynamic": "~8.2.4",
21 | "@angular/router": "~8.2.4",
22 | "rxjs": "~6.4.0",
23 | "tslib": "^1.10.0",
24 | "zone.js": "~0.9.1"
25 | },
26 | "devDependencies": {
27 | "@angular-devkit/build-angular": "~0.803.3",
28 | "@angular/cli": "~8.3.3",
29 | "@angular/compiler-cli": "~8.2.4",
30 | "@angular/language-service": "~8.2.4",
31 | "@types/node": "~8.9.4",
32 | "@types/jasmine": "~3.3.8",
33 | "@types/jasminewd2": "~2.0.3",
34 | "codelyzer": "^5.0.0",
35 | "jasmine-core": "~3.4.0",
36 | "jasmine-spec-reporter": "~4.2.1",
37 | "karma": "~4.1.0",
38 | "karma-chrome-launcher": "~2.2.0",
39 | "karma-coverage-istanbul-reporter": "~2.0.1",
40 | "karma-jasmine": "~2.0.1",
41 | "karma-jasmine-html-reporter": "^1.4.0",
42 | "protractor": "~5.4.0",
43 | "ts-node": "~7.0.0",
44 | "tslint": "~5.15.0",
45 | "typescript": "~3.5.3"
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/server/signal.go:
--------------------------------------------------------------------------------
1 | // Package signal contains helpers to exchange the SDP session
2 | // description between examples.
3 | package main
4 |
5 | import (
6 | "bufio"
7 | "bytes"
8 | "compress/gzip"
9 | "encoding/base64"
10 | "encoding/json"
11 | "fmt"
12 | "io"
13 | "io/ioutil"
14 | "os"
15 | "strings"
16 | )
17 |
18 | // Allows compressing offer/answer to bypass terminal input limits.
19 | const compress = false
20 |
21 | // MustReadStdin blocks until input is received from stdin
22 | func MustReadStdin() string {
23 | r := bufio.NewReader(os.Stdin)
24 |
25 | var in string
26 | for {
27 | var err error
28 | in, err = r.ReadString('\n')
29 | if err != io.EOF {
30 | if err != nil {
31 | panic(err)
32 | }
33 | }
34 | in = strings.TrimSpace(in)
35 | if len(in) > 0 {
36 | break
37 | }
38 | }
39 |
40 | fmt.Println("")
41 |
42 | return in
43 | }
44 |
45 | // Encode encodes the input in base64
46 | // It can optionally zip the input before encoding
47 | func Encode(obj interface{}) string {
48 | b, err := json.Marshal(obj)
49 | if err != nil {
50 | panic(err)
51 | }
52 |
53 | if compress {
54 | b = zip(b)
55 | }
56 |
57 | return base64.StdEncoding.EncodeToString(b)
58 | }
59 |
60 | // Decode decodes the input from base64
61 | // It can optionally unzip the input after decoding
62 | func Decode(in string, obj interface{}) {
63 | b, err := base64.StdEncoding.DecodeString(in)
64 | if err != nil {
65 | panic(err)
66 | }
67 |
68 | if compress {
69 | b = unzip(b)
70 | }
71 |
72 | err = json.Unmarshal(b, obj)
73 | if err != nil {
74 | panic(err)
75 | }
76 | }
77 |
78 | func zip(in []byte) []byte {
79 | var b bytes.Buffer
80 | gz := gzip.NewWriter(&b)
81 | _, err := gz.Write(in)
82 | if err != nil {
83 | panic(err)
84 | }
85 | err = gz.Flush()
86 | if err != nil {
87 | panic(err)
88 | }
89 | err = gz.Close()
90 | if err != nil {
91 | panic(err)
92 | }
93 | return b.Bytes()
94 | }
95 |
96 | func unzip(in []byte) []byte {
97 | var b bytes.Buffer
98 | _, err := b.Write(in)
99 | if err != nil {
100 | panic(err)
101 | }
102 | r, err := gzip.NewReader(&b)
103 | if err != nil {
104 | panic(err)
105 | }
106 | res, err := ioutil.ReadAll(r)
107 | if err != nil {
108 | panic(err)
109 | }
110 | return res
111 | }
112 |
--------------------------------------------------------------------------------
/ui/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "tslint:recommended",
3 | "rules": {
4 | "array-type": false,
5 | "arrow-parens": false,
6 | "deprecation": {
7 | "severity": "warning"
8 | },
9 | "component-class-suffix": true,
10 | "contextual-lifecycle": true,
11 | "directive-class-suffix": true,
12 | "directive-selector": [
13 | true,
14 | "attribute",
15 | "app",
16 | "camelCase"
17 | ],
18 | "component-selector": [
19 | true,
20 | "element",
21 | "app",
22 | "kebab-case"
23 | ],
24 | "import-blacklist": [
25 | true,
26 | "rxjs/Rx"
27 | ],
28 | "interface-name": false,
29 | "max-classes-per-file": false,
30 | "max-line-length": [
31 | true,
32 | 140
33 | ],
34 | "member-access": false,
35 | "member-ordering": [
36 | true,
37 | {
38 | "order": [
39 | "static-field",
40 | "instance-field",
41 | "static-method",
42 | "instance-method"
43 | ]
44 | }
45 | ],
46 | "no-consecutive-blank-lines": false,
47 | "no-console": [
48 | true,
49 | "debug",
50 | "info",
51 | "time",
52 | "timeEnd",
53 | "trace"
54 | ],
55 | "no-empty": false,
56 | "no-inferrable-types": [
57 | true,
58 | "ignore-params"
59 | ],
60 | "no-non-null-assertion": true,
61 | "no-redundant-jsdoc": true,
62 | "no-switch-case-fall-through": true,
63 | "no-use-before-declare": true,
64 | "no-var-requires": false,
65 | "object-literal-key-quotes": [
66 | true,
67 | "as-needed"
68 | ],
69 | "object-literal-sort-keys": false,
70 | "ordered-imports": false,
71 | "quotemark": [
72 | true,
73 | "single"
74 | ],
75 | "trailing-comma": false,
76 | "no-conflicting-lifecycle": true,
77 | "no-host-metadata-property": true,
78 | "no-input-rename": true,
79 | "no-inputs-metadata-property": true,
80 | "no-output-native": true,
81 | "no-output-on-prefix": true,
82 | "no-output-rename": true,
83 | "no-outputs-metadata-property": true,
84 | "template-banana-in-box": true,
85 | "template-no-negated-async": true,
86 | "use-lifecycle-interface": true,
87 | "use-pipe-transform-interface": true
88 | },
89 | "rulesDirectory": [
90 | "codelyzer"
91 | ]
92 | }
--------------------------------------------------------------------------------
/ui/src/polyfills.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * This file includes polyfills needed by Angular and is loaded before the app.
3 | * You can add your own extra polyfills to this file.
4 | *
5 | * This file is divided into 2 sections:
6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main
8 | * file.
9 | *
10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
13 | *
14 | * Learn more in https://angular.io/guide/browser-support
15 | */
16 |
17 | /***************************************************************************************************
18 | * BROWSER POLYFILLS
19 | */
20 |
21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */
22 | // import 'classlist.js'; // Run `npm install --save classlist.js`.
23 |
24 | /**
25 | * Web Animations `@angular/platform-browser/animations`
26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
28 | */
29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`.
30 |
31 | /**
32 | * By default, zone.js will patch all possible macroTask and DomEvents
33 | * user can disable parts of macroTask/DomEvents patch by setting following flags
34 | * because those flags need to be set before `zone.js` being loaded, and webpack
35 | * will put import in the top of bundle, so user need to create a separate file
36 | * in this directory (for example: zone-flags.ts), and put the following flags
37 | * into that file, and then add the following code before importing zone.js.
38 | * import './zone-flags.ts';
39 | *
40 | * The flags allowed in zone-flags.ts are listed here.
41 | *
42 | * The following flags will work for all browsers.
43 | *
44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
46 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
47 | *
48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge
50 | *
51 | * (window as any).__Zone_enable_cross_context_check = true;
52 | *
53 | */
54 |
55 | /***************************************************************************************************
56 | * Zone JS is required by default for Angular itself.
57 | */
58 | import 'zone.js/dist/zone'; // Included with Angular CLI.
59 |
60 |
61 | /***************************************************************************************************
62 | * APPLICATION IMPORTS
63 | */
64 |
--------------------------------------------------------------------------------
/ui/src/app/call/call.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 | import { HttpClient } from '@angular/common/http';
3 | import { Sdp } from './Sdp';
4 | import { ActivatedRoute } from "@angular/router";
5 |
6 | @Component({
7 | selector: 'app-call',
8 | templateUrl: './call.component.html',
9 | styleUrls: ['./call.component.css']
10 | })
11 | export class CallComponent implements OnInit {
12 |
13 | constructor(private http: HttpClient, private route: ActivatedRoute) { }
14 |
15 | pcSender : any
16 | pcReciever :any
17 | meetingId: string
18 | peerId: string
19 | userId: string
20 |
21 | ngOnInit() {
22 | // use http://localhost:4200/call;meetingId=07927fc8-af0a-11ea-b338-064f26a5f90a;userId=alice;peerId=bob
23 | // and http://localhost:4200/call;meetingId=07927fc8-af0a-11ea-b338-064f26a5f90a;userId=bob;peerId=alice
24 | // start the call
25 | this.meetingId = this.route.snapshot.paramMap.get("meetingId");
26 | this.peerId = this.route.snapshot.paramMap.get("peerId");
27 | this.userId = this.route.snapshot.paramMap.get("userId")
28 |
29 | this.pcSender = new RTCPeerConnection({
30 | iceServers: [
31 | {
32 | urls: 'stun:stun.l.google.com:19302'
33 | }
34 | ]
35 | })
36 | this.pcReciever = new RTCPeerConnection({
37 | iceServers: [
38 | {
39 | urls: 'stun:stun.l.google.com:19302'
40 | }
41 | ]
42 | })
43 |
44 | this.pcSender.onicecandidate = event => {
45 | if (event.candidate === null) {
46 | this.http.post('/webrtc/sdp/m/' + this.meetingId + "/c/"+ this.userId + "/p/" + this.peerId + "/s/" + true,
47 | {"sdp" : btoa(JSON.stringify(this.pcSender.localDescription))}).subscribe(response => {
48 | this.pcSender.setRemoteDescription(new RTCSessionDescription(JSON.parse(atob(response.Sdp))))
49 | });
50 | }
51 | }
52 | this.pcReciever.onicecandidate = event => {
53 | if (event.candidate === null) {
54 | this.http.post('/webrtc/sdp/m/' + this.meetingId + "/c/"+ this.userId + "/p/" + this.peerId + "/s/" + false,
55 | {"sdp" : btoa(JSON.stringify(this.pcReciever.localDescription))}).subscribe(response => {
56 | this.pcReciever.setRemoteDescription(new RTCSessionDescription(JSON.parse(atob(response.Sdp))))
57 | })
58 | }
59 | }
60 | }
61 |
62 | startCall() {
63 | // sender part of the call
64 | navigator.mediaDevices.getUserMedia({video: true, audio: true}).then((stream) =>{
65 | var senderVideo :any = document.getElementById('senderVideo');
66 | senderVideo.srcObject = stream;
67 | var tracks = stream.getTracks();
68 | for (var i = 0; i < tracks.length; i++) {
69 | this.pcSender.addTrack(stream.getTracks()[i]);
70 | }
71 | this.pcSender.createOffer().then(d => this.pcSender.setLocalDescription(d))
72 | })
73 | // you can use event listner so that you inform he is connected!
74 | this.pcSender.addEventListener('connectionstatechange', event => {
75 | if (this.pcSender.connectionState === 'connected') {
76 | console.log("horray!")
77 | }
78 | });
79 |
80 | // receiver part of the call
81 | this.pcReciever.addTransceiver('video', {'direction': 'recvonly'})
82 |
83 | this.pcReciever.createOffer()
84 | .then(d => this.pcReciever.setLocalDescription(d))
85 |
86 | this.pcReciever.ontrack = function (event) {
87 | var receiverVideo :any = document.getElementById('receiverVideo')
88 | receiverVideo.srcObject = event.streams[0]
89 | receiverVideo.autoplay = true
90 | receiverVideo.controls = true
91 | }
92 |
93 | }
94 |
95 | }
96 |
--------------------------------------------------------------------------------
/ui/angular.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
3 | "version": 1,
4 | "newProjectRoot": "projects",
5 | "projects": {
6 | "ui": {
7 | "projectType": "application",
8 | "schematics": {},
9 | "root": "",
10 | "sourceRoot": "src",
11 | "prefix": "app",
12 | "architect": {
13 | "build": {
14 | "builder": "@angular-devkit/build-angular:browser",
15 | "options": {
16 | "outputPath": "dist/ui",
17 | "index": "src/index.html",
18 | "main": "src/main.ts",
19 | "polyfills": "src/polyfills.ts",
20 | "tsConfig": "tsconfig.app.json",
21 | "aot": false,
22 | "assets": [
23 | "src/favicon.ico",
24 | "src/assets"
25 | ],
26 | "styles": [
27 | "src/styles.css"
28 | ],
29 | "scripts": []
30 | },
31 | "configurations": {
32 | "production": {
33 | "fileReplacements": [
34 | {
35 | "replace": "src/environments/environment.ts",
36 | "with": "src/environments/environment.prod.ts"
37 | }
38 | ],
39 | "optimization": true,
40 | "outputHashing": "all",
41 | "sourceMap": false,
42 | "extractCss": true,
43 | "namedChunks": false,
44 | "aot": true,
45 | "extractLicenses": true,
46 | "vendorChunk": false,
47 | "buildOptimizer": true,
48 | "budgets": [
49 | {
50 | "type": "initial",
51 | "maximumWarning": "2mb",
52 | "maximumError": "5mb"
53 | },
54 | {
55 | "type": "anyComponentStyle",
56 | "maximumWarning": "6kb",
57 | "maximumError": "10kb"
58 | }
59 | ]
60 | }
61 | }
62 | },
63 | "serve": {
64 | "builder": "@angular-devkit/build-angular:dev-server",
65 | "options": {
66 | "browserTarget": "ui:build",
67 | "proxyConfig": "proxyconfig.json"
68 | },
69 | "configurations": {
70 | "production": {
71 | "browserTarget": "ui:build:production"
72 | }
73 | }
74 | },
75 | "extract-i18n": {
76 | "builder": "@angular-devkit/build-angular:extract-i18n",
77 | "options": {
78 | "browserTarget": "ui:build"
79 | }
80 | },
81 | "test": {
82 | "builder": "@angular-devkit/build-angular:karma",
83 | "options": {
84 | "main": "src/test.ts",
85 | "polyfills": "src/polyfills.ts",
86 | "tsConfig": "tsconfig.spec.json",
87 | "karmaConfig": "karma.conf.js",
88 | "assets": [
89 | "src/favicon.ico",
90 | "src/assets"
91 | ],
92 | "styles": [
93 | "src/styles.css"
94 | ],
95 | "scripts": []
96 | }
97 | },
98 | "lint": {
99 | "builder": "@angular-devkit/build-angular:tslint",
100 | "options": {
101 | "tsConfig": [
102 | "tsconfig.app.json",
103 | "tsconfig.spec.json",
104 | "e2e/tsconfig.json"
105 | ],
106 | "exclude": [
107 | "**/node_modules/**"
108 | ]
109 | }
110 | },
111 | "e2e": {
112 | "builder": "@angular-devkit/build-angular:protractor",
113 | "options": {
114 | "protractorConfig": "e2e/protractor.conf.js",
115 | "devServerTarget": "ui:serve"
116 | },
117 | "configurations": {
118 | "production": {
119 | "devServerTarget": "ui:serve:production"
120 | }
121 | }
122 | }
123 | }
124 | }},
125 | "defaultProject": "ui"
126 | }
--------------------------------------------------------------------------------
/server/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "io"
6 | "log"
7 | "net/http"
8 | "os"
9 | "strconv"
10 | "time"
11 |
12 | "github.com/gin-gonic/gin"
13 | "github.com/pion/rtcp"
14 | "github.com/pion/webrtc/v2"
15 | )
16 |
17 | const (
18 | rtcpPLIInterval = time.Second * 3
19 | )
20 |
21 | // Sdp represent session description protocol describe media communication sessions
22 | type Sdp struct {
23 | Sdp string
24 | }
25 |
26 | func main() {
27 | file, err := os.OpenFile("info.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
28 | if err != nil {
29 | log.Fatal(err)
30 | }
31 | defer file.Close()
32 | log.SetOutput(file)
33 | router := gin.Default()
34 |
35 | // sender to channel of track
36 | peerConnectionMap := make(map[string]chan *webrtc.Track)
37 |
38 | m := webrtc.MediaEngine{}
39 |
40 | // Setup the codecs you want to use.
41 | // Only support VP8(video compression), this makes our proxying code simpler
42 | m.RegisterCodec(webrtc.NewRTPVP8Codec(webrtc.DefaultPayloadTypeVP8, 90000))
43 |
44 | api := webrtc.NewAPI(webrtc.WithMediaEngine(m))
45 |
46 | peerConnectionConfig := webrtc.Configuration{
47 | ICEServers: []webrtc.ICEServer{
48 | {
49 | URLs: []string{"stun:stun.l.google.com:19302"},
50 | },
51 | },
52 | }
53 |
54 | router.POST("/webrtc/sdp/m/:meetingId/c/:userID/p/:peerId/s/:isSender", func(c *gin.Context) {
55 | isSender, _ := strconv.ParseBool(c.Param("isSender"))
56 | userID := c.Param("userID")
57 | peerID := c.Param("peerId")
58 |
59 | var session Sdp
60 | if err := c.ShouldBindJSON(&session); err != nil {
61 | c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
62 | return
63 | }
64 |
65 | offer := webrtc.SessionDescription{}
66 | Decode(session.Sdp, &offer)
67 |
68 | // Create a new RTCPeerConnection
69 | // this is the gist of webrtc, generates and process SDP
70 | peerConnection, err := api.NewPeerConnection(peerConnectionConfig)
71 | if err != nil {
72 | log.Fatal(err)
73 | }
74 | if !isSender {
75 | recieveTrack(peerConnection, peerConnectionMap, peerID)
76 | } else {
77 | createTrack(peerConnection, peerConnectionMap, userID)
78 | }
79 | // Set the SessionDescription of remote peer
80 | peerConnection.SetRemoteDescription(offer)
81 |
82 | // Create answer
83 | answer, err := peerConnection.CreateAnswer(nil)
84 | if err != nil {
85 | log.Fatal(err)
86 | }
87 |
88 | // Sets the LocalDescription, and starts our UDP listeners
89 | err = peerConnection.SetLocalDescription(answer)
90 | if err != nil {
91 | log.Fatal(err)
92 | }
93 | c.JSON(http.StatusOK, Sdp{Sdp: Encode(answer)})
94 | })
95 |
96 | router.Run(":8080")
97 | }
98 |
99 | // user is the caller of the method
100 | // if user connects before peer: create channel and keep listening till track is added
101 | // if peer connects before user: channel would have been created by peer and track can be added by getting the channel from cache
102 | func recieveTrack(peerConnection *webrtc.PeerConnection,
103 | peerConnectionMap map[string]chan *webrtc.Track,
104 | peerID string) {
105 | if _, ok := peerConnectionMap[peerID]; !ok {
106 | peerConnectionMap[peerID] = make(chan *webrtc.Track, 1)
107 | }
108 | localTrack := <-peerConnectionMap[peerID]
109 | peerConnection.AddTrack(localTrack)
110 | }
111 |
112 | // user is the caller of the method
113 | // if user connects before peer: since user is first, user will create the channel and track and will pass the track to the channel
114 | // if peer connects before user: since peer came already, he created the channel and is listning and waiting for me to create and pass track
115 | func createTrack(peerConnection *webrtc.PeerConnection,
116 | peerConnectionMap map[string]chan *webrtc.Track,
117 | currentUserID string) {
118 |
119 | if _, err := peerConnection.AddTransceiver(webrtc.RTPCodecTypeVideo); err != nil {
120 | log.Fatal(err)
121 | }
122 |
123 | // Set a handler for when a new remote track starts, this just distributes all our packets
124 | // to connected peers
125 | peerConnection.OnTrack(func(remoteTrack *webrtc.Track, receiver *webrtc.RTPReceiver) {
126 | // Send a PLI on an interval so that the publisher is pushing a keyframe every rtcpPLIInterval
127 | // This can be less wasteful by processing incoming RTCP events, then we would emit a NACK/PLI when a viewer requests it
128 | go func() {
129 | ticker := time.NewTicker(rtcpPLIInterval)
130 | for range ticker.C {
131 | if rtcpSendErr := peerConnection.WriteRTCP([]rtcp.Packet{&rtcp.PictureLossIndication{MediaSSRC: remoteTrack.SSRC()}}); rtcpSendErr != nil {
132 | fmt.Println(rtcpSendErr)
133 | }
134 | }
135 | }()
136 |
137 | // Create a local track, all our SFU clients will be fed via this track
138 | // main track of the broadcaster
139 | localTrack, newTrackErr := peerConnection.NewTrack(remoteTrack.PayloadType(), remoteTrack.SSRC(), "video", "pion")
140 | if newTrackErr != nil {
141 | log.Fatal(newTrackErr)
142 | }
143 |
144 | // the channel that will have the local track that is used by the sender
145 | // the localTrack needs to be fed to the reciever
146 | localTrackChan := make(chan *webrtc.Track, 1)
147 | localTrackChan <- localTrack
148 | if existingChan, ok := peerConnectionMap[currentUserID]; ok {
149 | // feed the exsiting track from user with this track
150 | existingChan <- localTrack
151 | } else {
152 | peerConnectionMap[currentUserID] = localTrackChan
153 | }
154 |
155 | rtpBuf := make([]byte, 1400)
156 | for { // for publisher only
157 | i, readErr := remoteTrack.Read(rtpBuf)
158 | if readErr != nil {
159 | log.Fatal(readErr)
160 | }
161 |
162 | // ErrClosedPipe means we don't have any subscribers, this is ok if no peers have connected yet
163 | if _, err := localTrack.Write(rtpBuf[:i]); err != nil && err != io.ErrClosedPipe {
164 | log.Fatal(err)
165 | }
166 | }
167 | })
168 |
169 | }
170 |
--------------------------------------------------------------------------------