Migrate to redux
Detailed list of changes 1. Migrate off flux to redux stores, closes #35 2. Reorganize stores 3. Use PureComponents, closes #36 4. Rewrite most tests, increase coverage to 100%, closes #17 5. Allow preview to people without camera & mic, closes #26 6. Add package-lock.json for npm 5 7. Add mock of window object, closes #13
This commit is contained in:
commit
57b3d3ca6a
2
.eslintignore
Normal file
2
.eslintignore
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
build/
|
||||||
|
coverage/
|
||||||
221
.eslintrc
221
.eslintrc
@ -1,213 +1,20 @@
|
|||||||
{
|
{
|
||||||
"parserOptions": {
|
"parser": "babel-eslint",
|
||||||
"ecmaFeatures": {
|
"extends": ["standard", "standard-react"],
|
||||||
"globalReturn": true,
|
|
||||||
"modules": true,
|
|
||||||
"jsx": true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
"plugins": [
|
|
||||||
"react"
|
|
||||||
],
|
|
||||||
|
|
||||||
"esnext": true,
|
|
||||||
|
|
||||||
"env": {
|
|
||||||
"browser": false,
|
|
||||||
"es6": true,
|
|
||||||
"amd": true,
|
|
||||||
"mocha": true,
|
|
||||||
"node": true
|
|
||||||
},
|
|
||||||
|
|
||||||
"globals": {
|
|
||||||
"document": false,
|
|
||||||
"escape": false,
|
|
||||||
"navigator": false,
|
|
||||||
"unescape": false,
|
|
||||||
"expect": true,
|
|
||||||
"localStorage": false,
|
|
||||||
"window": false,
|
|
||||||
"jest": true,
|
|
||||||
"jasmine": true
|
|
||||||
},
|
|
||||||
|
|
||||||
"rules": {
|
"rules": {
|
||||||
"block-scoped-var": 0,
|
|
||||||
"brace-style": [2, "1tbs", { "allowSingleLine": true }],
|
|
||||||
"max-len": [2, 80, 4],
|
"max-len": [2, 80, 4],
|
||||||
"camelcase": 0,
|
"jsx-quotes": ["error", "prefer-double"],
|
||||||
"comma-dangle": 0,
|
|
||||||
"comma-spacing": [2, { "before": false, "after": true }],
|
|
||||||
"comma-style": [2, "last"],
|
|
||||||
"complexity": 0,
|
|
||||||
"consistent-return": 0,
|
|
||||||
"consistent-this": 0,
|
|
||||||
"curly": 0,
|
|
||||||
"default-case": 0,
|
|
||||||
"dot-notation": 0,
|
|
||||||
"eol-last": 2,
|
|
||||||
"eqeqeq": [2, "allow-null"],
|
|
||||||
"func-names": 0,
|
|
||||||
"func-style": [0, "declaration"],
|
|
||||||
"generator-star-spacing": [2],
|
|
||||||
"guard-for-in": 0,
|
|
||||||
"handle-callback-err": [2, "^(err|error|anySpecificError)$" ],
|
|
||||||
"key-spacing": [2, { "beforeColon": false, "afterColon": true }],
|
|
||||||
"max-depth": 0,
|
|
||||||
"max-nested-callbacks": 0,
|
|
||||||
"max-params": 0,
|
|
||||||
"max-statements": 0,
|
|
||||||
"new-cap": [2, { "newIsCap": true, "capIsNew": false }],
|
|
||||||
"new-parens": 2,
|
|
||||||
"no-alert": 2,
|
|
||||||
"no-array-constructor": 2,
|
|
||||||
"no-bitwise": 0,
|
|
||||||
"no-caller": 2,
|
|
||||||
"no-catch-shadow": 0,
|
|
||||||
"no-cond-assign": 2,
|
|
||||||
"no-console": 0,
|
|
||||||
"no-constant-condition": 0,
|
|
||||||
"no-control-regex": 2,
|
|
||||||
"no-debugger": 2,
|
|
||||||
"no-delete-var": 2,
|
|
||||||
"no-div-regex": 0,
|
|
||||||
"no-dupe-args": 2,
|
|
||||||
"no-dupe-keys": 2,
|
|
||||||
"no-duplicate-case": 2,
|
|
||||||
"no-else-return": 0,
|
|
||||||
"no-empty": 0,
|
|
||||||
"no-empty-character-class": 2,
|
|
||||||
"no-labels": 2,
|
|
||||||
"no-eq-null": 0,
|
|
||||||
"no-eval": 2,
|
|
||||||
"no-ex-assign": 2,
|
|
||||||
"no-extend-native": 2,
|
|
||||||
"no-extra-bind": 2,
|
|
||||||
"no-extra-boolean-cast": 2,
|
|
||||||
"no-extra-parens": 0,
|
|
||||||
"no-extra-semi": 0,
|
|
||||||
"no-extra-strict": 0,
|
|
||||||
"no-fallthrough": 2,
|
|
||||||
"no-floating-decimal": 2,
|
|
||||||
"no-func-assign": 2,
|
|
||||||
"no-implied-eval": 2,
|
|
||||||
"no-inline-comments": 0,
|
|
||||||
"no-inner-declarations": [2, "functions"],
|
|
||||||
"no-invalid-regexp": 2,
|
|
||||||
"no-irregular-whitespace": 2,
|
|
||||||
"no-iterator": 2,
|
|
||||||
"no-label-var": 2,
|
|
||||||
"no-lone-blocks": 2,
|
|
||||||
"no-lonely-if": 0,
|
|
||||||
"no-loop-func": 0,
|
|
||||||
"no-mixed-requires": [0, false],
|
|
||||||
"no-mixed-spaces-and-tabs": [2, false],
|
|
||||||
"no-multi-spaces": 2,
|
|
||||||
"no-multi-str": 2,
|
|
||||||
"no-multiple-empty-lines": 0,
|
|
||||||
"no-native-reassign": 2,
|
|
||||||
"no-negated-in-lhs": 2,
|
|
||||||
"no-nested-ternary": 0,
|
|
||||||
"no-new": 0,
|
|
||||||
"no-new-func": 2,
|
|
||||||
"no-new-object": 2,
|
|
||||||
"no-new-require": 2,
|
|
||||||
"no-new-wrappers": 2,
|
|
||||||
"no-obj-calls": 2,
|
|
||||||
"no-octal": 2,
|
|
||||||
"no-octal-escape": 2,
|
|
||||||
"no-path-concat": 0,
|
|
||||||
"no-plusplus": 0,
|
|
||||||
"no-process-env": 0,
|
|
||||||
"no-process-exit": 0,
|
|
||||||
"no-proto": 2,
|
|
||||||
"no-redeclare": 2,
|
|
||||||
"no-regex-spaces": 2,
|
|
||||||
"no-reserved-keys": 0,
|
|
||||||
"no-restricted-modules": 0,
|
|
||||||
"no-return-assign": 2,
|
|
||||||
"no-script-url": 2,
|
|
||||||
"no-self-compare": 2,
|
|
||||||
"no-sequences": 2,
|
|
||||||
"no-shadow": 0,
|
|
||||||
"no-shadow-restricted-names": 2,
|
|
||||||
"no-spaced-func": 2,
|
|
||||||
"no-sparse-arrays": 2,
|
|
||||||
"no-sync": 0,
|
|
||||||
"no-ternary": 0,
|
|
||||||
"no-throw-literal": 2,
|
|
||||||
"no-trailing-spaces": 2,
|
|
||||||
"no-undef": 2,
|
|
||||||
"no-undef-init": 2,
|
|
||||||
"no-undefined": 0,
|
|
||||||
"no-underscore-dangle": 0,
|
|
||||||
"no-unreachable": 2,
|
|
||||||
"no-unused-expressions": 0,
|
|
||||||
"no-unused-vars": [2, { "vars": "all", "args": "none" }],
|
|
||||||
"no-use-before-define": 0,
|
|
||||||
"no-var": 0,
|
|
||||||
"no-void": 0,
|
|
||||||
"no-warning-comments": [0, { "terms": ["todo", "fixme", "xxx"], "location": "start" }],
|
|
||||||
"no-with": 2,
|
|
||||||
"one-var": 0,
|
|
||||||
"operator-assignment": [0, "always"],
|
|
||||||
"padded-blocks": 0,
|
"padded-blocks": 0,
|
||||||
"quote-props": 0,
|
"import/first": 0,
|
||||||
"quotes": [2, "single", "avoid-escape"],
|
"no-return-assign": 0
|
||||||
"radix": 2,
|
},
|
||||||
"semi": [2, "always"],
|
"globals": {
|
||||||
"semi-spacing": 0,
|
"expect": true,
|
||||||
"sort-vars": 0,
|
"jest": true,
|
||||||
"keyword-spacing": ["error", {"before": true, "after": true, "overrides": {}}],
|
"jasmine": true,
|
||||||
"space-before-blocks": [2, "always"],
|
"it": true,
|
||||||
"space-before-function-paren": [2, "never"],
|
"beforeEach": true,
|
||||||
"space-in-brackets": 0,
|
"afterEach": true,
|
||||||
"space-in-parens": [2, "never"],
|
"describe": true
|
||||||
"space-infix-ops": 2,
|
|
||||||
"space-unary-ops": [2, { "words": true, "nonwords": false }],
|
|
||||||
"spaced-comment": [2, "always"],
|
|
||||||
"strict": 0,
|
|
||||||
"use-isnan": 2,
|
|
||||||
"valid-jsdoc": 0,
|
|
||||||
"valid-typeof": 2,
|
|
||||||
"vars-on-top": 0,
|
|
||||||
"wrap-iife": [2, "any"],
|
|
||||||
"wrap-regex": 0,
|
|
||||||
"yoda": [2, "never"],
|
|
||||||
|
|
||||||
// "react/display-name": 1,
|
|
||||||
"react/forbid-prop-types": 1,
|
|
||||||
"react/jsx-boolean-value": 1,
|
|
||||||
"react/jsx-closing-bracket-location": 1,
|
|
||||||
"react/jsx-curly-spacing": 1,
|
|
||||||
"react/jsx-handler-names": 1,
|
|
||||||
"react/jsx-indent-props": [1, 2],
|
|
||||||
"react/jsx-key": 1,
|
|
||||||
"react/jsx-max-props-per-line": 0,
|
|
||||||
"react/jsx-no-bind": 1,
|
|
||||||
"react/jsx-no-duplicate-props": 1,
|
|
||||||
"react/jsx-no-literals": 1,
|
|
||||||
"react/jsx-no-undef": 1,
|
|
||||||
"react/jsx-pascal-case": 0,
|
|
||||||
"jsx-quotes": 1,
|
|
||||||
"react/sort-prop-types": 1,
|
|
||||||
"react/jsx-sort-props": 1,
|
|
||||||
"react/jsx-uses-react": 1,
|
|
||||||
"react/jsx-uses-vars": 1,
|
|
||||||
"react/no-danger": 1,
|
|
||||||
"react/no-did-mount-set-state": 1,
|
|
||||||
"react/no-did-update-set-state": 1,
|
|
||||||
"react/no-direct-mutation-state": 1,
|
|
||||||
"react/no-set-state": 0,
|
|
||||||
"react/no-unknown-property": 1,
|
|
||||||
"react/prefer-es6-class": 0,
|
|
||||||
// "react/prop-types": 1,
|
|
||||||
"react/react-in-jsx-scope": 1,
|
|
||||||
"react/require-extension": 1,
|
|
||||||
"react/self-closing-comp": 1,
|
|
||||||
"react/sort-comp": 1,
|
|
||||||
"react/wrap-multilines": 1
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,6 +1,8 @@
|
|||||||
*.swp
|
*.swp
|
||||||
*.swo
|
*.swo
|
||||||
dist/
|
dist/
|
||||||
|
build/
|
||||||
|
!build/.gitkeep
|
||||||
node_modules/
|
node_modules/
|
||||||
config.js
|
config.js
|
||||||
coverage/
|
coverage/
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
language: node_js
|
language: node_js
|
||||||
node_js:
|
node_js:
|
||||||
- "5.2.0"
|
- "8.1.2"
|
||||||
script: make lint coverage build
|
script: npm run ci
|
||||||
notifications:
|
notifications:
|
||||||
email: false
|
email: false
|
||||||
|
|||||||
47
Makefile
47
Makefile
@ -1,47 +0,0 @@
|
|||||||
export PATH := node_modules/.bin:$(PATH)
|
|
||||||
SHELL=/bin/bash
|
|
||||||
|
|
||||||
.PHONY: build
|
|
||||||
build:
|
|
||||||
|
|
||||||
mkdir -p dist/client dist/css
|
|
||||||
|
|
||||||
browserify -t babelify ./src/client/index.js | uglifyjs --comments -o ./dist/client/index.js
|
|
||||||
|
|
||||||
lessc ./src/less/main.less ./dist/css/main.css
|
|
||||||
|
|
||||||
cp -v ./src/index.js ./dist/index.js
|
|
||||||
cp -rv ./src/server ./dist/
|
|
||||||
cp -rv ./src/less/fonts ./dist/css/
|
|
||||||
cp -rv ./src/views ./dist/
|
|
||||||
cp -rv ./src/res ./dist/
|
|
||||||
|
|
||||||
.PHONY: lint
|
|
||||||
lint:
|
|
||||||
|
|
||||||
eslint src/
|
|
||||||
|
|
||||||
.PHONY: test
|
|
||||||
test:
|
|
||||||
|
|
||||||
jest --verbose
|
|
||||||
|
|
||||||
.PHONY: testify
|
|
||||||
testify:
|
|
||||||
|
|
||||||
jest --watch
|
|
||||||
|
|
||||||
.PHONY: coverage
|
|
||||||
coverage:
|
|
||||||
|
|
||||||
jest --coverage
|
|
||||||
|
|
||||||
.PHONY: run
|
|
||||||
run:
|
|
||||||
|
|
||||||
node ./src/index.js
|
|
||||||
|
|
||||||
.PHONY: clean
|
|
||||||
clean:
|
|
||||||
|
|
||||||
rm -rf dist/
|
|
||||||
27
README.md
27
README.md
@ -8,7 +8,7 @@ WebRTC peer to peer calls for everyone. See it live in action at
|
|||||||
Work in progress.
|
Work in progress.
|
||||||
|
|
||||||
# Requirements
|
# Requirements
|
||||||
- Node.js 5 [https://nodejs.org/en/](https://nodejs.org/en/)
|
- Node.js 8 [https://nodejs.org/en/](https://nodejs.org/en/)
|
||||||
|
|
||||||
# Installation & Running
|
# Installation & Running
|
||||||
|
|
||||||
@ -18,9 +18,19 @@ From git source:
|
|||||||
git clone https://github.com/jeremija/peer-calls.git
|
git clone https://github.com/jeremija/peer-calls.git
|
||||||
cd peer-calls
|
cd peer-calls
|
||||||
npm install
|
npm install
|
||||||
|
|
||||||
|
# for production
|
||||||
npm start
|
npm start
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
# for development
|
||||||
|
npm run start:watch
|
||||||
```
|
```
|
||||||
|
|
||||||
|
To run a development version, type:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
If you successfully completed the above steps, your commandline/terminal should
|
If you successfully completed the above steps, your commandline/terminal should
|
||||||
show that your node server is listening.
|
show that your node server is listening.
|
||||||
|
|
||||||
@ -28,10 +38,6 @@ On your other machine or mobile device open the url:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
http://<your_ip_or_localhost>:3000
|
http://<your_ip_or_localhost>:3000
|
||||||
```
|
|
||||||
|
|
||||||
(Note: On Android you may have to select a notification on the pulldown menu to
|
|
||||||
connect if you are using Chrome)
|
|
||||||
|
|
||||||
# Testing
|
# Testing
|
||||||
|
|
||||||
@ -40,6 +46,17 @@ npm install
|
|||||||
npm test
|
npm test
|
||||||
```
|
```
|
||||||
|
|
||||||
|
# Browser Support
|
||||||
|
|
||||||
|
Tested on Firefox and Chrome, including mobile versions.
|
||||||
|
|
||||||
|
Does not work on iOS 10, but should work on iOS 11 (untested).
|
||||||
|
|
||||||
|
For more details, see here:
|
||||||
|
|
||||||
|
- http://caniuse.com/#feat=rtcpeerconnection
|
||||||
|
- http://caniuse.com/#search=getUserMedia
|
||||||
|
|
||||||
# Contributing
|
# Contributing
|
||||||
|
|
||||||
See [Contributing](CONTRIBUTING.md) section.
|
See [Contributing](CONTRIBUTING.md) section.
|
||||||
|
|||||||
11
__mocks__/simple-peer.js
Normal file
11
__mocks__/simple-peer.js
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
import EventEmitter from 'events'
|
||||||
|
const Peer = jest.genMockFunction().mockImplementation(() => {
|
||||||
|
let peer = new EventEmitter()
|
||||||
|
peer.destroy = jest.fn()
|
||||||
|
peer.signal = jest.fn()
|
||||||
|
peer.send = jest.fn()
|
||||||
|
Peer.instances.push(peer)
|
||||||
|
return peer
|
||||||
|
})
|
||||||
|
Peer.instances = []
|
||||||
|
export default Peer
|
||||||
1
config/test.json
Normal file
1
config/test.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
{}
|
||||||
5970
package-lock.json
generated
Normal file
5970
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
105
package.json
105
package.json
@ -6,50 +6,87 @@
|
|||||||
"main": "src/index.js",
|
"main": "src/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node src/index.js",
|
"start": "node src/index.js",
|
||||||
"test": "jest --coverage",
|
"start:server": "nodemon src/index.js --ignore build/ --ignore src/client",
|
||||||
"testify": "jest --watch",
|
"start:watch": "chastifol [ npm run js:watch ] [ npm run css:watch ] [ npm run start:server ]",
|
||||||
"lint": "eslint ./index.js ./src/js"
|
"watch": "",
|
||||||
|
"build": "npm run css && npm run js",
|
||||||
|
"test": "jest",
|
||||||
|
"test:coverage": "jest --coverage",
|
||||||
|
"test:watch": "jest --watch",
|
||||||
|
"js": "browserify -t babelify ./src/client/index.js -o ./build/index.js",
|
||||||
|
"js:watch": "watchify -d -v -t babelify ./src/client/index.js -o ./build/index.js",
|
||||||
|
"css": "node-sass ./src/scss/style.scss -o ./build/",
|
||||||
|
"css:watch": "node-sass --watch ./src/scss/style.scss -o ./build/",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"lint:fix": "eslint . --fix",
|
||||||
|
"ci": "npm run lint && npm run test:coverage && npm run build"
|
||||||
|
},
|
||||||
|
"babel": {
|
||||||
|
"presets": [
|
||||||
|
"es2015",
|
||||||
|
"es2016",
|
||||||
|
"react"
|
||||||
|
],
|
||||||
|
"plugins": [
|
||||||
|
"transform-object-rest-spread",
|
||||||
|
"transform-class-properties"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"author": "",
|
"author": "",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bluebird": "^3.3.4",
|
"bluebird": "3.3.4",
|
||||||
"config": "^1.26.1",
|
"classnames": "2.2.5",
|
||||||
"express": "^4.13.3",
|
"config": "1.26.1",
|
||||||
"flux": "^2.1.1",
|
"express": "4.13.3",
|
||||||
"jade": "^1.11.0",
|
"prop-types": "15.5.10",
|
||||||
"react": "^0.14.8",
|
"pug": "2.0.0-rc.2",
|
||||||
"react-addons-css-transition-group": "^0.14.8",
|
"react": "15.5.4",
|
||||||
"react-dom": "^0.14.8",
|
"react-dom": "15.5.4",
|
||||||
"simple-peer": "^6.0.3",
|
"react-redux": "5.0.5",
|
||||||
|
"react-transition-group": "1.1.3",
|
||||||
|
"redux": "3.6.0",
|
||||||
|
"redux-logger": "3.0.6",
|
||||||
|
"redux-promise-middleware": "4.2.0",
|
||||||
|
"redux-thunk": "2.2.0",
|
||||||
|
"seamless-immutable": "7.1.2",
|
||||||
|
"simple-peer": "8.1.0",
|
||||||
"socket.io": "1.6.0",
|
"socket.io": "1.6.0",
|
||||||
"socket.io-client": "1.6.0",
|
"socket.io-client": "1.6.0",
|
||||||
"underscore": "^1.8.3",
|
"underscore": "1.8.3",
|
||||||
"uuid": "^2.0.1"
|
"uuid": "2.0.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"babel-jest": "^10.0.1",
|
"babel-eslint": "7.2.3",
|
||||||
"babel-preset-es2015": "^6.6.0",
|
"babel-jest": "20.0.3",
|
||||||
"babel-preset-react": "^6.5.0",
|
"babel-plugin-transform-class-properties": "6.24.1",
|
||||||
"babelify": "^7.2.0",
|
"babel-plugin-transform-object-rest-spread": "6.23.0",
|
||||||
"browserify-middleware": "^7.0.0",
|
"babel-preset-es2015": "6.24.1",
|
||||||
"eslint": "^2.5.3",
|
"babel-preset-es2016": "6.24.1",
|
||||||
"eslint-plugin-react": "^4.2.3",
|
"babel-preset-react": "6.24.1",
|
||||||
"jest-cli": "^0.10.0",
|
"babelify": "7.3.0",
|
||||||
"less-middleware": "^2.0.1",
|
"chastifol": "4.1.0",
|
||||||
"react-addons-test-utils": "^0.14.8",
|
"eslint": "3.19.0",
|
||||||
"uglify-js": "^2.6.2"
|
"eslint-config-standard": "10.2.1",
|
||||||
|
"eslint-config-standard-react": "5.0.0",
|
||||||
|
"eslint-plugin-import": "2.3.0",
|
||||||
|
"eslint-plugin-node": "5.0.0",
|
||||||
|
"eslint-plugin-promise": "3.5.0",
|
||||||
|
"eslint-plugin-react": "7.0.1",
|
||||||
|
"eslint-plugin-standard": "3.0.1",
|
||||||
|
"jest-cli": "20.0.4",
|
||||||
|
"node-sass": "4.5.3",
|
||||||
|
"nodemon": "1.11.0",
|
||||||
|
"react-addons-test-utils": "15.5.1",
|
||||||
|
"redux-mock-store": "1.2.3",
|
||||||
|
"supertest": "^3.0.0",
|
||||||
|
"uglify-js": "2.6.2",
|
||||||
|
"watchify": "3.9.0"
|
||||||
},
|
},
|
||||||
"jest": {
|
"jest": {
|
||||||
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
|
"transform": {
|
||||||
"unmockedModulePathPatterns": [
|
".*": "<rootDir>/node_modules/babel-jest"
|
||||||
"<rootDir>/node_modules/debug",
|
},
|
||||||
"<rootDir>/node_modules/fbjs",
|
|
||||||
"<rootDir>/node_modules/react",
|
|
||||||
"<rootDir>/node_modules/react-addons-test-utils",
|
|
||||||
"<rootDir>/node_modules/react-dom",
|
|
||||||
"<rootDir>/node_modules/underscore"
|
|
||||||
],
|
|
||||||
"modulePathIgnorePatterns": [
|
"modulePathIgnorePatterns": [
|
||||||
"<rootDir>/node_modules/"
|
"<rootDir>/node_modules/"
|
||||||
]
|
]
|
||||||
|
|||||||
@ -1 +0,0 @@
|
|||||||
module.exports = [];
|
|
||||||
2
src/client/__mocks__/socket.js
Normal file
2
src/client/__mocks__/socket.js
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
import EventEmitter from 'events'
|
||||||
|
export default new EventEmitter()
|
||||||
3
src/client/__mocks__/store.js
Normal file
3
src/client/__mocks__/store.js
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
import configureStore from 'redux-mock-store'
|
||||||
|
import { middlewares } from '../middlewares.js'
|
||||||
|
export default configureStore(middlewares)({})
|
||||||
22
src/client/__mocks__/window.js
Normal file
22
src/client/__mocks__/window.js
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
import Promise from 'bluebird'
|
||||||
|
|
||||||
|
export const createObjectURL = object => 'blob://' + String(object)
|
||||||
|
|
||||||
|
class MediaStream {}
|
||||||
|
export function getUserMedia () {
|
||||||
|
return !getUserMedia.shouldFail
|
||||||
|
? Promise.resolve(getUserMedia.stream)
|
||||||
|
: Promise.reject(new Error('test'))
|
||||||
|
}
|
||||||
|
getUserMedia.fail = shouldFail => getUserMedia.shouldFail = shouldFail
|
||||||
|
getUserMedia.stream = new MediaStream()
|
||||||
|
|
||||||
|
export const navigator = window.navigator
|
||||||
|
|
||||||
|
export const play = jest.fn()
|
||||||
|
|
||||||
|
export const valueOf = jest.fn()
|
||||||
|
|
||||||
|
export const callId = 'call1234'
|
||||||
|
|
||||||
|
export const iceServers = []
|
||||||
96
src/client/__tests__/App-test.js
Normal file
96
src/client/__tests__/App-test.js
Normal file
@ -0,0 +1,96 @@
|
|||||||
|
jest.mock('../actions/CallActions.js')
|
||||||
|
jest.mock('../socket.js')
|
||||||
|
|
||||||
|
import * as constants from '../constants.js'
|
||||||
|
import App from '../containers/App.js'
|
||||||
|
import React from 'react'
|
||||||
|
import ReactDOM from 'react-dom'
|
||||||
|
import TestUtils from 'react-dom/test-utils'
|
||||||
|
import configureStore from 'redux-mock-store'
|
||||||
|
import reducers from '../reducers'
|
||||||
|
import { Provider } from 'react-redux'
|
||||||
|
import { init } from '../actions/CallActions.js'
|
||||||
|
import { middlewares } from '../store.js'
|
||||||
|
|
||||||
|
describe('App', () => {
|
||||||
|
|
||||||
|
const initAction = { type: 'INIT' }
|
||||||
|
|
||||||
|
let state
|
||||||
|
beforeEach(() => {
|
||||||
|
init.mockReturnValue(initAction)
|
||||||
|
state = reducers()
|
||||||
|
})
|
||||||
|
|
||||||
|
let component, node, store
|
||||||
|
function render () {
|
||||||
|
store = configureStore(middlewares)(state)
|
||||||
|
component = TestUtils.renderIntoDocument(
|
||||||
|
<Provider store={store}>
|
||||||
|
<App />
|
||||||
|
</Provider>
|
||||||
|
)
|
||||||
|
node = ReactDOM.findDOMNode(component)
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('render', () => {
|
||||||
|
it('renders without issues', () => {
|
||||||
|
render()
|
||||||
|
expect(node).toBeTruthy()
|
||||||
|
expect(init.mock.calls.length).toBe(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('state', () => {
|
||||||
|
let alert
|
||||||
|
beforeEach(() => {
|
||||||
|
state.streams = state.streams.merge({
|
||||||
|
test: 'blob://'
|
||||||
|
})
|
||||||
|
state.peers = {
|
||||||
|
test: {}
|
||||||
|
}
|
||||||
|
state.notifications = state.notifications.merge({
|
||||||
|
'notification1': {
|
||||||
|
id: 'notification1',
|
||||||
|
message: 'test',
|
||||||
|
type: 'warning'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const alerts = state.alerts.asMutable()
|
||||||
|
alert = {
|
||||||
|
dismissable: true,
|
||||||
|
action: 'Dismiss',
|
||||||
|
message: 'test alert'
|
||||||
|
}
|
||||||
|
alerts.push(alert)
|
||||||
|
state.alerts = alerts
|
||||||
|
render()
|
||||||
|
store.clearActions()
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('alerts', () => {
|
||||||
|
it('can be dismissed', () => {
|
||||||
|
const dismiss = node.querySelector('.action-alert-dismiss')
|
||||||
|
TestUtils.Simulate.click(dismiss)
|
||||||
|
expect(store.getActions()).toEqual([{
|
||||||
|
type: constants.ALERT_DISMISS,
|
||||||
|
payload: alert
|
||||||
|
}])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('video', () => {
|
||||||
|
it('can be activated', () => {
|
||||||
|
const video = node.querySelector('video')
|
||||||
|
TestUtils.Simulate.click(video)
|
||||||
|
expect(store.getActions()).toEqual([{
|
||||||
|
type: constants.ACTIVE_TOGGLE,
|
||||||
|
payload: { userId: constants.ME }
|
||||||
|
}])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
11
src/client/__tests__/store-test.js
Normal file
11
src/client/__tests__/store-test.js
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
window.localStorage = { log: true }
|
||||||
|
import logger from 'redux-logger'
|
||||||
|
const store = require('../store.js')
|
||||||
|
|
||||||
|
describe('store', () => {
|
||||||
|
|
||||||
|
it('should load logger middleware', () => {
|
||||||
|
expect(store.middlewares.some(m => m === logger)).toBeTruthy()
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
126
src/client/__tests__/window-test.js
Normal file
126
src/client/__tests__/window-test.js
Normal file
@ -0,0 +1,126 @@
|
|||||||
|
import Promise from 'bluebird'
|
||||||
|
|
||||||
|
import {
|
||||||
|
createObjectURL,
|
||||||
|
getUserMedia,
|
||||||
|
navigator,
|
||||||
|
play,
|
||||||
|
valueOf
|
||||||
|
} from '../window.js'
|
||||||
|
|
||||||
|
describe('window', () => {
|
||||||
|
|
||||||
|
describe('getUserMedia', () => {
|
||||||
|
|
||||||
|
class MediaStream {}
|
||||||
|
const stream = new MediaStream()
|
||||||
|
const constraints = { video: true }
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
delete navigator.mediaDevices
|
||||||
|
delete navigator.getUserMedia
|
||||||
|
delete navigator.webkitGetUserMedia
|
||||||
|
})
|
||||||
|
|
||||||
|
it('calls navigator.mediaDevices.getUserMedia', () => {
|
||||||
|
const promise = Promise.resolve(stream)
|
||||||
|
navigator.mediaDevices = {
|
||||||
|
getUserMedia: jest.fn().mockReturnValue(promise)
|
||||||
|
}
|
||||||
|
expect(getUserMedia(constraints)).toBe(promise)
|
||||||
|
})
|
||||||
|
|
||||||
|
;['getUserMedia', 'webkitGetUserMedia'].forEach((method) => {
|
||||||
|
it(`it calls navigator.${method} as a fallback`, () => {
|
||||||
|
navigator[method] = jest.fn()
|
||||||
|
.mockImplementation(
|
||||||
|
(constraints, onSuccess, onError) => onSuccess(stream)
|
||||||
|
)
|
||||||
|
return getUserMedia(constraints)
|
||||||
|
.then(s => expect(s).toBe(stream))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('throws error when no supported method', done => {
|
||||||
|
getUserMedia(constraints)
|
||||||
|
.asCallback(err => {
|
||||||
|
expect(err).toBeTruthy()
|
||||||
|
expect(err.message).toBe('Browser unsupported')
|
||||||
|
done()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('play', () => {
|
||||||
|
|
||||||
|
let v1, v2
|
||||||
|
beforeEach(() => {
|
||||||
|
v1 = window.document.createElement('video')
|
||||||
|
v2 = window.document.createElement('video')
|
||||||
|
window.document.body.appendChild(v1)
|
||||||
|
window.document.body.appendChild(v2)
|
||||||
|
v1.play = jest.fn()
|
||||||
|
v2.play = jest.fn()
|
||||||
|
})
|
||||||
|
afterEach(() => {
|
||||||
|
window.document.body.removeChild(v1)
|
||||||
|
window.document.body.removeChild(v2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('gets all videos and plays them', () => {
|
||||||
|
play()
|
||||||
|
expect(v1.play.mock.calls.length).toBe(1)
|
||||||
|
expect(v2.play.mock.calls.length).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not fail on error', () => {
|
||||||
|
v1.play.mockImplementation(() => { throw new Error('test') })
|
||||||
|
play()
|
||||||
|
expect(v1.play.mock.calls.length).toBe(1)
|
||||||
|
expect(v2.play.mock.calls.length).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('navigator', () => {
|
||||||
|
|
||||||
|
it('exposes window.navigator', () => {
|
||||||
|
expect(navigator).toBe(window.navigator)
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('createObjectURL', () => {
|
||||||
|
|
||||||
|
it('calls window.URL.createObjectURL', () => {
|
||||||
|
window.URL.createObjectURL = jest.fn().mockReturnValue('test')
|
||||||
|
expect(createObjectURL()).toBe('test')
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('valueOf', () => {
|
||||||
|
|
||||||
|
let input
|
||||||
|
beforeEach(() => {
|
||||||
|
input = window.document.createElement('input')
|
||||||
|
input.setAttribute('id', 'my-main-id')
|
||||||
|
input.value = 'test'
|
||||||
|
window.document.body.appendChild(input)
|
||||||
|
})
|
||||||
|
afterEach(() => {
|
||||||
|
window.document.body.removeChild(input)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return value of input', () => {
|
||||||
|
expect(valueOf('my-main-id')).toEqual('test')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not fail when not found', () => {
|
||||||
|
expect(valueOf('my-main-id2')).toEqual(null)
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
@ -1,78 +0,0 @@
|
|||||||
jest.unmock('../notify.js');
|
|
||||||
|
|
||||||
const dispatcher = require('../../dispatcher/dispatcher.js');
|
|
||||||
const notify = require('../notify.js');
|
|
||||||
|
|
||||||
describe('notify', () => {
|
|
||||||
|
|
||||||
beforeEach(() => dispatcher.dispatch.mockClear());
|
|
||||||
|
|
||||||
describe('info', () => {
|
|
||||||
|
|
||||||
it('should dispatch info notification', () => {
|
|
||||||
notify.info('test: {0} {1}', 'arg1', 'arg2');
|
|
||||||
|
|
||||||
expect(dispatcher.dispatch.mock.calls).toEqual([[{
|
|
||||||
type: 'notify',
|
|
||||||
notification: {
|
|
||||||
message: 'test: arg1 arg2',
|
|
||||||
type: 'info'
|
|
||||||
}
|
|
||||||
}]]);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('warn', () => {
|
|
||||||
|
|
||||||
it('should dispatch warning notification', () => {
|
|
||||||
notify.warn('test: {0} {1}', 'arg1', 'arg2');
|
|
||||||
|
|
||||||
expect(dispatcher.dispatch.mock.calls).toEqual([[{
|
|
||||||
type: 'notify',
|
|
||||||
notification: {
|
|
||||||
message: 'test: arg1 arg2',
|
|
||||||
type: 'warning'
|
|
||||||
}
|
|
||||||
}]]);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('error', () => {
|
|
||||||
|
|
||||||
it('should dispatch error notification', () => {
|
|
||||||
notify.error('test: {0} {1}', 'arg1', 'arg2');
|
|
||||||
|
|
||||||
expect(dispatcher.dispatch.mock.calls).toEqual([[{
|
|
||||||
type: 'notify',
|
|
||||||
notification: {
|
|
||||||
message: 'test: arg1 arg2',
|
|
||||||
type: 'error'
|
|
||||||
}
|
|
||||||
}]]);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('alert', () => {
|
|
||||||
|
|
||||||
it('should dispatch an alert', () => {
|
|
||||||
|
|
||||||
notify.alert('alert!', true);
|
|
||||||
|
|
||||||
expect(dispatcher.dispatch.mock.calls).toEqual([[{
|
|
||||||
type: 'alert',
|
|
||||||
alert: {
|
|
||||||
action: 'Dismiss',
|
|
||||||
dismissable: true,
|
|
||||||
message: 'alert!',
|
|
||||||
type: 'warning'
|
|
||||||
}
|
|
||||||
}]]);
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
@ -1,42 +0,0 @@
|
|||||||
const dispatcher = require('../dispatcher/dispatcher.js');
|
|
||||||
|
|
||||||
function format(string, args) {
|
|
||||||
string = args
|
|
||||||
.reduce((string, arg, i) => string.replace('{' + i + '}', arg), string);
|
|
||||||
return string;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _notify(type, args) {
|
|
||||||
let string = args[0] || '';
|
|
||||||
let message = format(string, Array.prototype.slice.call(args, 1));
|
|
||||||
dispatcher.dispatch({
|
|
||||||
type: 'notify',
|
|
||||||
notification: { type, message }
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function info() {
|
|
||||||
_notify('info', arguments);
|
|
||||||
}
|
|
||||||
|
|
||||||
function warn() {
|
|
||||||
_notify('warning', arguments);
|
|
||||||
}
|
|
||||||
|
|
||||||
function error() {
|
|
||||||
_notify('error', arguments);
|
|
||||||
}
|
|
||||||
|
|
||||||
function alert(message, dismissable) {
|
|
||||||
dispatcher.dispatch({
|
|
||||||
type: 'alert',
|
|
||||||
alert: {
|
|
||||||
action: dismissable ? 'Dismiss' : '',
|
|
||||||
dismissable: !!dismissable,
|
|
||||||
message,
|
|
||||||
type: 'warning'
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { alert, info, warn, error };
|
|
||||||
50
src/client/actions/CallActions.js
Normal file
50
src/client/actions/CallActions.js
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
import * as NotifyActions from './NotifyActions.js'
|
||||||
|
import * as SocketActions from './SocketActions.js'
|
||||||
|
import * as StreamActions from './StreamActions.js'
|
||||||
|
import * as constants from '../constants.js'
|
||||||
|
import Promise from 'bluebird'
|
||||||
|
import socket from '../socket.js'
|
||||||
|
import { callId, getUserMedia } from '../window.js'
|
||||||
|
|
||||||
|
export const init = () => dispatch => {
|
||||||
|
return dispatch({
|
||||||
|
type: constants.INIT,
|
||||||
|
payload: Promise.all([
|
||||||
|
connect()(dispatch),
|
||||||
|
getCameraStream()(dispatch)
|
||||||
|
])
|
||||||
|
.spread((socket, stream) => {
|
||||||
|
dispatch(SocketActions.handshake({
|
||||||
|
socket,
|
||||||
|
roomName: callId,
|
||||||
|
stream
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export const connect = () => dispatch => {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
socket.once('connect', () => {
|
||||||
|
resolve(socket)
|
||||||
|
})
|
||||||
|
socket.on('connect', () => {
|
||||||
|
dispatch(NotifyActions.warning('Connected to server socket'))
|
||||||
|
})
|
||||||
|
socket.on('disconnect', () => {
|
||||||
|
dispatch(NotifyActions.error('Server socket disconnected'))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getCameraStream = () => dispatch => {
|
||||||
|
return getUserMedia({ video: true, audio: true })
|
||||||
|
.then(stream => {
|
||||||
|
dispatch(StreamActions.addStream({ stream, userId: constants.ME }))
|
||||||
|
return stream
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
dispatch(NotifyActions.alert('Could not get access to microphone & camera'))
|
||||||
|
return null
|
||||||
|
})
|
||||||
|
}
|
||||||
68
src/client/actions/NotifyActions.js
Normal file
68
src/client/actions/NotifyActions.js
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
import * as constants from '../constants.js'
|
||||||
|
import _ from 'underscore'
|
||||||
|
|
||||||
|
const TIMEOUT = 5000
|
||||||
|
|
||||||
|
function format (string, args) {
|
||||||
|
string = args
|
||||||
|
.reduce((string, arg, i) => string.replace('{' + i + '}', arg), string)
|
||||||
|
return string
|
||||||
|
}
|
||||||
|
|
||||||
|
const _notify = (type, args) => dispatch => {
|
||||||
|
let string = args[0] || ''
|
||||||
|
let message = format(string, Array.prototype.slice.call(args, 1))
|
||||||
|
const id = _.uniqueId('notification')
|
||||||
|
const payload = { id, type, message }
|
||||||
|
dispatch({
|
||||||
|
type: constants.NOTIFY,
|
||||||
|
payload
|
||||||
|
})
|
||||||
|
setTimeout(() => {
|
||||||
|
dispatch({
|
||||||
|
type: constants.NOTIFY_DISMISS,
|
||||||
|
payload: { id }
|
||||||
|
})
|
||||||
|
}, TIMEOUT)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const info = function () {
|
||||||
|
return dispatch => _notify('info', arguments)(dispatch)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const warning = function () {
|
||||||
|
return dispatch => _notify('warning', arguments)(dispatch)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const error = function () {
|
||||||
|
return dispatch => _notify('error', arguments)(dispatch)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const clear = () => ({
|
||||||
|
type: constants.NOTIFY_CLEAR
|
||||||
|
})
|
||||||
|
|
||||||
|
export function alert (message, dismissable) {
|
||||||
|
return {
|
||||||
|
type: constants.ALERT,
|
||||||
|
payload: {
|
||||||
|
action: dismissable ? 'Dismiss' : '',
|
||||||
|
dismissable: !!dismissable,
|
||||||
|
message,
|
||||||
|
type: 'warning'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const dismissAlert = alert => {
|
||||||
|
return {
|
||||||
|
type: constants.ALERT_DISMISS,
|
||||||
|
payload: alert
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const clearAlerts = () => {
|
||||||
|
return {
|
||||||
|
type: constants.ALERT_CLEAR
|
||||||
|
}
|
||||||
|
}
|
||||||
132
src/client/actions/PeerActions.js
Normal file
132
src/client/actions/PeerActions.js
Normal file
@ -0,0 +1,132 @@
|
|||||||
|
import * as NotifyActions from '../actions/NotifyActions.js'
|
||||||
|
import * as StreamActions from '../actions/StreamActions.js'
|
||||||
|
import * as constants from '../constants.js'
|
||||||
|
import Peer from 'simple-peer'
|
||||||
|
import _ from 'underscore'
|
||||||
|
import _debug from 'debug'
|
||||||
|
import { play, iceServers } from '../window.js'
|
||||||
|
|
||||||
|
const debug = _debug('peercalls')
|
||||||
|
|
||||||
|
class PeerHandler {
|
||||||
|
constructor ({ socket, user, dispatch, getState }) {
|
||||||
|
this.socket = socket
|
||||||
|
this.user = user
|
||||||
|
this.dispatch = dispatch
|
||||||
|
this.getState = getState
|
||||||
|
}
|
||||||
|
handleError = err => {
|
||||||
|
const { dispatch, getState, user } = this
|
||||||
|
debug('peer: %s, error %s', user.id, err.stack)
|
||||||
|
dispatch(NotifyActions.error('A peer connection error occurred'))
|
||||||
|
const peer = getState().peers[user.id]
|
||||||
|
peer && peer.destroy()
|
||||||
|
dispatch(removePeer(user.id))
|
||||||
|
}
|
||||||
|
handleSignal = signal => {
|
||||||
|
const { socket, user } = this
|
||||||
|
debug('peer: %s, signal: %o', user.id, signal)
|
||||||
|
|
||||||
|
const payload = { userId: user.id, signal }
|
||||||
|
socket.emit('signal', payload)
|
||||||
|
}
|
||||||
|
handleConnect = () => {
|
||||||
|
const { dispatch, user } = this
|
||||||
|
debug('peer: %s, connect', user.id)
|
||||||
|
dispatch(NotifyActions.warning('Peer connection established'))
|
||||||
|
play()
|
||||||
|
}
|
||||||
|
handleStream = stream => {
|
||||||
|
const { user, dispatch } = this
|
||||||
|
debug('peer: %s, stream', user.id)
|
||||||
|
dispatch(StreamActions.addStream({
|
||||||
|
userId: user.id,
|
||||||
|
stream
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
handleData = object => {
|
||||||
|
const { dispatch, user } = this
|
||||||
|
object = JSON.parse(new window.TextDecoder('utf-8').decode(object))
|
||||||
|
debug('peer: %s, message: %o', user.id, object)
|
||||||
|
const message = user.id + ': ' + object.message
|
||||||
|
dispatch(NotifyActions.info(message))
|
||||||
|
}
|
||||||
|
handleClose = () => {
|
||||||
|
const { dispatch, user } = this
|
||||||
|
debug('peer: %s, close', user.id)
|
||||||
|
dispatch(NotifyActions.error('Peer connection closed'))
|
||||||
|
dispatch(StreamActions.removeStream(user.id))
|
||||||
|
dispatch(removePeer(user.id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Object} options
|
||||||
|
* @param {Socket} options.socket
|
||||||
|
* @param {User} options.user
|
||||||
|
* @param {String} options.user.id
|
||||||
|
* @param {Boolean} [options.initiator=false]
|
||||||
|
* @param {MediaStream} [options.stream]
|
||||||
|
*/
|
||||||
|
export function createPeer ({ socket, user, initiator, stream }) {
|
||||||
|
return (dispatch, getState) => {
|
||||||
|
const userId = user.id
|
||||||
|
debug('create peer: %s, stream:', userId, stream)
|
||||||
|
dispatch(NotifyActions.warning('Connecting to peer...'))
|
||||||
|
|
||||||
|
const oldPeer = getState().peers[userId]
|
||||||
|
if (oldPeer) {
|
||||||
|
dispatch(NotifyActions.info('Cleaning up old connection...'))
|
||||||
|
oldPeer.destroy()
|
||||||
|
dispatch(removePeer(userId))
|
||||||
|
}
|
||||||
|
|
||||||
|
const peer = new Peer({
|
||||||
|
initiator: socket.id === initiator,
|
||||||
|
config: { iceServers },
|
||||||
|
// Allow the peer to receive video, even if it's not sending stream:
|
||||||
|
// https://github.com/feross/simple-peer/issues/95
|
||||||
|
offerConstraints: {
|
||||||
|
offerToReceiveAudio: true,
|
||||||
|
offerToReceiveVideo: true
|
||||||
|
},
|
||||||
|
stream
|
||||||
|
})
|
||||||
|
|
||||||
|
const handler = new PeerHandler({
|
||||||
|
socket,
|
||||||
|
user,
|
||||||
|
dispatch,
|
||||||
|
getState
|
||||||
|
})
|
||||||
|
|
||||||
|
peer.once(constants.PEER_EVENT_ERROR, handler.handleError)
|
||||||
|
peer.once(constants.PEER_EVENT_CONNECT, handler.handleConnect)
|
||||||
|
peer.once(constants.PEER_EVENT_CLOSE, handler.handleClose)
|
||||||
|
peer.on(constants.PEER_EVENT_SIGNAL, handler.handleSignal)
|
||||||
|
peer.on(constants.PEER_EVENT_STREAM, handler.handleStream)
|
||||||
|
peer.on(constants.PEER_EVENT_DATA, handler.handleData)
|
||||||
|
|
||||||
|
dispatch(addPeer({ peer, userId }))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const addPeer = ({ peer, userId }) => ({
|
||||||
|
type: constants.PEER_ADD,
|
||||||
|
payload: { peer, userId }
|
||||||
|
})
|
||||||
|
|
||||||
|
export const removePeer = userId => ({
|
||||||
|
type: constants.PEER_REMOVE,
|
||||||
|
payload: { userId }
|
||||||
|
})
|
||||||
|
|
||||||
|
export const destroyPeers = () => ({
|
||||||
|
type: constants.PEERS_DESTROY
|
||||||
|
})
|
||||||
|
|
||||||
|
export const sendMessage = message => (dispatch, getState) => {
|
||||||
|
message = JSON.stringify({ message })
|
||||||
|
const { peers } = getState()
|
||||||
|
_.each(peers, peer => peer.send(message))
|
||||||
|
}
|
||||||
64
src/client/actions/SocketActions.js
Normal file
64
src/client/actions/SocketActions.js
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
import * as NotifyActions from '../actions/NotifyActions.js'
|
||||||
|
import * as PeerActions from '../actions/PeerActions.js'
|
||||||
|
import * as constants from '../constants.js'
|
||||||
|
import _ from 'underscore'
|
||||||
|
import _debug from 'debug'
|
||||||
|
|
||||||
|
const debug = _debug('peercalls')
|
||||||
|
|
||||||
|
class SocketHandler {
|
||||||
|
constructor ({ socket, roomName, stream, dispatch, getState }) {
|
||||||
|
this.socket = socket
|
||||||
|
this.roomName = roomName
|
||||||
|
this.stream = stream
|
||||||
|
this.dispatch = dispatch
|
||||||
|
this.getState = getState
|
||||||
|
}
|
||||||
|
handleSignal = ({ userId, signal }) => {
|
||||||
|
const { getState } = this
|
||||||
|
const peer = getState().peers[userId]
|
||||||
|
// debug('socket signal, userId: %s, signal: %o', userId, signal);
|
||||||
|
if (!peer) return debug('user: %s, no peer found', userId)
|
||||||
|
peer.signal(signal)
|
||||||
|
}
|
||||||
|
handleUsers = ({ initiator, users }) => {
|
||||||
|
const { socket, stream, dispatch, getState } = this
|
||||||
|
debug('socket users: %o', users)
|
||||||
|
dispatch(NotifyActions.info('Connected users: {0}', users.length))
|
||||||
|
const { peers } = getState()
|
||||||
|
|
||||||
|
users
|
||||||
|
.filter(user => !peers[user.id] && user.id !== socket.id)
|
||||||
|
.forEach(user => dispatch(PeerActions.createPeer({
|
||||||
|
socket,
|
||||||
|
user,
|
||||||
|
initiator,
|
||||||
|
stream
|
||||||
|
})))
|
||||||
|
|
||||||
|
let newUsersMap = _.indexBy(users, 'id')
|
||||||
|
_.keys(peers)
|
||||||
|
.filter(id => !newUsersMap[id])
|
||||||
|
.forEach(id => peers[id].destroy())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function handshake ({ socket, roomName, stream }) {
|
||||||
|
return (dispatch, getState) => {
|
||||||
|
const handler = new SocketHandler({
|
||||||
|
socket,
|
||||||
|
roomName,
|
||||||
|
stream,
|
||||||
|
dispatch,
|
||||||
|
getState
|
||||||
|
})
|
||||||
|
|
||||||
|
socket.on(constants.SOCKET_EVENT_SIGNAL, handler.handleSignal)
|
||||||
|
socket.on(constants.SOCKET_EVENT_USERS, handler.handleUsers)
|
||||||
|
|
||||||
|
debug('socket.id: %s', socket.id)
|
||||||
|
debug('emit ready for room: %s', roomName)
|
||||||
|
dispatch(NotifyActions.info('Ready for connections'))
|
||||||
|
socket.emit('ready', roomName)
|
||||||
|
}
|
||||||
|
}
|
||||||
24
src/client/actions/StreamActions.js
Normal file
24
src/client/actions/StreamActions.js
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
import * as constants from '../constants.js'
|
||||||
|
|
||||||
|
export const addStream = ({ stream, userId }) => ({
|
||||||
|
type: constants.STREAM_ADD,
|
||||||
|
payload: {
|
||||||
|
userId,
|
||||||
|
stream
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
export const removeStream = userId => ({
|
||||||
|
type: constants.STREAM_REMOVE,
|
||||||
|
payload: { userId }
|
||||||
|
})
|
||||||
|
|
||||||
|
export const setActive = userId => ({
|
||||||
|
type: constants.ACTIVE_SET,
|
||||||
|
payload: { userId }
|
||||||
|
})
|
||||||
|
|
||||||
|
export const toggleActive = userId => ({
|
||||||
|
type: constants.ACTIVE_TOGGLE,
|
||||||
|
payload: { userId }
|
||||||
|
})
|
||||||
92
src/client/actions/__tests__/CallActions-test.js
Normal file
92
src/client/actions/__tests__/CallActions-test.js
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
jest.mock('../../socket.js')
|
||||||
|
jest.mock('../../window.js')
|
||||||
|
jest.mock('../../store.js')
|
||||||
|
jest.mock('../SocketActions.js')
|
||||||
|
|
||||||
|
import * as CallActions from '../CallActions.js'
|
||||||
|
import * as SocketActions from '../SocketActions.js'
|
||||||
|
import * as constants from '../../constants.js'
|
||||||
|
import socket from '../../socket.js'
|
||||||
|
import store from '../../store.js'
|
||||||
|
import { callId, getUserMedia } from '../../window.js'
|
||||||
|
|
||||||
|
jest.useFakeTimers()
|
||||||
|
|
||||||
|
describe('reducers/alerts', () => {
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
store.clearActions()
|
||||||
|
getUserMedia.fail(false)
|
||||||
|
SocketActions.handshake.mockReturnValue(jest.fn())
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
jest.runAllTimers()
|
||||||
|
socket.removeAllListeners()
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('init', () => {
|
||||||
|
|
||||||
|
it('calls handshake.init when connected & got camera stream', done => {
|
||||||
|
const promise = store.dispatch(CallActions.init())
|
||||||
|
socket.emit('connect')
|
||||||
|
expect(store.getActions()).toEqual([{
|
||||||
|
type: constants.INIT_PENDING
|
||||||
|
}, {
|
||||||
|
type: constants.NOTIFY,
|
||||||
|
payload: {
|
||||||
|
id: jasmine.any(String),
|
||||||
|
message: 'Connected to server socket',
|
||||||
|
type: 'warning'
|
||||||
|
}
|
||||||
|
}])
|
||||||
|
promise.then(() => {
|
||||||
|
expect(SocketActions.handshake.mock.calls).toEqual([[{
|
||||||
|
socket,
|
||||||
|
roomName: callId,
|
||||||
|
stream: getUserMedia.stream
|
||||||
|
}]])
|
||||||
|
})
|
||||||
|
.then(done)
|
||||||
|
.catch(done.fail)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('calls dispatches disconnect message on disconnect', done => {
|
||||||
|
const promise = store.dispatch(CallActions.init())
|
||||||
|
socket.emit('connect')
|
||||||
|
socket.emit('disconnect')
|
||||||
|
expect(store.getActions()).toEqual([{
|
||||||
|
type: constants.INIT_PENDING
|
||||||
|
}, {
|
||||||
|
type: constants.NOTIFY,
|
||||||
|
payload: {
|
||||||
|
id: jasmine.any(String),
|
||||||
|
message: 'Connected to server socket',
|
||||||
|
type: 'warning'
|
||||||
|
}
|
||||||
|
}, {
|
||||||
|
type: constants.NOTIFY,
|
||||||
|
payload: {
|
||||||
|
id: jasmine.any(String),
|
||||||
|
message: 'Server socket disconnected',
|
||||||
|
type: 'error'
|
||||||
|
}
|
||||||
|
}])
|
||||||
|
promise.then(done).catch(done.fail)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('dispatches alert when failed to get media stream', done => {
|
||||||
|
getUserMedia.fail(true)
|
||||||
|
const promise = store.dispatch(CallActions.init())
|
||||||
|
socket.emit('connect')
|
||||||
|
promise
|
||||||
|
.then(result => {
|
||||||
|
expect(result.value).toBe(null)
|
||||||
|
done()
|
||||||
|
})
|
||||||
|
.catch(done.fail)
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
170
src/client/actions/__tests__/PeerActions-test.js
Normal file
170
src/client/actions/__tests__/PeerActions-test.js
Normal file
@ -0,0 +1,170 @@
|
|||||||
|
jest.mock('../../window.js')
|
||||||
|
jest.mock('simple-peer')
|
||||||
|
|
||||||
|
import * as PeerActions from '../PeerActions.js'
|
||||||
|
import Peer from 'simple-peer'
|
||||||
|
import { EventEmitter } from 'events'
|
||||||
|
import { createStore } from '../../store.js'
|
||||||
|
import { play } from '../../window.js'
|
||||||
|
|
||||||
|
describe('PeerActions', () => {
|
||||||
|
function createSocket () {
|
||||||
|
const socket = new EventEmitter()
|
||||||
|
socket.id = 'user1'
|
||||||
|
return socket
|
||||||
|
}
|
||||||
|
|
||||||
|
let socket, stream, user, store
|
||||||
|
beforeEach(() => {
|
||||||
|
store = createStore()
|
||||||
|
|
||||||
|
user = { id: 'user2' }
|
||||||
|
socket = createSocket()
|
||||||
|
Peer.instances = []
|
||||||
|
Peer.mockClear()
|
||||||
|
play.mockClear()
|
||||||
|
stream = { stream: true }
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('create', () => {
|
||||||
|
it('creates a new peer', () => {
|
||||||
|
store.dispatch(
|
||||||
|
PeerActions.createPeer({ socket, user, initiator: 'user2', stream })
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(Peer.instances.length).toBe(1)
|
||||||
|
expect(Peer.mock.calls.length).toBe(1)
|
||||||
|
expect(Peer.mock.calls[0][0].initiator).toBe(false)
|
||||||
|
expect(Peer.mock.calls[0][0].stream).toBe(stream)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('sets initiator correctly', () => {
|
||||||
|
store.dispatch(
|
||||||
|
PeerActions.createPeer({ socket, user, initiator: 'user1', stream })
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(Peer.instances.length).toBe(1)
|
||||||
|
expect(Peer.mock.calls.length).toBe(1)
|
||||||
|
expect(Peer.mock.calls[0][0].initiator).toBe(true)
|
||||||
|
expect(Peer.mock.calls[0][0].stream).toBe(stream)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('destroys old peer before creating new one', () => {
|
||||||
|
store.dispatch(
|
||||||
|
PeerActions.createPeer({ socket, user, initiator: 'user2', stream })
|
||||||
|
)
|
||||||
|
store.dispatch(
|
||||||
|
PeerActions.createPeer({ socket, user, initiator: 'user2', stream })
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(Peer.instances.length).toBe(2)
|
||||||
|
expect(Peer.mock.calls.length).toBe(2)
|
||||||
|
expect(Peer.instances[0].destroy.mock.calls.length).toBe(1)
|
||||||
|
expect(Peer.instances[1].destroy.mock.calls.length).toBe(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('events', () => {
|
||||||
|
let peer
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
store.dispatch(
|
||||||
|
PeerActions.createPeer({ socket, user, initiator: 'user1', stream })
|
||||||
|
)
|
||||||
|
peer = Peer.instances[0]
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('connect', () => {
|
||||||
|
beforeEach(() => peer.emit('connect'))
|
||||||
|
|
||||||
|
it('dispatches "play" action', () => {
|
||||||
|
expect(play.mock.calls.length).toBe(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('data', () => {
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
window.TextDecoder = class TextDecoder {
|
||||||
|
constructor (encoding) {
|
||||||
|
this.encoding = encoding
|
||||||
|
}
|
||||||
|
decode (object) {
|
||||||
|
return object.toString(this.encoding)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('decodes a message', () => {
|
||||||
|
const message = 'test'
|
||||||
|
const object = JSON.stringify({ message })
|
||||||
|
peer.emit('data', Buffer.from(object, 'utf-8'))
|
||||||
|
const { notifications } = store.getState()
|
||||||
|
const keys = Object.keys(notifications)
|
||||||
|
const n = notifications[keys[keys.length - 1]]
|
||||||
|
expect(n).toEqual({
|
||||||
|
id: jasmine.any(String),
|
||||||
|
type: 'info',
|
||||||
|
message: `${user.id}: ${message}`
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('get', () => {
|
||||||
|
it('returns undefined when not found', () => {
|
||||||
|
const { peers } = store.getState()
|
||||||
|
expect(peers[user.id]).not.toBeDefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns Peer instance when found', () => {
|
||||||
|
store.dispatch(
|
||||||
|
PeerActions.createPeer({ socket, user, initiator: 'user2', stream })
|
||||||
|
)
|
||||||
|
|
||||||
|
const { peers } = store.getState()
|
||||||
|
expect(peers[user.id]).toBe(Peer.instances[0])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('destroyPeers', () => {
|
||||||
|
it('destroys all peers and removes them', () => {
|
||||||
|
store.dispatch(PeerActions.createPeer({
|
||||||
|
socket, user: { id: 'user2' }, initiator: 'user2', stream
|
||||||
|
}))
|
||||||
|
store.dispatch(PeerActions.createPeer({
|
||||||
|
socket, user: { id: 'user3' }, initiator: 'user3', stream
|
||||||
|
}))
|
||||||
|
|
||||||
|
store.dispatch(PeerActions.destroyPeers())
|
||||||
|
|
||||||
|
expect(Peer.instances[0].destroy.mock.calls.length).toEqual(1)
|
||||||
|
expect(Peer.instances[1].destroy.mock.calls.length).toEqual(1)
|
||||||
|
|
||||||
|
const { peers } = store.getState()
|
||||||
|
expect(Object.keys(peers)).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('sendMessage', () => {
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
store.dispatch(PeerActions.createPeer({
|
||||||
|
socket, user: { id: 'user2' }, initiator: 'user2', stream
|
||||||
|
}))
|
||||||
|
store.dispatch(PeerActions.createPeer({
|
||||||
|
socket, user: { id: 'user3' }, initiator: 'user3', stream
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('sends a message to all peers', () => {
|
||||||
|
store.dispatch(PeerActions.sendMessage('test'))
|
||||||
|
const { peers } = store.getState()
|
||||||
|
expect(peers['user2'].send.mock.calls)
|
||||||
|
.toEqual([[ '{"message":"test"}' ]])
|
||||||
|
expect(peers['user3'].send.mock.calls)
|
||||||
|
.toEqual([[ '{"message":"test"}' ]])
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
})
|
||||||
149
src/client/actions/__tests__/SocketActions-test.js
Normal file
149
src/client/actions/__tests__/SocketActions-test.js
Normal file
@ -0,0 +1,149 @@
|
|||||||
|
jest.mock('simple-peer')
|
||||||
|
jest.mock('../../window.js')
|
||||||
|
|
||||||
|
import * as SocketActions from '../SocketActions.js'
|
||||||
|
import * as constants from '../../constants.js'
|
||||||
|
import Peer from 'simple-peer'
|
||||||
|
import { EventEmitter } from 'events'
|
||||||
|
import { createStore } from '../../store.js'
|
||||||
|
|
||||||
|
describe('SocketActions', () => {
|
||||||
|
const roomName = 'bla'
|
||||||
|
|
||||||
|
let socket, store
|
||||||
|
beforeEach(() => {
|
||||||
|
socket = new EventEmitter()
|
||||||
|
socket.id = 'a'
|
||||||
|
|
||||||
|
store = createStore()
|
||||||
|
|
||||||
|
Peer.instances = []
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('handshake', () => {
|
||||||
|
describe('users', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
store.dispatch(SocketActions.handshake({ socket, roomName }))
|
||||||
|
const payload = {
|
||||||
|
users: [{ id: 'a' }, { id: 'b' }],
|
||||||
|
initiator: 'a'
|
||||||
|
}
|
||||||
|
socket.emit('users', payload)
|
||||||
|
expect(Peer.instances.length).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('adds a peer for each new user and destroys peers for missing', () => {
|
||||||
|
const payload = {
|
||||||
|
users: [{ id: 'a' }, { id: 'c' }],
|
||||||
|
initiator: 'c'
|
||||||
|
}
|
||||||
|
socket.emit(constants.SOCKET_EVENT_USERS, payload)
|
||||||
|
|
||||||
|
// then
|
||||||
|
expect(Peer.instances.length).toBe(2)
|
||||||
|
expect(Peer.instances[0].destroy.mock.calls.length).toBe(1)
|
||||||
|
expect(Peer.instances[1].destroy.mock.calls.length).toBe(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('signal', () => {
|
||||||
|
let data
|
||||||
|
beforeEach(() => {
|
||||||
|
data = {}
|
||||||
|
store.dispatch(SocketActions.handshake({ socket, roomName }))
|
||||||
|
socket.emit('users', {
|
||||||
|
initiator: 'a',
|
||||||
|
users: [{ id: 'a' }, { id: 'b' }]
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should forward signal to peer', () => {
|
||||||
|
socket.emit('signal', {
|
||||||
|
userId: 'b',
|
||||||
|
data
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(Peer.instances.length).toBe(1)
|
||||||
|
expect(Peer.instances[0].signal.mock.calls.length).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does nothing if no peer', () => {
|
||||||
|
socket.emit('signal', {
|
||||||
|
userId: 'a',
|
||||||
|
data
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(Peer.instances.length).toBe(1)
|
||||||
|
expect(Peer.instances[0].signal.mock.calls.length).toBe(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('peer events', () => {
|
||||||
|
let peer
|
||||||
|
beforeEach(() => {
|
||||||
|
let ready = false
|
||||||
|
socket.once('ready', () => { ready = true })
|
||||||
|
|
||||||
|
store.dispatch(SocketActions.handshake({ socket, roomName }))
|
||||||
|
|
||||||
|
socket.emit('users', {
|
||||||
|
initiator: 'a',
|
||||||
|
users: [{ id: 'a' }, { id: 'b' }]
|
||||||
|
})
|
||||||
|
expect(Peer.instances.length).toBe(1)
|
||||||
|
peer = Peer.instances[0]
|
||||||
|
|
||||||
|
expect(ready).toBeDefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('error', () => {
|
||||||
|
it('destroys peer', () => {
|
||||||
|
peer.emit(constants.PEER_EVENT_ERROR, new Error('bla'))
|
||||||
|
expect(peer.destroy.mock.calls.length).toBe(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('signal', () => {
|
||||||
|
it('emits socket signal with user id', done => {
|
||||||
|
let signal = { bla: 'bla' }
|
||||||
|
|
||||||
|
socket.once('signal', payload => {
|
||||||
|
expect(payload.userId).toEqual('b')
|
||||||
|
expect(payload.signal).toBe(signal)
|
||||||
|
done()
|
||||||
|
})
|
||||||
|
|
||||||
|
peer.emit('signal', signal)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('stream', () => {
|
||||||
|
it('adds a stream to streamStore', () => {
|
||||||
|
const stream = {}
|
||||||
|
peer.emit(constants.PEER_EVENT_STREAM, stream)
|
||||||
|
|
||||||
|
expect(store.getState().streams).toEqual({
|
||||||
|
b: jasmine.any(String)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('close', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
const stream = {}
|
||||||
|
peer.emit(constants.PEER_EVENT_STREAM, stream)
|
||||||
|
expect(store.getState().streams).toEqual({
|
||||||
|
b: jasmine.any(String)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('removes stream & peer from store', () => {
|
||||||
|
expect(store.getState().peers).toEqual({ b: peer })
|
||||||
|
peer.emit('close')
|
||||||
|
expect(store.getState().streams).toEqual({})
|
||||||
|
expect(store.getState().peers).toEqual({})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@ -1,2 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
module.exports = object => window.URL.createObjectURL(object);
|
|
||||||
@ -1,17 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
const navigator = require('../browser/navigator.js');
|
|
||||||
const Promise = require('bluebird');
|
|
||||||
|
|
||||||
function getUserMedia(constraints) {
|
|
||||||
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
|
|
||||||
return navigator.mediaDevices.getUserMedia(constraints);
|
|
||||||
}
|
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
|
|
||||||
if (!getMedia) reject(new Error('Browser unsupported'));
|
|
||||||
getMedia.call(navigator, constraints, resolve, reject);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = getUserMedia;
|
|
||||||
@ -1,2 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
module.exports = window.navigator;
|
|
||||||
@ -1,15 +0,0 @@
|
|||||||
const debug = require('debug')('peer-calls:video');
|
|
||||||
|
|
||||||
function play() {
|
|
||||||
let videos = window.document.querySelectorAll('video');
|
|
||||||
Array.prototype.forEach.call(videos, (video, index) => {
|
|
||||||
debug('playing video: %s', index);
|
|
||||||
try {
|
|
||||||
video.play();
|
|
||||||
} catch (e) {
|
|
||||||
debug('error playing video: %s', e.name);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { play };
|
|
||||||
@ -1,53 +0,0 @@
|
|||||||
const Promise = require('bluebird');
|
|
||||||
const debug = require('debug')('peer-calls:call');
|
|
||||||
const dispatcher = require('./dispatcher/dispatcher.js');
|
|
||||||
const getUserMedia = require('./browser/getUserMedia.js');
|
|
||||||
const play = require('./browser/video.js').play;
|
|
||||||
const notify = require('./action/notify.js');
|
|
||||||
const handshake = require('./peer/handshake.js');
|
|
||||||
const socket = require('./socket.js');
|
|
||||||
|
|
||||||
dispatcher.register(action => {
|
|
||||||
if (action.type === 'play') play();
|
|
||||||
});
|
|
||||||
|
|
||||||
function init() {
|
|
||||||
const callId = window.document.getElementById('callId').value;
|
|
||||||
|
|
||||||
Promise.all([connect(), getCameraStream()])
|
|
||||||
.spread((_socket, stream) => {
|
|
||||||
debug('initializing peer connection');
|
|
||||||
handshake.init(_socket, callId, stream);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function connect() {
|
|
||||||
return new Promise(resolve => {
|
|
||||||
socket.once('connect', () => {
|
|
||||||
notify.warn('Connected to server socket');
|
|
||||||
debug('socket connected');
|
|
||||||
resolve(socket);
|
|
||||||
});
|
|
||||||
socket.on('disconnect', () => {
|
|
||||||
notify.error('Server socket disconnected');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function getCameraStream() {
|
|
||||||
return getUserMedia({ video: true, audio: true })
|
|
||||||
.then(stream => {
|
|
||||||
debug('got our media stream:', stream);
|
|
||||||
dispatcher.dispatch({
|
|
||||||
type: 'add-stream',
|
|
||||||
userId: '_me_',
|
|
||||||
stream
|
|
||||||
});
|
|
||||||
return stream;
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
notify.alert('Could not get access to microphone & camera');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { init };
|
|
||||||
52
src/client/components/Alerts.js
Normal file
52
src/client/components/Alerts.js
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
import React from 'react'
|
||||||
|
import PropTypes from 'prop-types'
|
||||||
|
import classnames from 'classnames'
|
||||||
|
|
||||||
|
export const AlertPropType = PropTypes.shape({
|
||||||
|
dismissable: PropTypes.bool,
|
||||||
|
action: PropTypes.string.isRequired,
|
||||||
|
message: PropTypes.string.isRequired
|
||||||
|
})
|
||||||
|
|
||||||
|
export class Alert extends React.PureComponent {
|
||||||
|
static propTypes = {
|
||||||
|
alert: AlertPropType,
|
||||||
|
dismiss: PropTypes.func.isRequired
|
||||||
|
}
|
||||||
|
dismiss = () => {
|
||||||
|
const { alert, dismiss } = this.props
|
||||||
|
dismiss(alert)
|
||||||
|
}
|
||||||
|
render () {
|
||||||
|
const { alert } = this.props
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={classnames('alert', alert.type)}>
|
||||||
|
<span>{alert.message}</span>
|
||||||
|
{alert.dismissable && (
|
||||||
|
<button
|
||||||
|
className="action-alert-dismiss"
|
||||||
|
onClick={this.dismiss}
|
||||||
|
>{alert.action}</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class Alerts extends React.PureComponent {
|
||||||
|
static propTypes = {
|
||||||
|
alerts: PropTypes.arrayOf(AlertPropType).isRequired,
|
||||||
|
dismiss: PropTypes.func.isRequired
|
||||||
|
}
|
||||||
|
render () {
|
||||||
|
const { alerts, dismiss } = this.props
|
||||||
|
return (
|
||||||
|
<div className="alerts">
|
||||||
|
{alerts.map((alert, i) => (
|
||||||
|
<Alert alert={alert} dismiss={dismiss} key={i} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
64
src/client/components/App.js
Normal file
64
src/client/components/App.js
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
import Alerts, { AlertPropType } from './Alerts.js'
|
||||||
|
import * as constants from '../constants.js'
|
||||||
|
import Input from './Input.js'
|
||||||
|
import Notifications, { NotificationPropTypes } from './Notifications.js'
|
||||||
|
import PropTypes from 'prop-types'
|
||||||
|
import React from 'react'
|
||||||
|
import Video from './Video.js'
|
||||||
|
import _ from 'underscore'
|
||||||
|
|
||||||
|
export default class App extends React.PureComponent {
|
||||||
|
static propTypes = {
|
||||||
|
active: PropTypes.string,
|
||||||
|
alerts: PropTypes.arrayOf(AlertPropType).isRequired,
|
||||||
|
dismissAlert: PropTypes.func.isRequired,
|
||||||
|
init: PropTypes.func.isRequired,
|
||||||
|
notifications: PropTypes.objectOf(NotificationPropTypes).isRequired,
|
||||||
|
notify: PropTypes.func.isRequired,
|
||||||
|
peers: PropTypes.object.isRequired,
|
||||||
|
sendMessage: PropTypes.func.isRequired,
|
||||||
|
streams: PropTypes.objectOf(PropTypes.string).isRequired,
|
||||||
|
toggleActive: PropTypes.func.isRequired
|
||||||
|
}
|
||||||
|
componentDidMount () {
|
||||||
|
const { init } = this.props
|
||||||
|
init()
|
||||||
|
}
|
||||||
|
render () {
|
||||||
|
const {
|
||||||
|
active,
|
||||||
|
alerts,
|
||||||
|
dismissAlert,
|
||||||
|
notifications,
|
||||||
|
notify,
|
||||||
|
peers,
|
||||||
|
sendMessage,
|
||||||
|
toggleActive,
|
||||||
|
streams
|
||||||
|
} = this.props
|
||||||
|
|
||||||
|
return (<div className="app">
|
||||||
|
<Alerts alerts={alerts} dismiss={dismissAlert} />
|
||||||
|
<Notifications notifications={notifications} />
|
||||||
|
<Input notify={notify} sendMessage={sendMessage} />
|
||||||
|
<div className="videos">
|
||||||
|
<Video
|
||||||
|
active={active === constants.ME}
|
||||||
|
onClick={toggleActive}
|
||||||
|
stream={streams[constants.ME]}
|
||||||
|
userId={constants.ME}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{_.map(peers, (_, userId) => (
|
||||||
|
<Video
|
||||||
|
active={userId === active}
|
||||||
|
key={userId}
|
||||||
|
onClick={toggleActive}
|
||||||
|
stream={streams[userId]}
|
||||||
|
userId={userId}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>)
|
||||||
|
}
|
||||||
|
}
|
||||||
51
src/client/components/Input.js
Normal file
51
src/client/components/Input.js
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
import PropTypes from 'prop-types'
|
||||||
|
import React from 'react'
|
||||||
|
|
||||||
|
export default class Input extends React.PureComponent {
|
||||||
|
static propTypes = {
|
||||||
|
notify: PropTypes.func.isRequired,
|
||||||
|
sendMessage: PropTypes.func.isRequired
|
||||||
|
}
|
||||||
|
constructor () {
|
||||||
|
super()
|
||||||
|
this.state = {
|
||||||
|
message: ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
handleChange = e => {
|
||||||
|
this.setState({
|
||||||
|
message: e.target.value
|
||||||
|
})
|
||||||
|
}
|
||||||
|
handleSubmit = e => {
|
||||||
|
e.preventDefault()
|
||||||
|
this.submit()
|
||||||
|
}
|
||||||
|
handleKeyPress = e => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault()
|
||||||
|
this.submit()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
submit = () => {
|
||||||
|
const { notify, sendMessage } = this.props
|
||||||
|
const { message } = this.state
|
||||||
|
notify('You: ' + message)
|
||||||
|
sendMessage(message)
|
||||||
|
this.setState({ message: '' })
|
||||||
|
}
|
||||||
|
render () {
|
||||||
|
const { message } = this.state
|
||||||
|
return (
|
||||||
|
<form className="input" onSubmit={this.handleSubmit}>
|
||||||
|
<input
|
||||||
|
onChange={this.handleChange}
|
||||||
|
onKeyPress={this.handleKeyPress}
|
||||||
|
placeholder="Enter your message..."
|
||||||
|
type="text"
|
||||||
|
value={message}
|
||||||
|
/>
|
||||||
|
</form>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
41
src/client/components/Notifications.js
Normal file
41
src/client/components/Notifications.js
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
import PropTypes from 'prop-types'
|
||||||
|
import React from 'react'
|
||||||
|
import classnames from 'classnames'
|
||||||
|
import { CSSTransitionGroup } from 'react-transition-group'
|
||||||
|
|
||||||
|
export const NotificationPropTypes = PropTypes.shape({
|
||||||
|
id: PropTypes.string.isRequired,
|
||||||
|
type: PropTypes.string.isRequired,
|
||||||
|
message: PropTypes.string.isRequired
|
||||||
|
})
|
||||||
|
|
||||||
|
export default class Notifications extends React.PureComponent {
|
||||||
|
static propTypes = {
|
||||||
|
notifications: PropTypes.objectOf(NotificationPropTypes).isRequired,
|
||||||
|
max: PropTypes.number.isRequired
|
||||||
|
}
|
||||||
|
static defaultProps = {
|
||||||
|
max: 10
|
||||||
|
}
|
||||||
|
render () {
|
||||||
|
const { notifications, max } = this.props
|
||||||
|
return (
|
||||||
|
<div className="notifications">
|
||||||
|
<CSSTransitionGroup
|
||||||
|
transitionEnterTimeout={200}
|
||||||
|
transitionLeaveTimeout={100}
|
||||||
|
transitionName="fade"
|
||||||
|
>
|
||||||
|
{Object.keys(notifications).slice(-max).map(id => (
|
||||||
|
<div
|
||||||
|
className={classnames(notifications[id].type, 'notification')}
|
||||||
|
key={id}
|
||||||
|
>
|
||||||
|
{notifications[id].message}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</CSSTransitionGroup>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
36
src/client/components/Video.js
Normal file
36
src/client/components/Video.js
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
import PropTypes from 'prop-types'
|
||||||
|
import React from 'react'
|
||||||
|
import classnames from 'classnames'
|
||||||
|
import { ME } from '../constants.js'
|
||||||
|
|
||||||
|
export default class Video extends React.PureComponent {
|
||||||
|
static propTypes = {
|
||||||
|
onClick: PropTypes.func,
|
||||||
|
active: PropTypes.bool.isRequired,
|
||||||
|
stream: PropTypes.string,
|
||||||
|
userId: PropTypes.string.isRequired
|
||||||
|
}
|
||||||
|
handleClick = e => {
|
||||||
|
const { onClick, userId } = this.props
|
||||||
|
this.play(e)
|
||||||
|
onClick(userId)
|
||||||
|
}
|
||||||
|
play = e => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.target.play()
|
||||||
|
}
|
||||||
|
render () {
|
||||||
|
const { active, stream, userId } = this.props
|
||||||
|
const className = classnames('video-container', { active })
|
||||||
|
return (
|
||||||
|
<div className={className}>
|
||||||
|
<video
|
||||||
|
muted={userId === ME}
|
||||||
|
onClick={this.handleClick}
|
||||||
|
onLoadedMetadata={this.play}
|
||||||
|
src={stream}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
66
src/client/components/__tests__/Input-test.js
Normal file
66
src/client/components/__tests__/Input-test.js
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
import Input from '../Input.js'
|
||||||
|
import React from 'react'
|
||||||
|
import ReactDOM from 'react-dom'
|
||||||
|
import TestUtils from 'react-dom/test-utils'
|
||||||
|
|
||||||
|
describe('components/Input', () => {
|
||||||
|
|
||||||
|
let component, node, notify, sendMessage
|
||||||
|
function render () {
|
||||||
|
notify = jest.fn()
|
||||||
|
sendMessage = jest.fn()
|
||||||
|
component = TestUtils.renderIntoDocument(
|
||||||
|
<Input
|
||||||
|
sendMessage={sendMessage}
|
||||||
|
notify={notify}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
node = ReactDOM.findDOMNode(component)
|
||||||
|
}
|
||||||
|
let message = 'test message'
|
||||||
|
|
||||||
|
beforeEach(() => render())
|
||||||
|
|
||||||
|
describe('send message', () => {
|
||||||
|
|
||||||
|
let input
|
||||||
|
beforeEach(() => {
|
||||||
|
sendMessage.mockClear()
|
||||||
|
input = node.querySelector('input')
|
||||||
|
TestUtils.Simulate.change(input, {
|
||||||
|
target: { value: message }
|
||||||
|
})
|
||||||
|
expect(input.value).toBe(message)
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('handleSubmit', () => {
|
||||||
|
it('sends a message', () => {
|
||||||
|
TestUtils.Simulate.submit(node)
|
||||||
|
expect(input.value).toBe('')
|
||||||
|
expect(sendMessage.mock.calls).toEqual([[ message ]])
|
||||||
|
expect(notify.mock.calls).toEqual([[ `You: ${message}` ]])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('handleKeyPress', () => {
|
||||||
|
it('sends a message', () => {
|
||||||
|
TestUtils.Simulate.keyPress(input, {
|
||||||
|
key: 'Enter'
|
||||||
|
})
|
||||||
|
expect(input.value).toBe('')
|
||||||
|
expect(sendMessage.mock.calls).toEqual([[ message ]])
|
||||||
|
expect(notify.mock.calls).toEqual([[ `You: ${message}` ]])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does nothing when other key pressed', () => {
|
||||||
|
TestUtils.Simulate.keyPress(input, {
|
||||||
|
key: 'test'
|
||||||
|
})
|
||||||
|
expect(sendMessage.mock.calls.length).toBe(0)
|
||||||
|
expect(notify.mock.calls.length).toBe(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
@ -1,74 +0,0 @@
|
|||||||
jest.unmock('../alert.js');
|
|
||||||
|
|
||||||
const React = require('react');
|
|
||||||
const ReactDOM = require('react-dom');
|
|
||||||
const TestUtils = require('react-addons-test-utils');
|
|
||||||
|
|
||||||
const Alert = require('../alert.js');
|
|
||||||
const dispatcher = require('../../dispatcher/dispatcher.js');
|
|
||||||
const alertStore = require('../../store/alertStore.js');
|
|
||||||
|
|
||||||
describe('alert', () => {
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
alertStore.getAlert.mockClear();
|
|
||||||
});
|
|
||||||
|
|
||||||
function render() {
|
|
||||||
let component = TestUtils.renderIntoDocument(<div><Alert /></div>);
|
|
||||||
return ReactDOM.findDOMNode(component);
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('render', () => {
|
|
||||||
|
|
||||||
it('should do nothing when no alert', () => {
|
|
||||||
let node = render();
|
|
||||||
expect(node.querySelector('.alert.hidden')).toBeTruthy();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should render alert', () => {
|
|
||||||
alertStore.getAlert.mockReturnValue({
|
|
||||||
message: 'example',
|
|
||||||
type: 'warning'
|
|
||||||
});
|
|
||||||
|
|
||||||
let node = render();
|
|
||||||
|
|
||||||
expect(node.querySelector('.alert.warning')).toBeTruthy();
|
|
||||||
expect(node.querySelector('.alert span').textContent).toMatch(/example/);
|
|
||||||
expect(node.querySelector('.alert button')).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should render dismissable alert', () => {
|
|
||||||
alertStore.getAlert.mockReturnValue({
|
|
||||||
message: 'example',
|
|
||||||
type: 'warning',
|
|
||||||
dismissable: true
|
|
||||||
});
|
|
||||||
|
|
||||||
let node = render();
|
|
||||||
|
|
||||||
expect(node.querySelector('.alert.warning')).toBeTruthy();
|
|
||||||
expect(node.querySelector('.alert span').textContent).toMatch(/example/);
|
|
||||||
expect(node.querySelector('.alert button')).toBeTruthy();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should dispatch dismiss alert on dismiss clicked', () => {
|
|
||||||
let alert = {
|
|
||||||
message: 'example',
|
|
||||||
type: 'warning',
|
|
||||||
dismissable: true
|
|
||||||
};
|
|
||||||
alertStore.getAlert.mockReturnValue(alert);
|
|
||||||
|
|
||||||
let node = render();
|
|
||||||
TestUtils.Simulate.click(node.querySelector('.alert button'));
|
|
||||||
|
|
||||||
expect(dispatcher.dispatch.mock.calls).toEqual([[{
|
|
||||||
type: 'alert-dismiss',
|
|
||||||
alert
|
|
||||||
}]]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
@ -1,62 +0,0 @@
|
|||||||
jest.unmock('../app.js');
|
|
||||||
jest.unmock('underscore');
|
|
||||||
|
|
||||||
const React = require('react');
|
|
||||||
const ReactDOM = require('react-dom');
|
|
||||||
const TestUtils = require('react-addons-test-utils');
|
|
||||||
|
|
||||||
require('../alert.js').mockImplementation(() => <div />);
|
|
||||||
require('../notifications.js').mockImplementation(() => <div />);
|
|
||||||
const App = require('../app.js');
|
|
||||||
const activeStore = require('../../store/activeStore.js');
|
|
||||||
const dispatcher = require('../../dispatcher/dispatcher.js');
|
|
||||||
const streamStore = require('../../store/streamStore.js');
|
|
||||||
|
|
||||||
describe('app', () => {
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
dispatcher.dispatch.mockClear();
|
|
||||||
});
|
|
||||||
|
|
||||||
function render(active) {
|
|
||||||
streamStore.getStreams.mockReturnValue({
|
|
||||||
user1: { stream: 1 },
|
|
||||||
user2: { stream: 2 }
|
|
||||||
});
|
|
||||||
let component = TestUtils.renderIntoDocument(<div><App /></div>);
|
|
||||||
return ReactDOM.findDOMNode(component).children[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
it('should render div.app', () => {
|
|
||||||
let node = render();
|
|
||||||
expect(node.tagName).toBe('DIV');
|
|
||||||
expect(node.className).toBe('app');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should have rendered two videos', () => {
|
|
||||||
let node = render();
|
|
||||||
|
|
||||||
expect(node.querySelectorAll('video').length).toBe(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should mark .active video', () => {
|
|
||||||
activeStore.getActive.mockReturnValue('user1');
|
|
||||||
activeStore.isActive.mockImplementation(test => test === 'user1');
|
|
||||||
|
|
||||||
let node = render();
|
|
||||||
expect(node.querySelectorAll('.video-container').length).toBe(2);
|
|
||||||
expect(node.querySelectorAll('.video-container.active').length).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should dispatch mark-active on video click', () => {
|
|
||||||
let node = render();
|
|
||||||
|
|
||||||
TestUtils.Simulate.click(node.querySelectorAll('video')[1]);
|
|
||||||
|
|
||||||
expect(dispatcher.dispatch.mock.calls).toEqual([[{
|
|
||||||
type: 'mark-active',
|
|
||||||
userId: 'user2'
|
|
||||||
}]]);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
@ -1,59 +0,0 @@
|
|||||||
jest.unmock('../notifications.js');
|
|
||||||
|
|
||||||
const React = require('react');
|
|
||||||
const ReactDOM = require('react-dom');
|
|
||||||
const TestUtils = require('react-addons-test-utils');
|
|
||||||
|
|
||||||
const Notifications = require('../notifications.js');
|
|
||||||
const notificationsStore = require('../../store/notificationsStore.js');
|
|
||||||
|
|
||||||
describe('alert', () => {
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
notificationsStore.getNotifications.mockClear();
|
|
||||||
notificationsStore.getNotifications.mockReturnValue([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
function render(component) {
|
|
||||||
let rendered = TestUtils.renderIntoDocument(<div>{component}</div>);
|
|
||||||
return ReactDOM.findDOMNode(rendered);
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('render', () => {
|
|
||||||
|
|
||||||
it('should render notifications placeholder', () => {
|
|
||||||
let node = render(<Notifications />);
|
|
||||||
expect(node.querySelector('.notifications')).toBeTruthy();
|
|
||||||
expect(node.querySelector('.notifications .notification')).toBeFalsy();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should render notifications', () => {
|
|
||||||
notificationsStore.getNotifications.mockReturnValue([{
|
|
||||||
_id: 1,
|
|
||||||
message: 'message 1',
|
|
||||||
type: 'warning'
|
|
||||||
}, {
|
|
||||||
_id: 2,
|
|
||||||
message: 'message 2',
|
|
||||||
type: 'error'
|
|
||||||
}]);
|
|
||||||
|
|
||||||
let node = render(<Notifications />);
|
|
||||||
expect(notificationsStore.getNotifications.mock.calls).toEqual([[ 10 ]]);
|
|
||||||
|
|
||||||
let c = node.querySelector('.notifications');
|
|
||||||
expect(c).toBeTruthy();
|
|
||||||
expect(c.querySelectorAll('.notification').length).toBe(2);
|
|
||||||
expect(c.querySelector('.notification.warning').textContent)
|
|
||||||
.toEqual('message 1');
|
|
||||||
expect(c.querySelector('.notification.error').textContent)
|
|
||||||
.toEqual('message 2');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should render max X notifications', () => {
|
|
||||||
render(<Notifications max={1} />);
|
|
||||||
expect(notificationsStore.getNotifications.mock.calls).toEqual([[ 1 ]]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
@ -1,30 +0,0 @@
|
|||||||
const React = require('react');
|
|
||||||
const alertStore = require('../store/alertStore.js');
|
|
||||||
const dispatcher = require('../dispatcher/dispatcher.js');
|
|
||||||
|
|
||||||
function alert() {
|
|
||||||
let alert = alertStore.getAlert();
|
|
||||||
if (!alert) return <div className="alert hidden"><span> </span></div>;
|
|
||||||
let button;
|
|
||||||
|
|
||||||
function dismiss() {
|
|
||||||
dispatcher.dispatch({
|
|
||||||
type: 'alert-dismiss',
|
|
||||||
alert
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (alert.dismissable) {
|
|
||||||
button = <button onClick={dismiss}>{alert.action}</button>;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={alert.type + ' alert'}>
|
|
||||||
<span>{alert.message}</span>
|
|
||||||
{button}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = alert;
|
|
||||||
@ -1,58 +0,0 @@
|
|||||||
const Alert = require('./alert.js');
|
|
||||||
const Input = require('./input.js');
|
|
||||||
const Notifications = require('./notifications.js');
|
|
||||||
const React = require('react');
|
|
||||||
const _ = require('underscore');
|
|
||||||
const activeStore = require('../store/activeStore.js');
|
|
||||||
const debug = require('debug')('peer-calls:app');
|
|
||||||
const dispatcher = require('../dispatcher/dispatcher.js');
|
|
||||||
const streamStore = require('../store/streamStore.js');
|
|
||||||
|
|
||||||
function app() {
|
|
||||||
let streams = streamStore.getStreams();
|
|
||||||
|
|
||||||
function play(event) {
|
|
||||||
try {
|
|
||||||
event.target.play();
|
|
||||||
} catch (e) {
|
|
||||||
debug('error starting video: %s', e.name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let videos = _.map(streams, (stream, userId) => {
|
|
||||||
let url = stream.url;
|
|
||||||
|
|
||||||
function markActive(event) {
|
|
||||||
play(event);
|
|
||||||
dispatcher.dispatch({
|
|
||||||
type: 'mark-active',
|
|
||||||
userId: activeStore.isActive(userId) ? undefined : userId
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let className = 'video-container';
|
|
||||||
className += activeStore.isActive(userId) ? ' active' : '';
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={className} key={userId}>
|
|
||||||
<video
|
|
||||||
muted={userId === '_me_'}
|
|
||||||
onClick={markActive}
|
|
||||||
onLoadedMetadata={play}
|
|
||||||
src={url}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
return (<div className="app">
|
|
||||||
<Alert />
|
|
||||||
<Notifications />
|
|
||||||
<Input />
|
|
||||||
<div className="videos">
|
|
||||||
{videos}
|
|
||||||
</div>
|
|
||||||
</div>);
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = app;
|
|
||||||
@ -1,39 +0,0 @@
|
|||||||
const React = require('react');
|
|
||||||
const peers = require('../peer/peers.js');
|
|
||||||
const notify = require('../action/notify.js');
|
|
||||||
|
|
||||||
const Input = React.createClass({
|
|
||||||
getInitialState() {
|
|
||||||
return {
|
|
||||||
visible: false,
|
|
||||||
message: ''
|
|
||||||
};
|
|
||||||
},
|
|
||||||
handleChange(e) {
|
|
||||||
this.setState({
|
|
||||||
message: e.target.value
|
|
||||||
});
|
|
||||||
},
|
|
||||||
handleSubmit(e) {
|
|
||||||
e.preventDefault();
|
|
||||||
const { message } = this.state;
|
|
||||||
peers.message(message);
|
|
||||||
notify.info('You: ' + message);
|
|
||||||
this.setState({ message: '' });
|
|
||||||
},
|
|
||||||
render() {
|
|
||||||
const { message } = this.state;
|
|
||||||
return (
|
|
||||||
<form className="input" onSubmit={this.handleSubmit}>
|
|
||||||
<input
|
|
||||||
onChange={this.handleChange}
|
|
||||||
placeholder="Enter your message..."
|
|
||||||
type="text"
|
|
||||||
value={message}
|
|
||||||
/>
|
|
||||||
</form>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = Input;
|
|
||||||
@ -1,30 +0,0 @@
|
|||||||
const React = require('react');
|
|
||||||
const Transition = require('react-addons-css-transition-group');
|
|
||||||
const notificationsStore = require('../store/notificationsStore.js');
|
|
||||||
|
|
||||||
function notifications(props) {
|
|
||||||
let notifs = notificationsStore.getNotifications(props.max || 10);
|
|
||||||
|
|
||||||
let notificationElements = notifs.map(notif => {
|
|
||||||
return (
|
|
||||||
<div className={notif.type + ' notification'} key={notif._id}>
|
|
||||||
{notif.message}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="notifications">
|
|
||||||
<Transition
|
|
||||||
transitionEnterTimeout={200}
|
|
||||||
transitionLeaveTimeout={100}
|
|
||||||
transitionName="fade"
|
|
||||||
>
|
|
||||||
{notificationElements}
|
|
||||||
</Transition>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = notifications;
|
|
||||||
35
src/client/constants.js
Normal file
35
src/client/constants.js
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
|
||||||
|
export const ACTIVE_SET = 'ACTIVE_SET'
|
||||||
|
export const ACTIVE_TOGGLE = 'ACTIVE_TOGGLE'
|
||||||
|
|
||||||
|
export const ALERT = 'ALERT'
|
||||||
|
export const ALERT_DISMISS = 'ALERT_DISMISS'
|
||||||
|
export const ALERT_CLEAR = 'ALERT_CLEAR'
|
||||||
|
|
||||||
|
export const INIT = 'INIT'
|
||||||
|
export const INIT_PENDING = `${INIT}_PENDING`
|
||||||
|
export const INIT_FULFILLED = `${INIT}_FULFILLED`
|
||||||
|
export const INIT_REJECTED = `${INIT}_REJECTED`
|
||||||
|
|
||||||
|
export const ME = '_me_'
|
||||||
|
|
||||||
|
export const NOTIFY = 'NOTIFY'
|
||||||
|
export const NOTIFY_DISMISS = 'NOTIFY_DISMISS'
|
||||||
|
export const NOTIFY_CLEAR = 'NOTIFY_CLEAR'
|
||||||
|
|
||||||
|
export const PEER_ADD = 'PEER_ADD'
|
||||||
|
export const PEER_REMOVE = 'PEER_REMOVE'
|
||||||
|
export const PEERS_DESTROY = 'PEERS_DESTROY'
|
||||||
|
|
||||||
|
export const PEER_EVENT_ERROR = 'error'
|
||||||
|
export const PEER_EVENT_CONNECT = 'connect'
|
||||||
|
export const PEER_EVENT_CLOSE = 'close'
|
||||||
|
export const PEER_EVENT_SIGNAL = 'signal'
|
||||||
|
export const PEER_EVENT_STREAM = 'stream'
|
||||||
|
export const PEER_EVENT_DATA = 'data'
|
||||||
|
|
||||||
|
export const SOCKET_EVENT_SIGNAL = 'signal'
|
||||||
|
export const SOCKET_EVENT_USERS = 'users'
|
||||||
|
|
||||||
|
export const STREAM_ADD = 'PEER_STREAM_ADD'
|
||||||
|
export const STREAM_REMOVE = 'PEER_STREAM_REMOVE'
|
||||||
29
src/client/containers/App.js
Normal file
29
src/client/containers/App.js
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
import * as CallActions from '../actions/CallActions.js'
|
||||||
|
import * as NotifyActions from '../actions/NotifyActions.js'
|
||||||
|
import * as PeerActions from '../actions/PeerActions.js'
|
||||||
|
import * as StreamActions from '../actions/StreamActions.js'
|
||||||
|
import App from '../components/App.js'
|
||||||
|
import { bindActionCreators } from 'redux'
|
||||||
|
import { connect } from 'react-redux'
|
||||||
|
|
||||||
|
function mapStateToProps (state) {
|
||||||
|
return {
|
||||||
|
streams: state.streams,
|
||||||
|
peers: state.peers,
|
||||||
|
alerts: state.alerts,
|
||||||
|
notifications: state.notifications,
|
||||||
|
active: state.active
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapDispatchToProps (dispatch) {
|
||||||
|
return {
|
||||||
|
toggleActive: bindActionCreators(StreamActions.toggleActive, dispatch),
|
||||||
|
sendMessage: bindActionCreators(PeerActions.sendMessage, dispatch),
|
||||||
|
dismissAlert: bindActionCreators(NotifyActions.dismissAlert, dispatch),
|
||||||
|
init: bindActionCreators(CallActions.init, dispatch),
|
||||||
|
notify: bindActionCreators(NotifyActions.info, dispatch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default connect(mapStateToProps, mapDispatchToProps)(App)
|
||||||
@ -1,51 +1,49 @@
|
|||||||
const iceServers = require('./iceServers.js');
|
const iceServers = require('./iceServers.js')
|
||||||
|
|
||||||
function noop() {}
|
function noop () {}
|
||||||
|
|
||||||
function checkTURNServer(turnConfig, timeout) {
|
function checkTURNServer (turnConfig, timeout) {
|
||||||
|
console.log('checking turn server', turnConfig)
|
||||||
|
|
||||||
console.log('checking turn server', turnConfig);
|
return new Promise(function (resolve, reject) {
|
||||||
|
setTimeout(function () {
|
||||||
|
if (promiseResolved) return
|
||||||
|
resolve(false)
|
||||||
|
promiseResolved = true
|
||||||
|
}, timeout || 5000)
|
||||||
|
|
||||||
return new Promise(function(resolve, reject) {
|
let promiseResolved = false
|
||||||
|
|
||||||
setTimeout(function() {
|
|
||||||
if (promiseResolved) return;
|
|
||||||
resolve(false);
|
|
||||||
promiseResolved = true;
|
|
||||||
}, timeout || 5000);
|
|
||||||
|
|
||||||
const promiseResolved = false;
|
|
||||||
const PeerConnection = window.RTCPeerConnection ||
|
const PeerConnection = window.RTCPeerConnection ||
|
||||||
window.mozRTCPeerConnection ||
|
window.mozRTCPeerConnection ||
|
||||||
window.webkitRTCPeerConnection;
|
window.webkitRTCPeerConnection
|
||||||
|
|
||||||
const pc = new PeerConnection({ iceServers: [turnConfig] });
|
const pc = new PeerConnection({ iceServers: [turnConfig] })
|
||||||
|
|
||||||
// create a bogus data channel
|
// create a bogus data channel
|
||||||
pc.createDataChannel('');
|
pc.createDataChannel('')
|
||||||
pc.createOffer(function(sdp) {
|
pc.createOffer(function (sdp) {
|
||||||
// sometimes sdp contains the ice candidates...
|
// sometimes sdp contains the ice candidates...
|
||||||
if (sdp.sdp.indexOf('typ relay') > -1) {
|
if (sdp.sdp.indexOf('typ relay') > -1) {
|
||||||
promiseResolved = true;
|
promiseResolved = true
|
||||||
resolve(true);
|
resolve(true)
|
||||||
}
|
}
|
||||||
pc.setLocalDescription(sdp, noop, noop);
|
pc.setLocalDescription(sdp, noop, noop)
|
||||||
}, noop);
|
}, noop)
|
||||||
|
|
||||||
pc.onicecandidate = function(ice) {
|
pc.onicecandidate = function (ice) {
|
||||||
if (promiseResolved ||
|
if (promiseResolved ||
|
||||||
!ice ||
|
!ice ||
|
||||||
!ice.candidate ||
|
!ice.candidate ||
|
||||||
!ice.candidate.candidate ||
|
!ice.candidate.candidate ||
|
||||||
!(ice.candidate.candidate.indexOf('typ relay') > -1)) {
|
!(ice.candidate.candidate.indexOf('typ relay') > -1)) {
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
promiseResolved = true;
|
promiseResolved = true
|
||||||
resolve(true);
|
resolve(true)
|
||||||
};
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
checkTURNServer(iceServers[0], 10000)
|
checkTURNServer(iceServers[0], 10000)
|
||||||
.then(console.log.bind(console))
|
.then(console.log.bind(console))
|
||||||
.catch(console.error.bind(console));
|
.catch(console.error.bind(console))
|
||||||
|
|||||||
@ -1,5 +0,0 @@
|
|||||||
const Dispatcher = require('flux').Dispatcher;
|
|
||||||
|
|
||||||
const dispatcher = new Dispatcher();
|
|
||||||
|
|
||||||
module.exports = dispatcher;
|
|
||||||
@ -1,3 +0,0 @@
|
|||||||
module.exports = JSON.parse(
|
|
||||||
window.document.getElementById('iceServers').value
|
|
||||||
);
|
|
||||||
@ -1,26 +1,16 @@
|
|||||||
'use strict';
|
'use strict'
|
||||||
const App = require('./components/app.js');
|
import App from './containers/App.js'
|
||||||
const React = require('react');
|
import React from 'react'
|
||||||
const ReactDom = require('react-dom');
|
import ReactDOM from 'react-dom'
|
||||||
const activeStore = require('./store/activeStore.js');
|
import store from './store.js'
|
||||||
const alertStore = require('./store/alertStore.js');
|
import { Provider } from 'react-redux'
|
||||||
const call = require('./call.js');
|
import { play } from './window.js'
|
||||||
const debug = require('debug')('peer-calls:index');
|
|
||||||
const notificationsStore = require('./store/notificationsStore.js');
|
|
||||||
const play = require('./browser/video.js').play;
|
|
||||||
const streamStore = require('./store/streamStore.js');
|
|
||||||
|
|
||||||
function render() {
|
const component = (
|
||||||
debug('rendering');
|
<Provider store={store}>
|
||||||
ReactDom.render(<App />, document.querySelector('#container'));
|
<App />
|
||||||
play();
|
</Provider>
|
||||||
}
|
)
|
||||||
|
|
||||||
activeStore.addListener(render);
|
ReactDOM.render(component, document.getElementById('container'))
|
||||||
alertStore.addListener(render);
|
play()
|
||||||
notificationsStore.addListener(render);
|
|
||||||
streamStore.addListener(render);
|
|
||||||
|
|
||||||
render();
|
|
||||||
|
|
||||||
call.init();
|
|
||||||
|
|||||||
10
src/client/middlewares.js
Normal file
10
src/client/middlewares.js
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
import logger from 'redux-logger'
|
||||||
|
import promiseMiddleware from 'redux-promise-middleware'
|
||||||
|
import thunk from 'redux-thunk'
|
||||||
|
|
||||||
|
export const middlewares = [thunk, promiseMiddleware()]
|
||||||
|
export const create = log => {
|
||||||
|
const m = middlewares.slice()
|
||||||
|
log && m.push(logger)
|
||||||
|
return m
|
||||||
|
}
|
||||||
@ -1,8 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
const Peer = require('simple-peer');
|
|
||||||
|
|
||||||
function init(opts) {
|
|
||||||
return Peer(opts);
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { init };
|
|
||||||
@ -1,176 +0,0 @@
|
|||||||
jest.unmock('../handshake.js');
|
|
||||||
jest.unmock('../peers.js');
|
|
||||||
jest.unmock('events');
|
|
||||||
jest.unmock('underscore');
|
|
||||||
|
|
||||||
const EventEmitter = require('events').EventEmitter;
|
|
||||||
const Peer = require('../Peer.js');
|
|
||||||
const dispatcher = require('../../dispatcher/dispatcher.js');
|
|
||||||
const handshake = require('../handshake.js');
|
|
||||||
const peers = require('../peers.js');
|
|
||||||
|
|
||||||
describe('handshake', () => {
|
|
||||||
|
|
||||||
let socket, peerInstances;
|
|
||||||
beforeEach(() => {
|
|
||||||
socket = new EventEmitter();
|
|
||||||
socket.id = 'a';
|
|
||||||
peerInstances = [];
|
|
||||||
|
|
||||||
Peer.init = jest.genMockFunction().mockImplementation(() => {
|
|
||||||
let peer = new EventEmitter();
|
|
||||||
peer.destroy = jest.genMockFunction();
|
|
||||||
peer.signal = jest.genMockFunction();
|
|
||||||
peerInstances.push(peer);
|
|
||||||
return peer;
|
|
||||||
});
|
|
||||||
|
|
||||||
dispatcher.dispatch.mockClear();
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => peers.clear());
|
|
||||||
|
|
||||||
describe('socket events', () => {
|
|
||||||
|
|
||||||
describe('users', () => {
|
|
||||||
|
|
||||||
it('add a peer for each new user and destroy peers for missing', () => {
|
|
||||||
handshake.init(socket, 'bla');
|
|
||||||
|
|
||||||
// given
|
|
||||||
let payload = {
|
|
||||||
users: [{ id: 'a'}, { id: 'b' }],
|
|
||||||
initiator: 'a',
|
|
||||||
};
|
|
||||||
socket.emit('users', payload);
|
|
||||||
expect(peerInstances.length).toBe(1);
|
|
||||||
|
|
||||||
// when
|
|
||||||
payload = {
|
|
||||||
users: [{ id: 'a'}, { id: 'c' }],
|
|
||||||
initiator: 'c',
|
|
||||||
};
|
|
||||||
socket.emit('users', payload);
|
|
||||||
|
|
||||||
// then
|
|
||||||
expect(peerInstances.length).toBe(2);
|
|
||||||
expect(peerInstances[0].destroy.mock.calls.length).toBe(1);
|
|
||||||
expect(peerInstances[1].destroy.mock.calls.length).toBe(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('signal', () => {
|
|
||||||
let data;
|
|
||||||
beforeEach(() => {
|
|
||||||
data = {};
|
|
||||||
handshake.init(socket, 'bla');
|
|
||||||
socket.emit('users', {
|
|
||||||
initiator: 'a',
|
|
||||||
users: [{ id: 'a' }, { id: 'b' }]
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should forward signal to peer', () => {
|
|
||||||
socket.emit('signal', {
|
|
||||||
userId: 'b',
|
|
||||||
data
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(peerInstances.length).toBe(1);
|
|
||||||
expect(peerInstances[0].signal.mock.calls.length).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does nothing if no peer', () => {
|
|
||||||
socket.emit('signal', {
|
|
||||||
userId: 'a',
|
|
||||||
data
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(peerInstances.length).toBe(1);
|
|
||||||
expect(peerInstances[0].signal.mock.calls.length).toBe(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('peer events', () => {
|
|
||||||
|
|
||||||
let peer;
|
|
||||||
beforeEach(() => {
|
|
||||||
let ready = false;
|
|
||||||
socket.once('ready', () => { ready = true; });
|
|
||||||
|
|
||||||
handshake.init(socket, 'bla');
|
|
||||||
|
|
||||||
socket.emit('users', {
|
|
||||||
initiator: 'a',
|
|
||||||
users: [{ id: 'a' }, { id: 'b'}]
|
|
||||||
});
|
|
||||||
expect(peerInstances.length).toBe(1);
|
|
||||||
peer = peerInstances[0];
|
|
||||||
|
|
||||||
expect(ready).toBeDefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('error', () => {
|
|
||||||
|
|
||||||
it('destroys peer', () => {
|
|
||||||
peer.emit('error', new Error('bla'));
|
|
||||||
expect(peer.destroy.mock.calls.length).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('signal', () => {
|
|
||||||
|
|
||||||
it('emits socket signal with user id', done => {
|
|
||||||
let signal = { bla: 'bla' };
|
|
||||||
|
|
||||||
socket.once('signal', payload => {
|
|
||||||
expect(payload.userId).toEqual('b');
|
|
||||||
expect(payload.signal).toBe(signal);
|
|
||||||
done();
|
|
||||||
});
|
|
||||||
|
|
||||||
peer.emit('signal', signal);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('stream', () => {
|
|
||||||
|
|
||||||
it('adds a stream to streamStore', () => {
|
|
||||||
expect(dispatcher.dispatch.mock.calls.length).toBe(0);
|
|
||||||
|
|
||||||
let stream = {};
|
|
||||||
peer.emit('stream', stream);
|
|
||||||
|
|
||||||
expect(dispatcher.dispatch.mock.calls.length).toBe(1);
|
|
||||||
expect(dispatcher.dispatch.mock.calls).toEqual([[{
|
|
||||||
type: 'add-stream',
|
|
||||||
userId: 'b',
|
|
||||||
stream
|
|
||||||
}]]);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('close', () => {
|
|
||||||
|
|
||||||
it('removes stream from streamStore', () => {
|
|
||||||
peer.emit('close');
|
|
||||||
|
|
||||||
expect(dispatcher.dispatch.mock.calls.length).toBe(1);
|
|
||||||
expect(dispatcher.dispatch.mock.calls).toEqual([[{
|
|
||||||
type: 'remove-stream',
|
|
||||||
userId: 'b'
|
|
||||||
}]]);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
@ -1,165 +0,0 @@
|
|||||||
jest.unmock('../peers.js');
|
|
||||||
|
|
||||||
const EventEmitter = require('events').EventEmitter;
|
|
||||||
const Peer = require('../Peer.js');
|
|
||||||
const dispatcher = require('../../dispatcher/dispatcher.js');
|
|
||||||
const notify = require('../../action/notify.js');
|
|
||||||
const peers = require('../peers.js');
|
|
||||||
|
|
||||||
describe('peers', () => {
|
|
||||||
|
|
||||||
function createSocket() {
|
|
||||||
let socket = new EventEmitter();
|
|
||||||
socket.id = 'user1';
|
|
||||||
return socket;
|
|
||||||
}
|
|
||||||
|
|
||||||
let socket, stream, peerInstances, user;
|
|
||||||
beforeEach(() => {
|
|
||||||
dispatcher.dispatch.mockClear();
|
|
||||||
notify.warn.mockClear();
|
|
||||||
|
|
||||||
user = { id: 'user2' };
|
|
||||||
socket = createSocket();
|
|
||||||
peerInstances = [];
|
|
||||||
stream = { stream: true };
|
|
||||||
|
|
||||||
Peer.init = jest.genMockFunction().mockImplementation(() => {
|
|
||||||
let peer = new EventEmitter();
|
|
||||||
peer.destroy = jest.genMockFunction();
|
|
||||||
peer.signal = jest.genMockFunction();
|
|
||||||
peerInstances.push(peer);
|
|
||||||
return peer;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => peers.clear());
|
|
||||||
|
|
||||||
describe('create', () => {
|
|
||||||
|
|
||||||
it('creates a new peer', () => {
|
|
||||||
peers.create({ socket, user, initiator: 'user2', stream });
|
|
||||||
|
|
||||||
expect(notify.warn.mock.calls).toEqual([[ 'Connecting to peer...' ]]);
|
|
||||||
|
|
||||||
expect(peerInstances.length).toBe(1);
|
|
||||||
expect(Peer.init.mock.calls.length).toBe(1);
|
|
||||||
expect(Peer.init.mock.calls[0][0].initiator).toBe(false);
|
|
||||||
expect(Peer.init.mock.calls[0][0].stream).toBe(stream);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('sets initiator correctly', () => {
|
|
||||||
peers.create({ socket, user, initiator: 'user1', stream });
|
|
||||||
|
|
||||||
expect(peerInstances.length).toBe(1);
|
|
||||||
expect(Peer.init.mock.calls.length).toBe(1);
|
|
||||||
expect(Peer.init.mock.calls[0][0].initiator).toBe(true);
|
|
||||||
expect(Peer.init.mock.calls[0][0].stream).toBe(stream);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('destroys old peer before creating new one', () => {
|
|
||||||
peers.create({ socket, user, initiator: 'user2', stream });
|
|
||||||
peers.create({ socket, user, initiator: 'user2', stream });
|
|
||||||
|
|
||||||
expect(peerInstances.length).toBe(2);
|
|
||||||
expect(Peer.init.mock.calls.length).toBe(2);
|
|
||||||
expect(peerInstances[0].destroy.mock.calls.length).toBe(1);
|
|
||||||
expect(peerInstances[1].destroy.mock.calls.length).toBe(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('events', () => {
|
|
||||||
|
|
||||||
let peer;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
peers.create({ socket, user, initiator: 'user1', stream });
|
|
||||||
notify.warn.mockClear();
|
|
||||||
peer = peerInstances[0];
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('connect', () => {
|
|
||||||
|
|
||||||
beforeEach(() => peer.emit('connect'));
|
|
||||||
|
|
||||||
it('sends a notification', () => {
|
|
||||||
expect(notify.warn.mock.calls).toEqual([[
|
|
||||||
'Peer connection established'
|
|
||||||
]]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('dispatches "play" action', () => {
|
|
||||||
expect(dispatcher.dispatch.mock.calls).toEqual([[{ type: 'play' }]]);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('get', () => {
|
|
||||||
|
|
||||||
it('returns undefined when not found', () => {
|
|
||||||
expect(peers.get(user.id)).not.toBeDefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns Peer instance when found', () => {
|
|
||||||
peers.create({ socket, user, initiator: 'user2', stream });
|
|
||||||
|
|
||||||
expect(peers.get(user.id)).toBe(peerInstances[0]);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('getIds', () => {
|
|
||||||
|
|
||||||
it('returns ids of all peers', () => {
|
|
||||||
peers.create({
|
|
||||||
socket, user: {id: 'user2' }, initiator: 'user2', stream
|
|
||||||
});
|
|
||||||
peers.create({
|
|
||||||
socket, user: {id: 'user3' }, initiator: 'user3', stream
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(peers.getIds()).toEqual([ 'user2', 'user3' ]);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('destroy', () => {
|
|
||||||
|
|
||||||
it('destroys a peer and removes it', () => {
|
|
||||||
peers.create({ socket, user, initiator: 'user2', stream });
|
|
||||||
|
|
||||||
peers.destroy(user.id);
|
|
||||||
|
|
||||||
expect(peerInstances[0].destroy.mock.calls.length).toEqual(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws no error when peer missing', () => {
|
|
||||||
peers.destroy('bla123');
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('clear', () => {
|
|
||||||
|
|
||||||
it('destroys all peers and removes them', () => {
|
|
||||||
peers.create({
|
|
||||||
socket, user: {id: 'user2' }, initiator: 'user2', stream
|
|
||||||
});
|
|
||||||
peers.create({
|
|
||||||
socket, user: {id: 'user3' }, initiator: 'user3', stream
|
|
||||||
});
|
|
||||||
|
|
||||||
peers.clear();
|
|
||||||
|
|
||||||
expect(peerInstances[0].destroy.mock.calls.length).toEqual(1);
|
|
||||||
expect(peerInstances[1].destroy.mock.calls.length).toEqual(1);
|
|
||||||
|
|
||||||
expect(peers.getIds()).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
@ -1,43 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
const _ = require('underscore');
|
|
||||||
const debug = require('debug')('peer-calls:peer');
|
|
||||||
const notify = require('../action/notify.js');
|
|
||||||
const peers = require('./peers.js');
|
|
||||||
|
|
||||||
function init(socket, roomName, stream) {
|
|
||||||
|
|
||||||
function createPeer(user, initiator) {
|
|
||||||
return peers.create({ socket, user, initiator, stream });
|
|
||||||
}
|
|
||||||
|
|
||||||
socket.on('signal', payload => {
|
|
||||||
let peer = peers.get(payload.userId);
|
|
||||||
let signal = payload.signal;
|
|
||||||
// debug('socket signal, userId: %s, signal: %o', payload.userId, signal);
|
|
||||||
|
|
||||||
if (!peer) return debug('user: %s, no peer found', payload.userId);
|
|
||||||
peer.signal(signal);
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on('users', payload => {
|
|
||||||
let { initiator, users } = payload;
|
|
||||||
debug('socket users: %o', users);
|
|
||||||
notify.info('Connected users: {0}', users.length);
|
|
||||||
|
|
||||||
users
|
|
||||||
.filter(user => !peers.get(user.id) && user.id !== socket.id)
|
|
||||||
.forEach(user => createPeer(user, initiator));
|
|
||||||
|
|
||||||
let newUsersMap = _.indexBy(users, 'id');
|
|
||||||
peers.getIds()
|
|
||||||
.filter(id => !newUsersMap[id])
|
|
||||||
.forEach(peers.destroy);
|
|
||||||
});
|
|
||||||
|
|
||||||
debug('socket.id: %s', socket.id);
|
|
||||||
debug('emit ready for room: %s', roomName);
|
|
||||||
notify.info('Ready for connections');
|
|
||||||
socket.emit('ready', roomName);
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { init };
|
|
||||||
@ -1,107 +0,0 @@
|
|||||||
const _ = require('underscore');
|
|
||||||
const Peer = require('./Peer.js');
|
|
||||||
const debug = require('debug')('peer-calls:peer');
|
|
||||||
const dispatcher = require('../dispatcher/dispatcher.js');
|
|
||||||
const iceServers = require('../iceServers.js');
|
|
||||||
const notify = require('../action/notify.js');
|
|
||||||
|
|
||||||
let peers = {};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {Socket} socket
|
|
||||||
* @param {User} user
|
|
||||||
* @param {String} user.id
|
|
||||||
* @param {Boolean} [initiator=false]
|
|
||||||
* @param {MediaStream} [stream]
|
|
||||||
*/
|
|
||||||
function create({ socket, user, initiator, stream }) {
|
|
||||||
debug('create peer: %s, stream:', user.id, stream);
|
|
||||||
notify.warn('Connecting to peer...');
|
|
||||||
|
|
||||||
if (peers[user.id]) {
|
|
||||||
notify.info('Cleaning up old connection...');
|
|
||||||
destroy(user.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
let peer = peers[user.id] = Peer.init({
|
|
||||||
initiator: socket.id === initiator,
|
|
||||||
stream,
|
|
||||||
config: { iceServers }
|
|
||||||
});
|
|
||||||
|
|
||||||
peer.once('error', err => {
|
|
||||||
debug('peer: %s, error %s', user.id, err.stack);
|
|
||||||
notify.error('A peer connection error occurred');
|
|
||||||
destroy(user.id);
|
|
||||||
});
|
|
||||||
|
|
||||||
peer.on('signal', signal => {
|
|
||||||
debug('peer: %s, signal: %o', user.id, signal);
|
|
||||||
|
|
||||||
let payload = { userId: user.id, signal };
|
|
||||||
socket.emit('signal', payload);
|
|
||||||
});
|
|
||||||
|
|
||||||
peer.once('connect', () => {
|
|
||||||
debug('peer: %s, connect', user.id);
|
|
||||||
notify.warn('Peer connection established');
|
|
||||||
dispatcher.dispatch({ type: 'play' });
|
|
||||||
});
|
|
||||||
|
|
||||||
peer.on('stream', stream => {
|
|
||||||
debug('peer: %s, stream', user.id);
|
|
||||||
dispatcher.dispatch({
|
|
||||||
type: 'add-stream',
|
|
||||||
userId: user.id,
|
|
||||||
stream
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
peer.on('data', object => {
|
|
||||||
object = JSON.parse(new window.TextDecoder('utf-8').decode(object));
|
|
||||||
debug('peer: %s, message: %o', user.id, object);
|
|
||||||
notify.info('' + user.id + ': ' + object.message);
|
|
||||||
});
|
|
||||||
|
|
||||||
peer.once('close', () => {
|
|
||||||
debug('peer: %s, close', user.id);
|
|
||||||
notify.error('Peer connection closed');
|
|
||||||
dispatcher.dispatch({
|
|
||||||
type: 'remove-stream',
|
|
||||||
userId: user.id
|
|
||||||
});
|
|
||||||
|
|
||||||
// make sure some other peer with different id didn't take place between
|
|
||||||
// calling `destroy()` and `close` event
|
|
||||||
if (peers[user.id] === peer) delete peers[user.id];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function get(userId) {
|
|
||||||
return peers[userId];
|
|
||||||
}
|
|
||||||
|
|
||||||
function getIds() {
|
|
||||||
return _.map(peers, (peer, id) => id);
|
|
||||||
}
|
|
||||||
|
|
||||||
function clear() {
|
|
||||||
debug('clear');
|
|
||||||
_.each(peers, (_, userId) => destroy(userId));
|
|
||||||
peers = {};
|
|
||||||
}
|
|
||||||
|
|
||||||
function destroy(userId) {
|
|
||||||
debug('destroy peer: %s', userId);
|
|
||||||
let peer = peers[userId];
|
|
||||||
if (!peer) return debug('peer: %s peer not found', userId);
|
|
||||||
peer.destroy();
|
|
||||||
delete peers[userId];
|
|
||||||
}
|
|
||||||
|
|
||||||
function message(message) {
|
|
||||||
message = JSON.stringify({ message });
|
|
||||||
_.each(peers, peer => peer.send(message));
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { create, get, getIds, destroy, clear, message };
|
|
||||||
28
src/client/reducers/__tests__/active-test.js
Normal file
28
src/client/reducers/__tests__/active-test.js
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
import * as StreamActions from '../../actions/StreamActions.js'
|
||||||
|
import active from '../active.js'
|
||||||
|
|
||||||
|
describe('reducers/active', () => {
|
||||||
|
|
||||||
|
describe('setActive', () => {
|
||||||
|
it('sets active to userId', () => {
|
||||||
|
const userId = 'test'
|
||||||
|
let state = active()
|
||||||
|
state = active(state, StreamActions.setActive(userId))
|
||||||
|
expect(state).toBe(userId)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('toggleActive', () => {
|
||||||
|
it('sets active to userId', () => {
|
||||||
|
const userId = 'test'
|
||||||
|
let state = active()
|
||||||
|
state = active(state, StreamActions.toggleActive(userId))
|
||||||
|
expect(state).toBe(userId)
|
||||||
|
state = active(state, StreamActions.toggleActive(userId))
|
||||||
|
expect(state).toBe(null)
|
||||||
|
state = active(state, StreamActions.toggleActive(userId))
|
||||||
|
expect(state).toBe(userId)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
101
src/client/reducers/__tests__/alerts-test.js
Normal file
101
src/client/reducers/__tests__/alerts-test.js
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
import * as NotifyActions from '../../actions/NotifyActions.js'
|
||||||
|
import _ from 'underscore'
|
||||||
|
import { applyMiddleware, createStore } from 'redux'
|
||||||
|
import { create } from '../../middlewares.js'
|
||||||
|
import reducers from '../index.js'
|
||||||
|
|
||||||
|
jest.useFakeTimers()
|
||||||
|
|
||||||
|
describe('reducers/alerts', () => {
|
||||||
|
|
||||||
|
let store
|
||||||
|
beforeEach(() => {
|
||||||
|
store = createStore(
|
||||||
|
reducers,
|
||||||
|
applyMiddleware.apply(null, create())
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('clearAlert', () => {
|
||||||
|
|
||||||
|
const actions = {
|
||||||
|
true: 'Dismiss',
|
||||||
|
false: ''
|
||||||
|
}
|
||||||
|
;[true, false].forEach(dismissable => {
|
||||||
|
beforeEach(() => {
|
||||||
|
store.dispatch(NotifyActions.clearAlerts())
|
||||||
|
})
|
||||||
|
it('adds alert to store', () => {
|
||||||
|
store.dispatch(NotifyActions.alert('test', dismissable))
|
||||||
|
expect(store.getState().alerts).toEqual([{
|
||||||
|
action: actions[dismissable],
|
||||||
|
dismissable,
|
||||||
|
message: 'test',
|
||||||
|
type: 'warning'
|
||||||
|
}])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('dismissAlert', () => {
|
||||||
|
|
||||||
|
it('removes an alert', () => {
|
||||||
|
store.dispatch(NotifyActions.alert('test', true))
|
||||||
|
expect(store.getState().alerts.length).toBe(1)
|
||||||
|
store.dispatch(NotifyActions.dismissAlert(store.getState().alerts[0]))
|
||||||
|
expect(store.getState().alerts.length).toBe(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not remove an alert when not found', () => {
|
||||||
|
store.dispatch(NotifyActions.alert('test', true))
|
||||||
|
expect(store.getState().alerts.length).toBe(1)
|
||||||
|
store.dispatch(NotifyActions.dismissAlert({}))
|
||||||
|
expect(store.getState().alerts.length).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
;['info', 'warning', 'error'].forEach(type => {
|
||||||
|
|
||||||
|
describe(type, () => {
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
store.dispatch(NotifyActions[type]('Hi {0}!', 'John'))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('adds a notification', () => {
|
||||||
|
expect(_.values(store.getState().notifications)).toEqual([{
|
||||||
|
id: jasmine.any(String),
|
||||||
|
message: 'Hi John!',
|
||||||
|
type
|
||||||
|
}])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('dismisses notification after a timeout', () => {
|
||||||
|
jest.runAllTimers()
|
||||||
|
expect(store.getState().notifications).toEqual({})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not fail when no arguments', () => {
|
||||||
|
store.dispatch(NotifyActions[type]())
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('clear', () => {
|
||||||
|
|
||||||
|
it('clears all alerts', () => {
|
||||||
|
store.dispatch(NotifyActions.info('Hi {0}!', 'John'))
|
||||||
|
store.dispatch(NotifyActions.warning('Hi {0}!', 'John'))
|
||||||
|
store.dispatch(NotifyActions.error('Hi {0}!', 'John'))
|
||||||
|
store.dispatch(NotifyActions.clear())
|
||||||
|
expect(store.getState().notifications).toEqual({})
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
44
src/client/reducers/__tests__/streams-test.js
Normal file
44
src/client/reducers/__tests__/streams-test.js
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
jest.mock('../../window.js')
|
||||||
|
|
||||||
|
import * as StreamActions from '../../actions/StreamActions.js'
|
||||||
|
import { applyMiddleware, createStore } from 'redux'
|
||||||
|
import { create } from '../../middlewares.js'
|
||||||
|
import reducers from '../index.js'
|
||||||
|
|
||||||
|
describe('reducers/alerts', () => {
|
||||||
|
|
||||||
|
class MediaStream {}
|
||||||
|
let store, stream, userId
|
||||||
|
beforeEach(() => {
|
||||||
|
store = createStore(
|
||||||
|
reducers,
|
||||||
|
applyMiddleware.apply(null, create())
|
||||||
|
)
|
||||||
|
userId = 'test id'
|
||||||
|
stream = new MediaStream()
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('defaultState', () => {
|
||||||
|
it('should have default state set', () => {
|
||||||
|
expect(store.getState().streams).toEqual({})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('addStream', () => {
|
||||||
|
it('adds a stream', () => {
|
||||||
|
store.dispatch(StreamActions.addStream({ userId, stream }))
|
||||||
|
expect(store.getState().streams).toEqual({
|
||||||
|
[userId]: jasmine.any(String)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('removeStream', () => {
|
||||||
|
it('removes a stream', () => {
|
||||||
|
store.dispatch(StreamActions.addStream({ userId, stream }))
|
||||||
|
store.dispatch(StreamActions.removeStream(userId))
|
||||||
|
expect(store.getState().streams).toEqual({})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
13
src/client/reducers/active.js
Normal file
13
src/client/reducers/active.js
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import * as constants from '../constants.js'
|
||||||
|
|
||||||
|
export default function active (state = null, action) {
|
||||||
|
switch (action && action.type) {
|
||||||
|
case constants.ACTIVE_SET:
|
||||||
|
case constants.STREAM_ADD:
|
||||||
|
return action.payload.userId
|
||||||
|
case constants.ACTIVE_TOGGLE:
|
||||||
|
return state === action.payload.userId ? null : action.payload.userId
|
||||||
|
default:
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
}
|
||||||
19
src/client/reducers/alerts.js
Normal file
19
src/client/reducers/alerts.js
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
import * as constants from '../constants.js'
|
||||||
|
import Immutable from 'seamless-immutable'
|
||||||
|
|
||||||
|
const defaultState = Immutable([])
|
||||||
|
|
||||||
|
export default function alerts (state = defaultState, action) {
|
||||||
|
switch (action && action.type) {
|
||||||
|
case constants.ALERT:
|
||||||
|
const alerts = state.asMutable()
|
||||||
|
alerts.push(action.payload)
|
||||||
|
return Immutable(alerts)
|
||||||
|
case constants.ALERT_DISMISS:
|
||||||
|
return state.filter(a => a !== action.payload)
|
||||||
|
case constants.ALERT_CLEAR:
|
||||||
|
return defaultState
|
||||||
|
default:
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
}
|
||||||
14
src/client/reducers/index.js
Normal file
14
src/client/reducers/index.js
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import active from './active.js'
|
||||||
|
import alerts from './alerts.js'
|
||||||
|
import notifications from './notifications.js'
|
||||||
|
import peers from './peers.js'
|
||||||
|
import streams from './streams.js'
|
||||||
|
import { combineReducers } from 'redux'
|
||||||
|
|
||||||
|
export default combineReducers({
|
||||||
|
active,
|
||||||
|
alerts,
|
||||||
|
notifications,
|
||||||
|
peers,
|
||||||
|
streams
|
||||||
|
})
|
||||||
19
src/client/reducers/notifications.js
Normal file
19
src/client/reducers/notifications.js
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
import * as constants from '../constants.js'
|
||||||
|
import Immutable from 'seamless-immutable'
|
||||||
|
|
||||||
|
const defaultState = Immutable({})
|
||||||
|
|
||||||
|
export default function notifications (state = defaultState, action) {
|
||||||
|
switch (action && action.type) {
|
||||||
|
case constants.NOTIFY:
|
||||||
|
return state.merge({
|
||||||
|
[action.payload.id]: action.payload
|
||||||
|
})
|
||||||
|
case constants.NOTIFY_DISMISS:
|
||||||
|
return state.without(action.payload.id)
|
||||||
|
case constants.NOTIFY_CLEAR:
|
||||||
|
return defaultState
|
||||||
|
default:
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
}
|
||||||
21
src/client/reducers/peers.js
Normal file
21
src/client/reducers/peers.js
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
import * as constants from '../constants.js'
|
||||||
|
import _ from 'underscore'
|
||||||
|
|
||||||
|
const defaultState = {}
|
||||||
|
|
||||||
|
export default function peers (state = defaultState, action) {
|
||||||
|
switch (action && action.type) {
|
||||||
|
case constants.PEER_ADD:
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
[action.payload.userId]: action.payload.peer
|
||||||
|
}
|
||||||
|
case constants.PEER_REMOVE:
|
||||||
|
return _.omit(state, [action.payload.userId])
|
||||||
|
case constants.PEERS_DESTROY:
|
||||||
|
_.each(state, peer => peer.destroy())
|
||||||
|
return defaultState
|
||||||
|
default:
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
}
|
||||||
25
src/client/reducers/streams.js
Normal file
25
src/client/reducers/streams.js
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import * as constants from '../constants.js'
|
||||||
|
import Immutable from 'seamless-immutable'
|
||||||
|
import { createObjectURL } from '../window.js'
|
||||||
|
|
||||||
|
const defaultState = Immutable({})
|
||||||
|
|
||||||
|
function addStream (state, action) {
|
||||||
|
const { userId, stream } = action.payload
|
||||||
|
return state.merge({
|
||||||
|
[userId]: createObjectURL(stream)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const removeStream = (state, action) => state.without(action.payload.userId)
|
||||||
|
|
||||||
|
export default function streams (state = defaultState, action) {
|
||||||
|
switch (action && action.type) {
|
||||||
|
case constants.STREAM_ADD:
|
||||||
|
return addStream(state, action)
|
||||||
|
case constants.STREAM_REMOVE:
|
||||||
|
return removeStream(state, action)
|
||||||
|
default:
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,5 +1,2 @@
|
|||||||
let SocketIOClient = require('socket.io-client');
|
import SocketIOClient from 'socket.io-client'
|
||||||
|
export default new SocketIOClient()
|
||||||
let socket = new SocketIOClient();
|
|
||||||
|
|
||||||
module.exports = socket;
|
|
||||||
|
|||||||
13
src/client/store.js
Normal file
13
src/client/store.js
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import { create } from './middlewares.js'
|
||||||
|
import reducers from './reducers'
|
||||||
|
import { applyMiddleware, createStore as _createStore } from 'redux'
|
||||||
|
export const middlewares = create(
|
||||||
|
window.localStorage && window.localStorage.log
|
||||||
|
)
|
||||||
|
|
||||||
|
export const createStore = () => _createStore(
|
||||||
|
reducers,
|
||||||
|
applyMiddleware.apply(null, middlewares)
|
||||||
|
)
|
||||||
|
|
||||||
|
export default createStore()
|
||||||
@ -1,34 +0,0 @@
|
|||||||
jest.unmock('../activeStore.js');
|
|
||||||
|
|
||||||
const dispatcher = require('../../dispatcher/dispatcher.js');
|
|
||||||
const activeStore = require('../activeStore.js');
|
|
||||||
|
|
||||||
describe('activeStore', () => {
|
|
||||||
|
|
||||||
let handleAction = dispatcher.register.mock.calls[0][0];
|
|
||||||
let onChange = jest.genMockFunction();
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
onChange.mockClear();
|
|
||||||
activeStore.addListener(onChange);
|
|
||||||
});
|
|
||||||
afterEach(() => activeStore.removeListener(onChange));
|
|
||||||
|
|
||||||
describe('mark-active', () => {
|
|
||||||
|
|
||||||
it('should mark id as active', () => {
|
|
||||||
expect(activeStore.getActive()).not.toBeDefined();
|
|
||||||
expect(activeStore.isActive('user1')).toBe(false);
|
|
||||||
expect(onChange.mock.calls.length).toBe(0);
|
|
||||||
|
|
||||||
handleAction({ type: 'mark-active', userId: 'user1' });
|
|
||||||
|
|
||||||
expect(activeStore.getActive()).toBe('user1');
|
|
||||||
expect(activeStore.isActive('user1')).toBe(true);
|
|
||||||
|
|
||||||
expect(onChange.mock.calls.length).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
@ -1,70 +0,0 @@
|
|||||||
jest.unmock('../alertStore.js');
|
|
||||||
|
|
||||||
const dispatcher = require('../../dispatcher/dispatcher.js');
|
|
||||||
const alertStore = require('../alertStore.js');
|
|
||||||
|
|
||||||
describe('alertStore', () => {
|
|
||||||
|
|
||||||
let handleAction, onChange;
|
|
||||||
beforeEach(() => {
|
|
||||||
handleAction = dispatcher.register.mock.calls[0][0];
|
|
||||||
handleAction({ type: 'alert-clear' });
|
|
||||||
|
|
||||||
onChange = jest.genMockFunction();
|
|
||||||
alertStore.addListener(onChange);
|
|
||||||
});
|
|
||||||
afterEach(() => {
|
|
||||||
alertStore.removeListener(onChange);
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('alert', () => {
|
|
||||||
|
|
||||||
it('should add alerts to end of queue and dispatch change', () => {
|
|
||||||
let alert1 = { message: 'example alert 1' };
|
|
||||||
let alert2 = { message: 'example alert 2' };
|
|
||||||
|
|
||||||
handleAction({ type: 'alert', alert: alert1 });
|
|
||||||
handleAction({ type: 'alert', alert: alert2 });
|
|
||||||
|
|
||||||
expect(onChange.mock.calls.length).toBe(2);
|
|
||||||
expect(alertStore.getAlerts()).toEqual([ alert1, alert2 ]);
|
|
||||||
expect(alertStore.getAlert()).toBe(alert1);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('alert-dismiss', () => {
|
|
||||||
|
|
||||||
it('should remove alert and dispatch change', () => {
|
|
||||||
let alert1 = { message: 'example alert 1' };
|
|
||||||
let alert2 = { message: 'example alert 2' };
|
|
||||||
|
|
||||||
handleAction({ type: 'alert', alert: alert1 });
|
|
||||||
handleAction({ type: 'alert', alert: alert2 });
|
|
||||||
handleAction({ type: 'alert-dismiss', alert: alert1 });
|
|
||||||
|
|
||||||
expect(onChange.mock.calls.length).toBe(3);
|
|
||||||
expect(alertStore.getAlerts()).toEqual([ alert2 ]);
|
|
||||||
expect(alertStore.getAlert()).toBe(alert2);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('alert-clear', () => {
|
|
||||||
|
|
||||||
it('should remove all alerts', () => {
|
|
||||||
let alert1 = { message: 'example alert 1' };
|
|
||||||
let alert2 = { message: 'example alert 2' };
|
|
||||||
|
|
||||||
handleAction({ type: 'alert', alert: alert1 });
|
|
||||||
handleAction({ type: 'alert', alert: alert2 });
|
|
||||||
handleAction({ type: 'alert-clear' });
|
|
||||||
|
|
||||||
expect(onChange.mock.calls.length).toBe(3);
|
|
||||||
expect(alertStore.getAlerts()).toEqual([]);
|
|
||||||
expect(alertStore.getAlert()).not.toBeDefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
@ -1,67 +0,0 @@
|
|||||||
jest.unmock('../notificationsStore.js');
|
|
||||||
|
|
||||||
const dispatcher = require('../../dispatcher/dispatcher.js');
|
|
||||||
const store = require('../notificationsStore.js');
|
|
||||||
|
|
||||||
describe('store', () => {
|
|
||||||
|
|
||||||
let handleAction, onChange;
|
|
||||||
beforeEach(() => {
|
|
||||||
dispatcher.dispatch.mockClear();
|
|
||||||
handleAction = dispatcher.register.mock.calls[0][0];
|
|
||||||
|
|
||||||
handleAction({ type: 'notify-clear' });
|
|
||||||
|
|
||||||
onChange = jest.genMockFunction();
|
|
||||||
store.addListener(onChange);
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('notify', () => {
|
|
||||||
|
|
||||||
it('should add notification and dispatch change', () => {
|
|
||||||
let notif1 = { message: 'example notif 1' };
|
|
||||||
let notif2 = { message: 'example notif 2' };
|
|
||||||
|
|
||||||
handleAction({ type: 'notify', notification: notif1 });
|
|
||||||
handleAction({ type: 'notify', notification: notif2 });
|
|
||||||
|
|
||||||
expect(onChange.mock.calls.length).toBe(2);
|
|
||||||
expect(store.getNotifications()).toEqual([ notif1, notif2 ]);
|
|
||||||
expect(store.getNotifications(1)).toEqual([ notif2 ]);
|
|
||||||
expect(store.getNotifications(3)).toEqual([ notif1, notif2 ]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should add timeout for autoremoval', () => {
|
|
||||||
let notif1 = { message: 'example notif 1' };
|
|
||||||
|
|
||||||
handleAction({ type: 'notify', notification: notif1 });
|
|
||||||
|
|
||||||
expect(onChange.mock.calls.length).toBe(1);
|
|
||||||
expect(store.getNotifications()).toEqual([ notif1 ]);
|
|
||||||
|
|
||||||
jest.runAllTimers();
|
|
||||||
|
|
||||||
expect(onChange.mock.calls.length).toBe(2);
|
|
||||||
expect(store.getNotifications()).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('notify-dismiss', () => {
|
|
||||||
|
|
||||||
it('should remove notif and dispatch change', () => {
|
|
||||||
let notif1 = { message: 'example notif 1' };
|
|
||||||
let notif2 = { message: 'example notif 2' };
|
|
||||||
|
|
||||||
handleAction({ type: 'notify', notification: notif1 });
|
|
||||||
handleAction({ type: 'notify', notification: notif2 });
|
|
||||||
handleAction({ type: 'notify-dismiss', notification: notif1 });
|
|
||||||
|
|
||||||
expect(onChange.mock.calls.length).toBe(3);
|
|
||||||
expect(store.getNotifications()).toEqual([ notif2 ]);
|
|
||||||
expect(store.getNotifications(2)).toEqual([ notif2 ]);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
@ -1,81 +0,0 @@
|
|||||||
jest.unmock('../streamStore.js');
|
|
||||||
|
|
||||||
const createObjectUrl = require('../../browser/createObjectURL.js');
|
|
||||||
const dispatcher = require('../../dispatcher/dispatcher.js');
|
|
||||||
const streamStore = require('../streamStore.js');
|
|
||||||
|
|
||||||
describe('streamStore', () => {
|
|
||||||
|
|
||||||
let handleAction = dispatcher.register.mock.calls[0][0];
|
|
||||||
let onChange = jest.genMockFunction();
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
onChange.mockClear();
|
|
||||||
streamStore.addListener(onChange);
|
|
||||||
});
|
|
||||||
afterEach(() => streamStore.removeListener(onChange));
|
|
||||||
|
|
||||||
describe('add-stream and remove-stream', () => {
|
|
||||||
|
|
||||||
it('should add a stream', () => {
|
|
||||||
let stream = {};
|
|
||||||
|
|
||||||
createObjectUrl.mockImplementation(str => {
|
|
||||||
if (str === stream) return 'url1';
|
|
||||||
});
|
|
||||||
|
|
||||||
handleAction({ type: 'add-stream', userId: 'user1', stream });
|
|
||||||
|
|
||||||
expect(streamStore.getStream('user1')).toEqual({
|
|
||||||
stream,
|
|
||||||
url: 'url1'
|
|
||||||
});
|
|
||||||
expect(onChange.mock.calls.length).toEqual(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should add a stream multiple times', () => {
|
|
||||||
let stream1 = {};
|
|
||||||
let stream2 = {};
|
|
||||||
|
|
||||||
createObjectUrl.mockImplementation(stream => {
|
|
||||||
if (stream === stream1) return 'url1';
|
|
||||||
if (stream === stream2) return 'url2';
|
|
||||||
});
|
|
||||||
|
|
||||||
handleAction({ type: 'add-stream', userId: 'user1', stream: stream1 });
|
|
||||||
handleAction({ type: 'add-stream', userId: 'user2', stream: stream2 });
|
|
||||||
|
|
||||||
expect(streamStore.getStream('user1')).toEqual({
|
|
||||||
stream: stream1,
|
|
||||||
url: 'url1'
|
|
||||||
});
|
|
||||||
expect(streamStore.getStream('user2')).toEqual({
|
|
||||||
stream: stream2,
|
|
||||||
url: 'url2'
|
|
||||||
});
|
|
||||||
expect(streamStore.getStreams()).toEqual({
|
|
||||||
user1: {
|
|
||||||
stream: stream1,
|
|
||||||
url: 'url1'
|
|
||||||
},
|
|
||||||
user2: {
|
|
||||||
stream: stream2,
|
|
||||||
url: 'url2'
|
|
||||||
}
|
|
||||||
});
|
|
||||||
expect(onChange.mock.calls.length).toEqual(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should remove a stream', () => {
|
|
||||||
let stream = {};
|
|
||||||
|
|
||||||
handleAction({ type: 'add-stream', userId: 'user1', stream });
|
|
||||||
handleAction({ type: 'remove-stream', userId: 'user1' });
|
|
||||||
|
|
||||||
expect(streamStore.getStream('user1')).not.toBeDefined();
|
|
||||||
expect(onChange.mock.calls.length).toEqual(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
@ -1,43 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
const EventEmitter = require('events');
|
|
||||||
const debug = require('debug')('peer-calls:activeStore');
|
|
||||||
const dispatcher = require('../dispatcher/dispatcher.js');
|
|
||||||
|
|
||||||
const emitter = new EventEmitter();
|
|
||||||
const addListener = cb => emitter.on('change', cb);
|
|
||||||
const removeListener = cb => emitter.removeListener('change', cb);
|
|
||||||
|
|
||||||
let active;
|
|
||||||
|
|
||||||
const handlers = {
|
|
||||||
'add-stream': ({ userId }) => {
|
|
||||||
active = userId;
|
|
||||||
},
|
|
||||||
'mark-active': ({ userId }) => {
|
|
||||||
debug('mark-active, userId: %s', userId);
|
|
||||||
active = userId;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const dispatcherIndex = dispatcher.register(action => {
|
|
||||||
let handle = handlers[action.type];
|
|
||||||
if (!handle) return;
|
|
||||||
handle(action);
|
|
||||||
emitter.emit('change');
|
|
||||||
});
|
|
||||||
|
|
||||||
function getActive() {
|
|
||||||
return active;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isActive(test) {
|
|
||||||
return active === test;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
dispatcherIndex,
|
|
||||||
addListener,
|
|
||||||
removeListener,
|
|
||||||
getActive,
|
|
||||||
isActive
|
|
||||||
};
|
|
||||||
@ -1,50 +0,0 @@
|
|||||||
const EventEmitter = require('events');
|
|
||||||
const debug = require('debug')('peer-calls:alertStore');
|
|
||||||
const dispatcher = require('../dispatcher/dispatcher.js');
|
|
||||||
|
|
||||||
const emitter = new EventEmitter();
|
|
||||||
const addListener = cb => emitter.on('change', cb);
|
|
||||||
const removeListener = cb => emitter.removeListener('change', cb);
|
|
||||||
|
|
||||||
let alerts = [];
|
|
||||||
|
|
||||||
const handlers = {
|
|
||||||
alert: ({ alert }) => {
|
|
||||||
debug('alert: %s', alert.message);
|
|
||||||
alerts.push(alert);
|
|
||||||
},
|
|
||||||
'alert-dismiss': ({ alert }) => {
|
|
||||||
debug('alert-dismiss: %s', alert.message);
|
|
||||||
let index = alerts.indexOf(alert);
|
|
||||||
debug('index: %s', index);
|
|
||||||
if (index < 0) return;
|
|
||||||
alerts.splice(index, 1);
|
|
||||||
},
|
|
||||||
'alert-clear': () => {
|
|
||||||
debug('alert-clear');
|
|
||||||
alerts = [];
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const dispatcherIndex = dispatcher.register(action => {
|
|
||||||
let handle = handlers[action.type];
|
|
||||||
if (!handle) return;
|
|
||||||
handle(action);
|
|
||||||
emitter.emit('change');
|
|
||||||
});
|
|
||||||
|
|
||||||
function getAlert() {
|
|
||||||
return alerts[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
function getAlerts() {
|
|
||||||
return alerts;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
dispatcherIndex,
|
|
||||||
addListener,
|
|
||||||
removeListener,
|
|
||||||
getAlert,
|
|
||||||
getAlerts,
|
|
||||||
};
|
|
||||||
@ -1,5 +0,0 @@
|
|||||||
function getCallId() {
|
|
||||||
return window.document.getElementById('callId').value;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { getCallId };
|
|
||||||
@ -1,65 +0,0 @@
|
|||||||
const EventEmitter = require('events');
|
|
||||||
const debug = require('debug')('peer-calls:alertStore');
|
|
||||||
const dispatcher = require('../dispatcher/dispatcher.js');
|
|
||||||
|
|
||||||
const emitter = new EventEmitter();
|
|
||||||
const addListener = cb => emitter.on('change', cb);
|
|
||||||
const removeListener = cb => emitter.removeListener('change', cb);
|
|
||||||
|
|
||||||
let index = 0;
|
|
||||||
let notifications = [];
|
|
||||||
|
|
||||||
function dismiss(notification) {
|
|
||||||
let index = notifications.indexOf(notification);
|
|
||||||
if (index < 0) return;
|
|
||||||
notifications.splice(index, 1);
|
|
||||||
clearTimeout(notification._timeout);
|
|
||||||
delete notification._timeout;
|
|
||||||
}
|
|
||||||
|
|
||||||
function emitChange() {
|
|
||||||
emitter.emit('change');
|
|
||||||
}
|
|
||||||
|
|
||||||
const handlers = {
|
|
||||||
notify: ({ notification }) => {
|
|
||||||
index++;
|
|
||||||
debug('notify', notification.message);
|
|
||||||
notification._id = index;
|
|
||||||
notifications.push(notification);
|
|
||||||
notification._timeout = setTimeout(() => {
|
|
||||||
debug('notify-dismiss timeout: %s', notification.message);
|
|
||||||
dismiss(notification);
|
|
||||||
emitChange();
|
|
||||||
}, 10000);
|
|
||||||
},
|
|
||||||
'notify-dismiss': ({ notification }) => {
|
|
||||||
debug('notify-dismiss: %s', notification.message);
|
|
||||||
dismiss(notification);
|
|
||||||
},
|
|
||||||
'notify-clear': () => {
|
|
||||||
debug('notify-clear');
|
|
||||||
notifications = [];
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const dispatcherIndex = dispatcher.register(action => {
|
|
||||||
let handle = handlers[action.type];
|
|
||||||
if (!handle) return;
|
|
||||||
handle(action);
|
|
||||||
emitChange();
|
|
||||||
});
|
|
||||||
|
|
||||||
function getNotifications(max) {
|
|
||||||
if (!max) max = notifications.length;
|
|
||||||
let start = notifications.length - max;
|
|
||||||
if (start < 0) start = 0;
|
|
||||||
return notifications.slice(start, notifications.length);
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
dispatcherIndex,
|
|
||||||
addListener,
|
|
||||||
removeListener,
|
|
||||||
getNotifications
|
|
||||||
};
|
|
||||||
@ -1,48 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
const EventEmitter = require('events');
|
|
||||||
const createObjectURL = require('../browser/createObjectURL');
|
|
||||||
const debug = require('debug')('peer-calls:streamStore');
|
|
||||||
const dispatcher = require('../dispatcher/dispatcher.js');
|
|
||||||
|
|
||||||
const emitter = new EventEmitter();
|
|
||||||
const addListener = cb => emitter.on('change', cb);
|
|
||||||
const removeListener = cb => emitter.removeListener('change', cb);
|
|
||||||
|
|
||||||
const streams = {};
|
|
||||||
|
|
||||||
const handlers = {
|
|
||||||
'add-stream': ({ userId, stream }) => {
|
|
||||||
debug('add-stream, user: %s', userId);
|
|
||||||
streams[userId] = {
|
|
||||||
stream,
|
|
||||||
url: createObjectURL(stream)
|
|
||||||
};
|
|
||||||
},
|
|
||||||
'remove-stream': ({ userId }) => {
|
|
||||||
debug('remove-stream, user: %s', userId);
|
|
||||||
delete streams[userId];
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const dispatcherIndex = dispatcher.register(action => {
|
|
||||||
let handle = handlers[action.type];
|
|
||||||
if (!handle) return;
|
|
||||||
handle(action);
|
|
||||||
emitter.emit('change');
|
|
||||||
});
|
|
||||||
|
|
||||||
function getStream(userId) {
|
|
||||||
return streams[userId];
|
|
||||||
}
|
|
||||||
|
|
||||||
function getStreams() {
|
|
||||||
return streams;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
dispatcherIndex,
|
|
||||||
addListener,
|
|
||||||
removeListener,
|
|
||||||
getStream,
|
|
||||||
getStreams
|
|
||||||
};
|
|
||||||
40
src/client/window.js
Normal file
40
src/client/window.js
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
import Promise from 'bluebird'
|
||||||
|
import _debug from 'debug'
|
||||||
|
|
||||||
|
const debug = _debug('peercalls')
|
||||||
|
|
||||||
|
export function getUserMedia (constraints) {
|
||||||
|
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
|
||||||
|
return navigator.mediaDevices.getUserMedia(constraints)
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia
|
||||||
|
if (!getMedia) reject(new Error('Browser unsupported'))
|
||||||
|
getMedia.call(navigator, constraints, resolve, reject)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export const createObjectURL = object => window.URL.createObjectURL(object)
|
||||||
|
|
||||||
|
export const navigator = window.navigator
|
||||||
|
|
||||||
|
export function play () {
|
||||||
|
let videos = window.document.querySelectorAll('video')
|
||||||
|
Array.prototype.forEach.call(videos, (video, index) => {
|
||||||
|
debug('playing video: %s', index)
|
||||||
|
try {
|
||||||
|
video.play()
|
||||||
|
} catch (e) {
|
||||||
|
debug('error playing video: %s', e.name)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export const valueOf = id => {
|
||||||
|
const el = window.document.getElementById(id)
|
||||||
|
return el && el.value
|
||||||
|
}
|
||||||
|
|
||||||
|
export const callId = valueOf('callId')
|
||||||
|
export const iceServers = JSON.parse(valueOf('iceServers'))
|
||||||
18
src/index.js
18
src/index.js
@ -1,17 +1,11 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
'use strict';
|
'use strict'
|
||||||
if (!process.env.DEBUG) {
|
if (!process.env.DEBUG) {
|
||||||
process.env.DEBUG = 'peer-calls:*';
|
process.env.DEBUG = 'peercalls'
|
||||||
}
|
}
|
||||||
|
|
||||||
const app = require('./server/app.js');
|
const app = require('./server/app.js')
|
||||||
const os = require('os');
|
const debug = require('debug')('peercalls')
|
||||||
|
|
||||||
let port = process.env.PORT || 3000;
|
let port = process.env.PORT || 3000
|
||||||
let ifaces = os.networkInterfaces();
|
app.listen(port, () => debug('Listening on: %s', port))
|
||||||
|
|
||||||
app.http.listen(port, function() {
|
|
||||||
Object.keys(ifaces).forEach(ifname =>
|
|
||||||
ifaces[ifname].forEach(iface =>
|
|
||||||
console.log('listening on', iface.address, 'and port', port)));
|
|
||||||
});
|
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 4.7 KiB After Width: | Height: | Size: 4.7 KiB |
@ -1,17 +1,17 @@
|
|||||||
@import "fonts.less";
|
@import "_fonts";
|
||||||
|
|
||||||
@font-sans-serif: "Helvetica Neue", Helvetica, Arial, sans-serif;
|
$font-sans-serif: "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||||
@font-monospace: Menlo, Monaco, Consolas, "Ubuntu Mono", monospace;
|
$font-monospace: Menlo, Monaco, Consolas, "Ubuntu Mono", monospace;
|
||||||
|
|
||||||
@color-bg: #086788;
|
$color-bg: #086788;
|
||||||
@color-fg: #07A0C3;
|
$color-fg: #07A0C3;
|
||||||
@color-btn: #FFF1D0;
|
$color-btn: #FFF1D0;
|
||||||
@icon-size: 48px;
|
$icon-size: 48px;
|
||||||
|
|
||||||
@color-primary: white;
|
$color-primary: white;
|
||||||
@color-info: #31EF40;
|
$color-info: #31EF40;
|
||||||
@color-warning: #F0C808;
|
$color-warning: #F0C808;
|
||||||
@color-error: #EE7600;
|
$color-error: #EE7600;
|
||||||
|
|
||||||
* {
|
* {
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
@ -24,10 +24,10 @@ html, body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
background-color: @color-bg;
|
background-color: $color-bg;
|
||||||
color: @color-fg;
|
color: $color-fg;
|
||||||
margin: 0 0;
|
margin: 0 0;
|
||||||
font-family: @font-sans-serif;
|
font-family: $font-sans-serif;
|
||||||
}
|
}
|
||||||
|
|
||||||
body.call {
|
body.call {
|
||||||
@ -61,34 +61,34 @@ body.call {
|
|||||||
|
|
||||||
p {
|
p {
|
||||||
margin: 50px 0;
|
margin: 50px 0;
|
||||||
color: @color-primary;
|
color: $color-primary;
|
||||||
}
|
}
|
||||||
|
|
||||||
.button(@color-fg, @color-bg) {
|
@mixin button($color-fg, $color-bg) {
|
||||||
background-color: @color-bg;
|
background-color: $color-bg;
|
||||||
border: none;
|
border: none;
|
||||||
border-bottom: 2px solid darken(@color-bg, 10%);
|
border-bottom: 2px solid darken($color-bg, 10%);
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
color: @color-fg;
|
color: $color-fg;
|
||||||
// font-size: 1.2rem;
|
// font-size: 1.2rem;
|
||||||
text-shadow: 0 0 0.35rem rgba(0, 0, 0, 0.6);
|
text-shadow: 0 0 0.35rem rgba(0, 0, 0, 0.6);
|
||||||
padding: 1rem 1rem;
|
padding: 1rem 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
input {
|
input {
|
||||||
font-family: @font-monospace;
|
font-family: $font-monospace;
|
||||||
.button(@color-primary, @color-warning);
|
@include button($color-primary, $color-warning);
|
||||||
font-size: 1.1rem;
|
font-size: 1.1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
input:hover {
|
input:hover {
|
||||||
.button(@color-primary, darken(@color-warning, 5%));
|
@include button($color-primary, darken($color-warning, 5%));
|
||||||
}
|
}
|
||||||
|
|
||||||
input:active {
|
input:active {
|
||||||
transform: translate(0px, 1px);
|
transform: translate(0px, 1px);
|
||||||
.button(@color-primary, darken(@color-warning, 10%));
|
@include button($color-primary, darken($color-warning, 10%));
|
||||||
}
|
}
|
||||||
|
|
||||||
input:active,
|
input:active,
|
||||||
@ -101,36 +101,36 @@ body.call {
|
|||||||
}
|
}
|
||||||
|
|
||||||
::-webkit-input-placeholder {
|
::-webkit-input-placeholder {
|
||||||
color: @color-fg;
|
color: $color-fg;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
:-moz-placeholder { /* Firefox 18- */
|
:-moz-placeholder { /* Firefox 18- */
|
||||||
color: @color-fg;
|
color: $color-fg;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
::-moz-placeholder { /* Firefox 19+ */
|
::-moz-placeholder { /* Firefox 19+ */
|
||||||
color: @color-fg;
|
color: $color-fg;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
:-ms-input-placeholder {
|
:-ms-input-placeholder {
|
||||||
color: @color-fg;
|
color: $color-fg;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.warning {
|
.warning {
|
||||||
color: @color-warning;
|
color: $color-warning;
|
||||||
}
|
}
|
||||||
|
|
||||||
.error {
|
.error {
|
||||||
color: @color-error;
|
color: $color-error;
|
||||||
}
|
}
|
||||||
|
|
||||||
.info {
|
.info {
|
||||||
color: @color-info;
|
color: $color-info;
|
||||||
}
|
}
|
||||||
|
|
||||||
.app {
|
.app {
|
||||||
@ -157,8 +157,8 @@ body.call {
|
|||||||
line-height: 1.4rem;
|
line-height: 1.4rem;
|
||||||
border: none;
|
border: none;
|
||||||
border-radius: 0.3rem;
|
border-radius: 0.3rem;
|
||||||
color: @color-info;
|
color: $color-info;
|
||||||
background-color: @color-fg;
|
background-color: $color-fg;
|
||||||
vertical-align: middle;
|
vertical-align: middle;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -169,7 +169,7 @@ body.call {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.notifications {
|
.notifications {
|
||||||
font-family: @font-monospace;
|
font-family: $font-monospace;
|
||||||
font-size: 10px;
|
font-size: 10px;
|
||||||
left: 1rem;
|
left: 1rem;
|
||||||
position: fixed;
|
position: fixed;
|
||||||
@ -179,17 +179,17 @@ body.call {
|
|||||||
z-index: 3;
|
z-index: 3;
|
||||||
|
|
||||||
.notification {
|
.notification {
|
||||||
color: @color-info;
|
color: $color-info;
|
||||||
padding: 0.25rem;
|
padding: 0.25rem;
|
||||||
background-color: rgba(0, 0, 0, 0.2);
|
background-color: rgba(0, 0, 0, 0.2);
|
||||||
}
|
}
|
||||||
|
|
||||||
.notification.error {
|
.notification.error {
|
||||||
color: @color-error;
|
color: $color-error;
|
||||||
}
|
}
|
||||||
|
|
||||||
.notification.warning {
|
.notification.warning {
|
||||||
color: @color-warning;
|
color: $color-warning;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -201,7 +201,7 @@ body.call {
|
|||||||
right: 0px;
|
right: 0px;
|
||||||
text-align: right;
|
text-align: right;
|
||||||
|
|
||||||
@video-size: 100px;
|
$video-size: 100px;
|
||||||
|
|
||||||
.video-container {
|
.video-container {
|
||||||
background-color: black;
|
background-color: black;
|
||||||
@ -209,7 +209,7 @@ body.call {
|
|||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
margin-right: 10px;
|
margin-right: 10px;
|
||||||
width: @video-size;
|
width: $video-size;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
z-index: 2;
|
z-index: 2;
|
||||||
|
|
||||||
@ -254,7 +254,7 @@ body.call {
|
|||||||
border: none;
|
border: none;
|
||||||
color: #ccc;
|
color: #ccc;
|
||||||
padding: 0.5rem;
|
padding: 0.5rem;
|
||||||
font-family: @font-monospace;
|
font-family: $font-monospace;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -277,4 +277,3 @@ body.call {
|
|||||||
opacity: 0.01;
|
opacity: 0.01;
|
||||||
transition: opacity 100ms ease-in;
|
transition: opacity 100ms ease-in;
|
||||||
}
|
}
|
||||||
|
|
||||||
62
src/server/__tests__/app-test.js
Normal file
62
src/server/__tests__/app-test.js
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
jest.mock('socket.io', () => {
|
||||||
|
const { EventEmitter } = require('events')
|
||||||
|
return jest.fn().mockReturnValue(new EventEmitter())
|
||||||
|
})
|
||||||
|
jest.mock('../socket.js')
|
||||||
|
|
||||||
|
const app = require('../app.js')
|
||||||
|
const handleSocket = require('../socket.js')
|
||||||
|
const io = require('socket.io')()
|
||||||
|
const request = require('supertest')
|
||||||
|
|
||||||
|
describe('server/app', () => {
|
||||||
|
|
||||||
|
describe('GET /', () => {
|
||||||
|
|
||||||
|
it('renders index', () => {
|
||||||
|
return request(app)
|
||||||
|
.get('/')
|
||||||
|
.expect(200)
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('GET /call', () => {
|
||||||
|
|
||||||
|
it('redirects to a new call', () => {
|
||||||
|
return request(app)
|
||||||
|
.get('/call')
|
||||||
|
.expect(302)
|
||||||
|
.expect('location', /^call\/[0-9a-f-]{36}$/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('redirects to relative url when slash', () => {
|
||||||
|
return request(app)
|
||||||
|
.get('/call/')
|
||||||
|
.expect(302)
|
||||||
|
.expect('location', /[0-9a-f-]{36}$/)
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('GET /call/<uuid>', () => {
|
||||||
|
|
||||||
|
it('renders call page', () => {
|
||||||
|
return request(app)
|
||||||
|
.get('/call/test')
|
||||||
|
.expect(200)
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('io:connection', () => {
|
||||||
|
|
||||||
|
it('calls handleSocket with socket', () => {
|
||||||
|
const socket = { hi: 'me socket' }
|
||||||
|
io.emit('connection', socket)
|
||||||
|
expect(handleSocket.mock.calls).toEqual([[ socket, io ]])
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
@ -1,27 +1,23 @@
|
|||||||
'use strict';
|
'use strict'
|
||||||
jest.unmock('../socket.js');
|
|
||||||
jest.unmock('events');
|
|
||||||
jest.unmock('underscore');
|
|
||||||
|
|
||||||
const EventEmitter = require('events').EventEmitter;
|
const EventEmitter = require('events').EventEmitter
|
||||||
const handleSocket = require('../socket.js');
|
const handleSocket = require('../socket.js')
|
||||||
|
|
||||||
describe('socket', () => {
|
describe('server/socket', () => {
|
||||||
|
let socket, io, rooms
|
||||||
let socket, io, rooms;
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
socket = new EventEmitter();
|
socket = new EventEmitter()
|
||||||
socket.id = 'socket0';
|
socket.id = 'socket0'
|
||||||
socket.join = jest.genMockFunction();
|
socket.join = jest.genMockFunction()
|
||||||
socket.leave = jest.genMockFunction();
|
socket.leave = jest.genMockFunction()
|
||||||
rooms = {};
|
rooms = {}
|
||||||
|
|
||||||
io = {};
|
io = {}
|
||||||
io.in = io.to = jest.genMockFunction().mockImplementation(room => {
|
io.in = io.to = jest.genMockFunction().mockImplementation(room => {
|
||||||
return (rooms[room] = rooms[room] || {
|
return (rooms[room] = rooms[room] || {
|
||||||
emit: jest.genMockFunction()
|
emit: jest.genMockFunction()
|
||||||
});
|
})
|
||||||
});
|
})
|
||||||
|
|
||||||
io.sockets = {
|
io.sockets = {
|
||||||
adapter: {
|
adapter: {
|
||||||
@ -41,73 +37,66 @@ describe('socket', () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
socket.leave = jest.genMockFunction();
|
socket.leave = jest.genMockFunction()
|
||||||
socket.join = jest.genMockFunction();
|
socket.join = jest.genMockFunction()
|
||||||
});
|
})
|
||||||
|
|
||||||
it('should be a function', () => {
|
it('should be a function', () => {
|
||||||
expect(typeof handleSocket).toBe('function');
|
expect(typeof handleSocket).toBe('function')
|
||||||
});
|
})
|
||||||
|
|
||||||
describe('socket events', () => {
|
describe('socket events', () => {
|
||||||
|
beforeEach(() => handleSocket(socket, io))
|
||||||
beforeEach(() => handleSocket(socket, io));
|
|
||||||
|
|
||||||
describe('signal', () => {
|
describe('signal', () => {
|
||||||
|
|
||||||
it('should broadcast signal to specific user', () => {
|
it('should broadcast signal to specific user', () => {
|
||||||
let signal = { type: 'signal' };
|
let signal = { type: 'signal' }
|
||||||
|
|
||||||
socket.emit('signal', { userId: 'a', signal });
|
socket.emit('signal', { userId: 'a', signal })
|
||||||
|
|
||||||
expect(io.to.mock.calls).toEqual([[ 'a' ]]);
|
expect(io.to.mock.calls).toEqual([[ 'a' ]])
|
||||||
expect(io.to('a').emit.mock.calls).toEqual([[
|
expect(io.to('a').emit.mock.calls).toEqual([[
|
||||||
'signal', {
|
'signal', {
|
||||||
userId: 'socket0',
|
userId: 'socket0',
|
||||||
signal
|
signal
|
||||||
}
|
}
|
||||||
]]);
|
]])
|
||||||
});
|
})
|
||||||
|
})
|
||||||
});
|
|
||||||
|
|
||||||
describe('ready', () => {
|
describe('ready', () => {
|
||||||
|
|
||||||
it('should call socket.leave if socket.room', () => {
|
it('should call socket.leave if socket.room', () => {
|
||||||
socket.room = 'room1';
|
socket.room = 'room1'
|
||||||
socket.emit('ready', 'room2');
|
socket.emit('ready', 'room2')
|
||||||
|
|
||||||
expect(socket.leave.mock.calls).toEqual([[ 'room1' ]]);
|
expect(socket.leave.mock.calls).toEqual([[ 'room1' ]])
|
||||||
expect(socket.join.mock.calls).toEqual([[ 'room2' ]]);
|
expect(socket.join.mock.calls).toEqual([[ 'room2' ]])
|
||||||
});
|
})
|
||||||
|
|
||||||
it('should call socket.join to room', () => {
|
it('should call socket.join to room', () => {
|
||||||
socket.emit('ready', 'room3');
|
socket.emit('ready', 'room3')
|
||||||
expect(socket.join.mock.calls).toEqual([[ 'room3' ]]);
|
expect(socket.join.mock.calls).toEqual([[ 'room3' ]])
|
||||||
});
|
})
|
||||||
|
|
||||||
it('should emit users', () => {
|
it('should emit users', () => {
|
||||||
socket.emit('ready', 'room3');
|
socket.emit('ready', 'room3')
|
||||||
|
|
||||||
expect(io.to.mock.calls).toEqual([[ 'room3' ]]);
|
expect(io.to.mock.calls).toEqual([[ 'room3' ]])
|
||||||
expect(io.to('room3').emit.mock.calls).toEqual([[
|
expect(io.to('room3').emit.mock.calls).toEqual([[
|
||||||
'users', {
|
'users', {
|
||||||
initiator: 'socket0',
|
initiator: 'socket0',
|
||||||
users: [{
|
users: [{
|
||||||
id: 'socket0',
|
id: 'socket0'
|
||||||
}, {
|
}, {
|
||||||
id: 'socket1',
|
id: 'socket1'
|
||||||
}, {
|
}, {
|
||||||
id: 'socket2'
|
id: 'socket2'
|
||||||
}]
|
}]
|
||||||
}
|
}
|
||||||
]]);
|
]])
|
||||||
});
|
})
|
||||||
|
})
|
||||||
});
|
})
|
||||||
|
})
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|||||||
@ -1,21 +1,16 @@
|
|||||||
jest.unmock('../turn.js');
|
const turn = require('../turn.js')
|
||||||
const turn = require('../turn.js');
|
|
||||||
|
|
||||||
describe('turn', () => {
|
|
||||||
|
|
||||||
|
describe('server/turn', () => {
|
||||||
describe('getCredentials', () => {
|
describe('getCredentials', () => {
|
||||||
|
|
||||||
it('returns username & credential', () => {
|
it('returns username & credential', () => {
|
||||||
const auth = turn.getCredentials('a', 'b');
|
const auth = turn.getCredentials('a', 'b')
|
||||||
expect(auth).toEqual(jasmine.any(Object));
|
expect(auth).toEqual(jasmine.any(Object))
|
||||||
expect(auth.username).toEqual(jasmine.any(String));
|
expect(auth.username).toEqual(jasmine.any(String))
|
||||||
expect(auth.credential).toEqual(jasmine.any(String));
|
expect(auth.credential).toEqual(jasmine.any(String))
|
||||||
});
|
})
|
||||||
|
})
|
||||||
});
|
|
||||||
|
|
||||||
describe('processServers', () => {
|
describe('processServers', () => {
|
||||||
|
|
||||||
const servers = [{
|
const servers = [{
|
||||||
url: 'server1',
|
url: 'server1',
|
||||||
urls: 'server1',
|
urls: 'server1',
|
||||||
@ -27,27 +22,24 @@ describe('turn', () => {
|
|||||||
username: 'c',
|
username: 'c',
|
||||||
secret: 'd',
|
secret: 'd',
|
||||||
auth: 'secret'
|
auth: 'secret'
|
||||||
}];
|
}]
|
||||||
|
|
||||||
it('does not expose secret', () => {
|
it('does not expose secret', () => {
|
||||||
const s = turn.processServers(servers);
|
const s = turn.processServers(servers)
|
||||||
expect(s.length).toBe(2);
|
expect(s.length).toBe(2)
|
||||||
expect(s[0]).toBe(servers[0]);
|
expect(s[0]).toBe(servers[0])
|
||||||
expect(s[1]).toEqual({
|
expect(s[1]).toEqual({
|
||||||
url: 'server2',
|
url: 'server2',
|
||||||
urls: 'server2',
|
urls: 'server2',
|
||||||
username: jasmine.any(String),
|
username: jasmine.any(String),
|
||||||
credential: jasmine.any(String)
|
credential: jasmine.any(String)
|
||||||
});
|
})
|
||||||
expect(s[1].username).toMatch(/^[0-9]+:c$/);
|
expect(s[1].username).toMatch(/^[0-9]+:c$/)
|
||||||
});
|
})
|
||||||
|
|
||||||
it('throws error when unknown auth type', () => {
|
it('throws error when unknown auth type', () => {
|
||||||
expect(() => turn.processServers([{ auth: 'bla' }]))
|
expect(() => turn.processServers([{ auth: 'bla' }]))
|
||||||
.toThrowError(/not implemented/);
|
.toThrowError(/not implemented/)
|
||||||
});
|
})
|
||||||
|
})
|
||||||
});
|
})
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|||||||
@ -1,45 +1,21 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
'use strict';
|
'use strict'
|
||||||
const express = require('express');
|
const express = require('express')
|
||||||
const handleSocket = require('./socket.js');
|
const handleSocket = require('./socket.js')
|
||||||
const os = require('os');
|
const path = require('path')
|
||||||
const path = require('path');
|
|
||||||
|
|
||||||
// Require in express.Router Middleware.
|
const app = express()
|
||||||
const callRouter = require('./routes/call');
|
const http = require('http').Server(app)
|
||||||
const siteRouter = require('./routes/index');
|
const io = require('socket.io')(http)
|
||||||
|
|
||||||
const app = express();
|
app.set('view engine', 'pug')
|
||||||
const http = require('http').Server(app);
|
app.set('views', path.join(__dirname, '../views'))
|
||||||
const io = require('socket.io')(http);
|
|
||||||
|
|
||||||
app.set('view engine', 'jade');
|
app.use('/res', express.static(path.join(__dirname, '../res')))
|
||||||
app.set('views', path.join(__dirname, '../views'));
|
app.use('/static', express.static(path.join(__dirname, '../../build')))
|
||||||
|
app.use('/call', require('./routes/call.js'))
|
||||||
|
app.use('/', require('./routes/index.js'))
|
||||||
|
|
||||||
app.use('/res', express.static(path.join(__dirname, '../res')));
|
io.on('connection', socket => handleSocket(socket, io))
|
||||||
|
|
||||||
if (__dirname.indexOf('/dist/') >= 0 || __dirname.indexOf('\\dist\\') >= 0) {
|
module.exports = http
|
||||||
app.use('/js', express.static(path.join(__dirname, '../client')));
|
|
||||||
app.use('/css', express.static(path.join(__dirname, '../css')));
|
|
||||||
} else {
|
|
||||||
const browserify = require('browserify-middleware');
|
|
||||||
const less = require('less-middleware');
|
|
||||||
browserify.settings({
|
|
||||||
transform: ['babelify']
|
|
||||||
});
|
|
||||||
|
|
||||||
const tempDir = path.join(os.tmpDir(), 'node-peer-calls-cache');
|
|
||||||
app.use('/js', browserify(path.join(__dirname, '../client')));
|
|
||||||
app.use('/css', less(path.join(__dirname, '../less'), { dest: tempDir}));
|
|
||||||
app.use('/css', express.static(tempDir));
|
|
||||||
app.use('/css/fonts', express.static(
|
|
||||||
path.join(__dirname, '../less/fonts')));
|
|
||||||
}
|
|
||||||
|
|
||||||
// using Express.Router Middleware
|
|
||||||
app.use('/call', callRouter);
|
|
||||||
app.use('/', siteRouter);
|
|
||||||
|
|
||||||
io.on('connection', socket => handleSocket(socket, io));
|
|
||||||
|
|
||||||
module.exports = { http, app };
|
|
||||||
|
|||||||
@ -1,24 +1,24 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
'use strict';
|
'use strict'
|
||||||
const config = require('config');
|
const config = require('config')
|
||||||
const turn = require('../turn.js');
|
const turn = require('../turn.js')
|
||||||
const router = require('express').Router();
|
const router = require('express').Router()
|
||||||
const uuid = require('uuid');
|
const uuid = require('uuid')
|
||||||
|
|
||||||
const cfgIceServers = config.get('iceServers');
|
const cfgIceServers = config.get('iceServers')
|
||||||
|
|
||||||
router.get('/', (req, res) => {
|
router.get('/', (req, res) => {
|
||||||
let prefix = 'call/';
|
let prefix = 'call/'
|
||||||
if (req.originalUrl.charAt(req.originalUrl.length - 1) === '/') prefix = '';
|
if (req.originalUrl.charAt(req.originalUrl.length - 1) === '/') prefix = ''
|
||||||
res.redirect(prefix + uuid.v4());
|
res.redirect(prefix + uuid.v4())
|
||||||
});
|
})
|
||||||
|
|
||||||
router.get('/:callId', (req, res) => {
|
router.get('/:callId', (req, res) => {
|
||||||
const iceServers = turn.processServers(cfgIceServers);
|
const iceServers = turn.processServers(cfgIceServers)
|
||||||
res.render('call', {
|
res.render('call', {
|
||||||
callId: encodeURIComponent(req.params.callId),
|
callId: encodeURIComponent(req.params.callId),
|
||||||
iceServers
|
iceServers
|
||||||
});
|
})
|
||||||
});
|
})
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
'use strict';
|
'use strict'
|
||||||
const router = require('express').Router();
|
const router = require('express').Router()
|
||||||
|
|
||||||
router.get('/', (req, res) => {
|
router.get('/', (req, res) => {
|
||||||
res.render('index');
|
res.render('index')
|
||||||
});
|
})
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router
|
||||||
|
|||||||
@ -1,36 +1,34 @@
|
|||||||
'use strict';
|
'use strict'
|
||||||
const debug = require('debug')('peer-calls:socket');
|
const debug = require('debug')('peer-calls:socket')
|
||||||
const _ = require('underscore');
|
const _ = require('underscore')
|
||||||
|
|
||||||
module.exports = function(socket, io) {
|
|
||||||
|
|
||||||
|
module.exports = function (socket, io) {
|
||||||
socket.on('signal', payload => {
|
socket.on('signal', payload => {
|
||||||
// debug('signal: %s, payload: %o', socket.id, payload);
|
// debug('signal: %s, payload: %o', socket.id, payload);
|
||||||
io.to(payload.userId).emit('signal', {
|
io.to(payload.userId).emit('signal', {
|
||||||
userId: socket.id,
|
userId: socket.id,
|
||||||
signal: payload.signal
|
signal: payload.signal
|
||||||
});
|
})
|
||||||
});
|
})
|
||||||
|
|
||||||
socket.on('ready', roomName => {
|
socket.on('ready', roomName => {
|
||||||
debug('ready: %s, room: %s', socket.id, roomName);
|
debug('ready: %s, room: %s', socket.id, roomName)
|
||||||
if (socket.room) socket.leave(socket.room);
|
if (socket.room) socket.leave(socket.room)
|
||||||
socket.room = roomName;
|
socket.room = roomName
|
||||||
socket.join(roomName);
|
socket.join(roomName)
|
||||||
socket.room = roomName;
|
socket.room = roomName
|
||||||
|
|
||||||
let users = getUsers(roomName);
|
let users = getUsers(roomName)
|
||||||
debug('ready: %s, room: %s, users: %o', socket.id, roomName, users);
|
debug('ready: %s, room: %s, users: %o', socket.id, roomName, users)
|
||||||
io.to(roomName).emit('users', {
|
io.to(roomName).emit('users', {
|
||||||
initiator: socket.id,
|
initiator: socket.id,
|
||||||
users
|
users
|
||||||
});
|
})
|
||||||
});
|
})
|
||||||
|
|
||||||
function getUsers(roomName) {
|
function getUsers (roomName) {
|
||||||
return _.map(io.sockets.adapter.rooms[roomName].sockets, (_, id) => {
|
return _.map(io.sockets.adapter.rooms[roomName].sockets, (_, id) => {
|
||||||
return { id };
|
return { id }
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
}
|
||||||
};
|
|
||||||
|
|||||||
@ -1,35 +1,35 @@
|
|||||||
'use strict';
|
'use strict'
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto')
|
||||||
|
|
||||||
function getCredentials(name, secret) {
|
function getCredentials (name, secret) {
|
||||||
// this credential would be valid for the next 24 hours
|
// this credential would be valid for the next 24 hours
|
||||||
const timestamp = parseInt(Date.now() / 1000, 10) + 24 * 3600;
|
const timestamp = parseInt(Date.now() / 1000, 10) + 24 * 3600
|
||||||
const username = [timestamp, name].join(':');
|
const username = [timestamp, name].join(':')
|
||||||
const hmac = crypto.createHmac('sha1', secret);
|
const hmac = crypto.createHmac('sha1', secret)
|
||||||
hmac.setEncoding('base64');
|
hmac.setEncoding('base64')
|
||||||
hmac.write(username);
|
hmac.write(username)
|
||||||
hmac.end();
|
hmac.end()
|
||||||
const credential = hmac.read();
|
const credential = hmac.read()
|
||||||
return { username, credential };
|
return { username, credential }
|
||||||
}
|
}
|
||||||
|
|
||||||
function processServers(iceServers) {
|
function processServers (iceServers) {
|
||||||
return iceServers.map(server => {
|
return iceServers.map(server => {
|
||||||
switch (server.auth) {
|
switch (server.auth) {
|
||||||
case undefined:
|
case undefined:
|
||||||
return server;
|
return server
|
||||||
case 'secret':
|
case 'secret':
|
||||||
const cred = getCredentials(server.username, server.secret);
|
const cred = getCredentials(server.username, server.secret)
|
||||||
return {
|
return {
|
||||||
url: server.url,
|
url: server.url,
|
||||||
urls: server.urls,
|
urls: server.urls,
|
||||||
username: cred.username,
|
username: cred.username,
|
||||||
credential: cred.credential
|
credential: cred.credential
|
||||||
};
|
}
|
||||||
default:
|
default:
|
||||||
throw new Error('Authentication type not implemented: ' + server.auth);
|
throw new Error('Authentication type not implemented: ' + server.auth)
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { getCredentials, processServers };
|
module.exports = { getCredentials, processServers }
|
||||||
|
|||||||
@ -8,12 +8,12 @@ html
|
|||||||
meta(name="apple-mobile-web-app-capable" content="yes")
|
meta(name="apple-mobile-web-app-capable" content="yes")
|
||||||
link(rel="apple-touch-icon" href="../res/icon.png")
|
link(rel="apple-touch-icon" href="../res/icon.png")
|
||||||
link(rel="icon" sizes="256x256" href="../res/icon.png")
|
link(rel="icon" sizes="256x256" href="../res/icon.png")
|
||||||
link(rel="stylesheet" type="text/css" href="../css/main.css")
|
link(rel="stylesheet" type="text/css" href="../static/style.css")
|
||||||
|
|
||||||
body.call
|
body.call
|
||||||
input#callId(type="hidden" value="#{callId}")
|
input#callId(type="hidden" value=callId)
|
||||||
input#iceServers(type="hidden" value="#{JSON.stringify(iceServers)}")
|
input#iceServers(type="hidden" value=JSON.stringify(iceServers))
|
||||||
|
|
||||||
div#container
|
div#container
|
||||||
|
|
||||||
script(src='../js/index.js')
|
script(src='../static/index.js')
|
||||||
@ -9,10 +9,10 @@ html
|
|||||||
meta(name="apple-mobile-web-app-capable" content="yes")
|
meta(name="apple-mobile-web-app-capable" content="yes")
|
||||||
link(rel="apple-touch-icon" href="res/icon.png")
|
link(rel="apple-touch-icon" href="res/icon.png")
|
||||||
link(rel="icon" sizes="256x256" href="res/icon.png")
|
link(rel="icon" sizes="256x256" href="res/icon.png")
|
||||||
link(rel="stylesheet" type="text/css" href="css/main.css")
|
link(rel="stylesheet" type="text/css" href="static/style.css")
|
||||||
|
|
||||||
body
|
body
|
||||||
include ./_fork.jade
|
include ./_fork.pug
|
||||||
|
|
||||||
div#container
|
div#container
|
||||||
|
|
||||||
Loading…
x
Reference in New Issue
Block a user